<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="com.pandoli365.bibimbap.data.OperatorView" %>
<%@ page import="com.pandoli365.bibimbap.data.PermissionData" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<%@ page import="java.util.Collections" %>
<%@ page import="java.util.List" %>
<%
    String ctx = request.getContextPath();

    Object rawOperators = request.getAttribute("operators");
    List<OperatorView> operators = rawOperators instanceof List<?> ? (List<OperatorView>) rawOperators : Collections.<OperatorView>emptyList();

    Object rawCatalog = request.getAttribute("catalog");
    List<PermissionData> catalog = rawCatalog instanceof List<?> ? (List<PermissionData>) rawCatalog : Collections.<PermissionData>emptyList();

    Object rawCsrf = request.getAttribute("csrfToken");
    String csrfToken = rawCsrf == null ? "" : String.valueOf(rawCsrf);
    String csrfTokenHtml = HtmlUtils.htmlEscape(csrfToken);
    // JS 문자열 컨텍스트용: 따옴표/역슬래시/스크립트 종료 시퀀스 차단
    String csrfTokenJs = csrfToken
            .replace("\\", "\\\\")
            .replace("'", "\\'")
            .replace("\"", "\\\"")
            .replace("<", "\\u003C")
            .replace(">", "\\u003E")
            .replace("\r", "")
            .replace("\n", "");
%>
<!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: 72rem;
        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;
        letter-spacing: 0;
      }
      .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;
        letter-spacing: 0;
      }
      .admin-appoint {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        align-items: flex-end;
      }
      .admin-field {
        display: grid;
        gap: 0.375rem;
      }
      .admin-field label {
        font-size: 0.8125rem;
        font-weight: 700;
        color: var(--text);
      }
      .admin-field input {
        height: 3rem;
        min-width: 16rem;
        box-sizing: border-box;
        padding: 0 0.875rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--field-bg);
        color: var(--text);
        font-size: 1rem;
      }
      .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;
      }
      .admin-perm-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 0.35rem;
        margin: 0;
        padding: 0;
        list-style: none;
      }
      .admin-perm-tags li {
        padding: 0.15rem 0.5rem;
        border-radius: 999px;
        background: var(--accent-soft);
        color: var(--accent);
        font-size: 0.75rem;
        font-weight: 800;
      }
      .admin-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.35rem;
      }
      .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-catalog {
        margin: 0;
        padding: 0;
        list-style: none;
        display: grid;
        gap: 0.5rem;
      }
      .admin-catalog li {
        display: flex;
        gap: 0.75rem;
        align-items: baseline;
        padding: 0.5rem 0.65rem;
        border: 1px solid var(--border);
        border-radius: 10px;
      }
      .admin-catalog code {
        font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
        font-size: 0.8125rem;
        color: var(--accent);
      }
      .admin-catalog .admin-inactive {
        color: var(--text-muted);
        font-size: 0.75rem;
        font-weight: 800;
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <main class="admin-page">
        <section class="admin-hero" aria-labelledby="admin-title">
            <p class="admin-hero__eyebrow">ADMIN CONSOLE</p>
            <h1 id="admin-title">관리자 콘솔</h1>
            <p>운영진 임명, 권한 토글, 강등을 관리합니다. 실제 권한 검증은 서버에서 수행됩니다.</p>
        </section>

        <section class="admin-section" aria-labelledby="admin-appoint-title">
            <h2 id="admin-appoint-title">SUBADMIN 임명</h2>
            <form class="admin-appoint" id="admin-appoint-form" autocomplete="off">
                <input type="hidden" name="_csrf" value="<%= csrfTokenHtml %>" />
                <div class="admin-field">
                    <label for="admin-appoint-user-id">사용자 ID</label>
                    <input type="text" id="admin-appoint-user-id" name="userId" inputmode="numeric" placeholder="대상 사용자 ID" required />
                </div>
                <button class="admin-btn admin-btn--primary" type="submit">SUBADMIN 임명</button>
            </form>
        </section>

        <section class="admin-section" aria-labelledby="admin-operators-title">
            <h2 id="admin-operators-title">운영진 목록</h2>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th scope="col">표시 이름</th>
                        <th scope="col">역할</th>
                        <th scope="col">보유 권한</th>
                        <th scope="col">액션</th>
                    </tr>
                </thead>
                <tbody>
                    <%
                        for (OperatorView op : operators) {
                            if (op == null || op.getUserId() == null) {
                                continue;
                            }
                            String opUserId = String.valueOf(op.getUserId());
                            String opUserIdAttr = HtmlUtils.htmlEscape(opUserId);
                            String opDisplayName = HtmlUtils.htmlEscape(op.getDisplayName() == null || op.getDisplayName().isBlank() ? "(이름 없음)" : op.getDisplayName());
                            String rawRole = op.getRole() == null ? "" : op.getRole();
                            String opRole = HtmlUtils.htmlEscape(rawRole.isBlank() ? "(역할 없음)" : rawRole);
                            boolean isSubadmin = "SUBADMIN".equals(rawRole);
                            boolean isAdmin = "ADMIN".equals(rawRole);
                            List<String> permKeys = op.getPermissionKeys() == null ? Collections.<String>emptyList() : op.getPermissionKeys();
                    %>
                    <tr>
                        <td><%= opDisplayName %></td>
                        <td><%= opRole %></td>
                        <td>
                            <%
                                if (permKeys.isEmpty()) {
                            %>
                            <span class="admin-muted">(없음)</span>
                            <%
                                } else {
                            %>
                            <ul class="admin-perm-tags">
                                <%
                                    for (String key : permKeys) {
                                        if (key == null) {
                                            continue;
                                        }
                                %>
                                <li><%= HtmlUtils.htmlEscape(key) %></li>
                                <%
                                    }
                                %>
                            </ul>
                            <%
                                }
                            %>
                        </td>
                        <td>
                            <%
                                if (isAdmin) {
                            %>
                            <span class="admin-muted">부트스트랩 관리자 (변경 불가)</span>
                            <%
                                } else if (isSubadmin) {
                            %>
                            <div class="admin-actions">
                                <%
                                    for (PermissionData p : catalog) {
                                        if (p == null || p.getPermissionKey() == null) {
                                            continue;
                                        }
                                        String permKey = p.getPermissionKey();
                                        String permKeyAttr = HtmlUtils.htmlEscape(permKey);
                                        String permLabel = HtmlUtils.htmlEscape(p.getDisplayName() == null || p.getDisplayName().isBlank() ? permKey : p.getDisplayName());
                                        boolean held = permKeys.contains(permKey);
                                %>
                                <button class="admin-btn" type="button"
                                        data-action="toggle"
                                        data-user-id="<%= opUserIdAttr %>"
                                        data-permission-key="<%= permKeyAttr %>">
                                    <%= held ? "해제: " : "부여: " %><%= permLabel %>
                                </button>
                                <%
                                    }
                                %>
                                <button class="admin-btn admin-btn--danger" type="button"
                                        data-action="demote"
                                        data-user-id="<%= opUserIdAttr %>">강등</button>
                            </div>
                            <%
                                } else {
                            %>
                            <span class="admin-muted">-</span>
                            <%
                                }
                            %>
                        </td>
                    </tr>
                    <%
                        }
                        if (operators.isEmpty()) {
                    %>
                    <tr>
                        <td colspan="4"><span class="admin-muted">등록된 운영진이 없습니다.</span></td>
                    </tr>
                    <%
                        }
                    %>
                </tbody>
            </table>
        </section>

        <section class="admin-section" aria-labelledby="admin-catalog-title">
            <h2 id="admin-catalog-title">권한 카탈로그</h2>
            <%
                if (catalog.isEmpty()) {
            %>
            <span class="admin-muted">등록된 권한이 없습니다.</span>
            <%
                } else {
            %>
            <ul class="admin-catalog">
                <%
                    for (PermissionData p : catalog) {
                        if (p == null || p.getPermissionKey() == null) {
                            continue;
                        }
                        String permKey = HtmlUtils.htmlEscape(p.getPermissionKey());
                        String permLabel = HtmlUtils.htmlEscape(p.getDisplayName() == null || p.getDisplayName().isBlank() ? p.getPermissionKey() : p.getDisplayName());
                        boolean active = Boolean.TRUE.equals(p.getIsActive());
                %>
                <li>
                    <code><%= permKey %></code>
                    <span><%= permLabel %></span>
                    <%
                        if (!active) {
                    %>
                    <span class="admin-inactive">비활성</span>
                    <%
                        }
                    %>
                </li>
                <%
                    }
                %>
            </ul>
            <%
                }
            %>
        </section>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var ctx = '<%= ctx %>';
  var CSRF_TOKEN = '<%= csrfTokenJs %>';

  function notify(message) {
    if (window.BibimbapModal && typeof window.BibimbapModal.alert === 'function') {
      window.BibimbapModal.alert({ title: '관리자 콘솔', message: message });
      return;
    }
    alert(message);
  }

  function post(url) {
    return fetch(url, {
      method: 'POST',
      headers: {
        'X-CSRF-Token': CSRF_TOKEN,
        'Accept': 'application/json'
      }
    });
  }

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

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

  function appoint(userId) {
    if (!userId) {
      notify('사용자 ID를 입력해 주세요.');
      return;
    }
    post(ctx + '/admin/users/' + encodeURIComponent(userId) + '/appoint')
      .then(handleResult)
      .catch(handleError);
  }

  function toggle(userId, key) {
    post(ctx + '/admin/users/' + encodeURIComponent(userId) + '/permissions/' + encodeURIComponent(key) + '/toggle')
      .then(handleResult)
      .catch(handleError);
  }

  function demote(userId) {
    post(ctx + '/admin/users/' + encodeURIComponent(userId) + '/demote')
      .then(handleResult)
      .catch(handleError);
  }

  // operators 조회 (GET) — 외부에서 재사용 가능하도록 노출
  function fetchOperators() {
    return fetch(ctx + '/admin/operators', {
      method: 'GET',
      headers: { 'Accept': 'application/json' }
    });
  }
  window.BibimbapAdminConsole = { fetchOperators: fetchOperators };

  var appointForm = document.getElementById('admin-appoint-form');
  if (appointForm) {
    appointForm.addEventListener('submit', function (ev) {
      ev.preventDefault();
      var input = document.getElementById('admin-appoint-user-id');
      appoint(input ? input.value.trim() : '');
    });
  }

  // data-* 속성 + 위임 핸들러 (inline 핸들러에 사용자 데이터 삽입 금지)
  document.addEventListener('click', function (ev) {
    var btn = ev.target.closest('[data-action]');
    if (!btn) {
      return;
    }
    var action = btn.getAttribute('data-action');
    var userId = btn.getAttribute('data-user-id');
    if (action === 'toggle') {
      toggle(userId, btn.getAttribute('data-permission-key'));
    } else if (action === 'demote') {
      demote(userId);
    }
  });
})();
    </script>
</body>
</html>
