<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<%@ page import="com.pandoli365.bibimbap.data.PostCategoryData" %>
<%@ page import="java.util.Collections" %>
<%@ page import="java.util.List" %>
<%
    String ctx = request.getContextPath();
    List<PostCategoryData> categories = Collections.emptyList();
    Object categoriesAttr = request.getAttribute("categories");
    if (categoriesAttr instanceof List<?>) { categories = (List<PostCategoryData>) categoriesAttr; }
    String csrfToken = (String) request.getAttribute("csrfToken");
    String csrfTokenHtml = HtmlUtils.htmlEscape(csrfToken == null ? "" : csrfToken);
%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" content="<%= csrfTokenHtml %>">
    <jsp:include page="/WEB-INF/views/theme-init.jsp"/>
    <title>포스트 카테고리 관리 | bibimbap</title>
    <style>
      html {
        color-scheme: light;
        --surface: #faf8f5;
        --card-bg: #fff;
        --text: #1a1a1a;
        --text-muted: #5c5c5c;
        --accent: #e8a54b;
        --accent-soft: rgba(232, 165, 75, 0.16);
        --border: rgba(0, 0, 0, 0.08);
        --shadow: rgba(0, 0, 0, 0.06);
        --field-bg: #fff;
        --button-text: #1a1a1a;
      }
      html[data-theme="dark"] {
        color-scheme: dark;
        --surface: #121212;
        --card-bg: #1e1e1e;
        --text: #ece8e1;
        --text-muted: #a39e96;
        --border: rgba(255, 255, 255, 0.1);
        --shadow: rgba(0, 0, 0, 0.35);
        --field-bg: #181818;
        --button-text: #1a1a1a;
      }
      body {
        margin: 0;
        min-height: 100vh;
        font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Noto Sans KR", sans-serif;
        background: var(--surface);
        color: var(--text);
      }
      .admin-page {
        max-width: 78rem;
        margin: 0 auto;
        padding: 1.5rem max(1rem, env(safe-area-inset-left)) 3rem max(1rem, env(safe-area-inset-right));
      }
      .admin-hero { margin-bottom: 1.5rem; }
      .admin-hero__eyebrow {
        margin: 0 0 0.35rem;
        color: var(--accent);
        font-size: 0.75rem;
        font-weight: 900;
      }
      .admin-hero h1 { margin: 0; font-size: 1.9rem; line-height: 1.2; }
      .admin-hero p { margin: 0.45rem 0 0; color: var(--text-muted); line-height: 1.6; }
      .admin-section {
        margin-bottom: 2rem;
        padding: 1.25rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 2px 8px var(--shadow);
      }
      .admin-section h2 { margin: 0 0 1rem; font-size: 1.15rem; }
      .admin-form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
        gap: 0.9rem;
      }
      .admin-field { display: grid; gap: 0.375rem; }
      .admin-field label { font-size: 0.8125rem; font-weight: 700; color: var(--text); }
      .admin-field input {
        box-sizing: border-box;
        height: 3rem;
        padding: 0.7rem 0.875rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--field-bg);
        color: var(--text);
        font: inherit;
        font-size: 1rem;
      }
      .admin-form-actions { margin-top: 1rem; }
      .admin-table-wrap { overflow-x: auto; }
      .admin-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
      .admin-table th, .admin-table td {
        padding: 0.65rem 0.5rem;
        border-bottom: 1px solid var(--border);
        text-align: left;
        vertical-align: top;
      }
      .admin-table th {
        color: var(--text-muted);
        font-size: 0.8125rem;
        font-weight: 800;
        white-space: nowrap;
      }
      .admin-actions { display: flex; flex-wrap: wrap; gap: 0.35rem; align-items: center; }
      .admin-btn {
        min-height: 2.25rem;
        padding: 0 0.85rem;
        border: 1px solid var(--border);
        border-radius: 10px;
        background: var(--card-bg);
        color: var(--text);
        font: inherit;
        font-size: 0.8125rem;
        font-weight: 800;
        cursor: pointer;
      }
      .admin-btn:hover { border-color: rgba(232, 165, 75, 0.45); }
      .admin-btn--primary { border-color: transparent; background: var(--accent); color: var(--button-text); }
      .admin-btn--danger { border-color: rgba(200, 60, 60, 0.45); color: #c83c3c; }
      .admin-muted { color: var(--text-muted); font-size: 0.8125rem; }
      .admin-status {
        display: inline-flex;
        align-items: center;
        padding: 0.15rem 0.55rem;
        border-radius: 999px;
        background: var(--accent-soft);
        color: var(--accent);
        font-size: 0.75rem;
        font-weight: 800;
      }
      .admin-input-inline {
        box-sizing: border-box;
        min-height: 2.25rem;
        max-width: 9rem;
        padding: 0 0.5rem;
        border: 1px solid var(--border);
        border-radius: 10px;
        background: var(--field-bg);
        color: var(--text);
        font: inherit;
        font-size: 0.8125rem;
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <main class="admin-page">
        <section class="admin-hero">
            <p class="admin-hero__eyebrow">POST CATEGORY ADMIN</p>
            <h1>포스트 카테고리 관리</h1>
            <p>포스트 카테고리를 등록·수정·비활성화합니다. 소속 포스트가 있는 카테고리는 삭제할 수 없으며 비활성화를 권장합니다.</p>
        </section>

        <section class="admin-section">
            <h2>신규 카테고리 등록</h2>
            <form id="category-create-form" autocomplete="off">
                <input type="hidden" name="_csrf" value="<%= csrfTokenHtml %>" />
                <div class="admin-form-grid">
                    <div class="admin-field">
                        <label for="cat-name">이름 (필수)</label>
                        <input type="text" id="cat-name" name="name" maxlength="80" placeholder="카테고리 이름" required />
                    </div>
                    <div class="admin-field">
                        <label for="cat-slug">슬러그 (필수)</label>
                        <input type="text" id="cat-slug" name="slug" maxlength="80" placeholder="slug" required />
                    </div>
                    <div class="admin-field">
                        <label for="cat-sort">정렬 순서</label>
                        <input type="number" id="cat-sort" name="sortOrder" step="1" value="0" />
                    </div>
                </div>
                <div class="admin-form-actions">
                    <button class="admin-btn admin-btn--primary" type="submit" data-action="create">카테고리 등록</button>
                </div>
            </form>
        </section>

        <section class="admin-section">
            <h2>카테고리 목록</h2>
            <div class="admin-table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th scope="col">이름</th>
                            <th scope="col">슬러그</th>
                            <th scope="col">정렬</th>
                            <th scope="col">활성</th>
                            <th scope="col">액션</th>
                        </tr>
                    </thead>
                    <tbody>
                        <% if (categories.isEmpty()) { %>
                            <tr>
                                <td colspan="5"><span class="admin-muted">등록된 카테고리가 없습니다.</span></td>
                            </tr>
                        <% } else {
                            for (PostCategoryData cat : categories) {
                                boolean catActive = Boolean.TRUE.equals(cat.getIsActive());
                                String catSortOrder = cat.getSortOrder() == null ? "" : String.valueOf(cat.getSortOrder());
                        %>
                            <tr>
                                <td><%= HtmlUtils.htmlEscape(cat.getName() == null ? "" : cat.getName()) %></td>
                                <td><%= HtmlUtils.htmlEscape(cat.getSlug() == null ? "" : cat.getSlug()) %></td>
                                <td><%= HtmlUtils.htmlEscape(catSortOrder) %></td>
                                <td>
                                    <% if (catActive) { %><span class="admin-status">활성</span><% } else { %><span class="admin-muted">비활성</span><% } %>
                                </td>
                                <td>
                                    <div class="admin-actions">
                                        <input type="number" class="admin-input-inline"
                                               data-edit-sort="<%= cat.getId() %>"
                                               value="<%= HtmlUtils.htmlEscape(catSortOrder) %>"
                                               step="1" aria-label="정렬 순서 수정" />
                                        <button class="admin-btn" type="button"
                                                data-action="save-sort"
                                                data-cat-id="<%= cat.getId() %>">정렬 저장</button>
                                        <button class="admin-btn" type="button"
                                                data-action="toggle"
                                                data-cat-id="<%= cat.getId() %>"
                                                data-active="<%= catActive %>">
                                            <%= catActive ? "비활성화" : "활성화" %>
                                        </button>
                                        <button class="admin-btn admin-btn--danger" type="button"
                                                data-action="delete"
                                                data-cat-id="<%= cat.getId() %>">삭제</button>
                                    </div>
                                </td>
                            </tr>
                        <%      }
                           } %>
                    </tbody>
                </table>
            </div>
        </section>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var ctx = document.querySelector('base') ? '' : '';
  var meta = document.querySelector('meta[name="_csrf"]');
  var CSRF_TOKEN = meta ? meta.getAttribute('content') : '';
  var BASE = '/admin/post-categories';

  function notify(message) {
    if (window.BibimbapModal && typeof window.BibimbapModal.alert === 'function') {
      window.BibimbapModal.alert({ title: '포스트 카테고리 관리', message: message });
      return;
    }
    alert(message);
  }

  function post(url, params) {
    var options = {
      method: 'POST',
      headers: {
        'X-CSRF-Token': CSRF_TOKEN,
        'Accept': 'application/json'
      }
    };
    if (!params) {
      params = new URLSearchParams();
    }
    params.set('_csrf', CSRF_TOKEN);
    options.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    options.body = params.toString();
    return fetch(url, options);
  }

  function handleResult(res) {
    if (res.ok) {
      window.location.reload();
      return;
    }
    res.json().then(function (data) {
      notify((data && data.message) ? data.message : ('요청을 처리하지 못했습니다. (상태 ' + res.status + ')'));
    }).catch(function () {
      notify('요청을 처리하지 못했습니다. (상태 ' + res.status + ')');
    });
  }

  function handleError() {
    notify('요청 중 오류가 발생했습니다.');
  }

  function createCategory() {
    var name = (document.getElementById('cat-name').value || '').trim();
    var slug = (document.getElementById('cat-slug').value || '').trim();
    var sort = (document.getElementById('cat-sort').value || '').trim();
    if (!name || !slug) {
      notify('이름과 슬러그를 입력해 주세요.');
      return;
    }
    var params = new URLSearchParams();
    params.set('name', name);
    params.set('slug', slug);
    if (sort) {
      params.set('sortOrder', sort);
    }
    post(BASE, params).then(handleResult).catch(handleError);
  }

  function saveSort(catId) {
    var input = document.querySelector('[data-edit-sort="' + catId + '"]');
    var sort = input ? input.value.trim() : '';
    var params = new URLSearchParams();
    params.set('sortOrder', sort === '' ? '0' : sort);
    post(BASE + '/' + encodeURIComponent(catId), params).then(handleResult).catch(handleError);
  }

  function toggleActive(catId, currentActive) {
    var params = new URLSearchParams();
    params.set('isActive', currentActive === 'true' ? 'false' : 'true');
    post(BASE + '/' + encodeURIComponent(catId), params).then(handleResult).catch(handleError);
  }

  function removeCategory(catId) {
    if (!window.confirm('이 카테고리를 삭제하시겠습니까? 소속 포스트가 있으면 삭제할 수 없습니다.')) {
      return;
    }
    post(BASE + '/' + encodeURIComponent(catId) + '/delete').then(handleResult).catch(handleError);
  }

  var form = document.getElementById('category-create-form');
  if (form) {
    form.addEventListener('submit', function (ev) {
      ev.preventDefault();
      createCategory();
    });
  }

  document.addEventListener('click', function (ev) {
    var btn = ev.target.closest('[data-action]');
    if (!btn) {
      return;
    }
    var action = btn.getAttribute('data-action');
    var catId = btn.getAttribute('data-cat-id');
    if (action === 'save-sort' && catId) {
      saveSort(catId);
    } else if (action === 'toggle' && catId) {
      toggleActive(catId, btn.getAttribute('data-active'));
    } else if (action === 'delete' && catId) {
      removeCategory(catId);
    }
  });
})();
    </script>
</body>
</html>
