{% extends "_base.html" %}

{% block title %}頁面管理 - MES Dashboard{% endblock %}

{% block head_extra %}
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft JhengHei', Arial, sans-serif;
            background: #f5f7fa;
            color: #222;
        }

        .shell {
            max-width: 1320px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 24px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-left h1 {
            font-size: 24px;
            margin-bottom: 4px;
        }

        .header-left p {
            font-size: 14px;
            opacity: 0.9;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .admin-info {
            text-align: right;
            font-size: 14px;
        }

        .admin-info .name {
            font-weight: 600;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            transition: background 0.2s ease;
        }

        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .panel {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            margin-bottom: 16px;
        }

        .panel-header {
            padding: 16px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 16px;
        }

        .panel-header h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .panel-subtitle {
            font-size: 13px;
            color: #64748b;
        }

        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 14px 16px;
            text-align: left;
            border-bottom: 1px solid #eee;
            vertical-align: middle;
        }

        th {
            background: #f8f9fa;
            font-weight: 600;
            font-size: 14px;
            color: #555;
        }

        td {
            font-size: 14px;
        }

        tr:hover {
            background: #fafbfc;
        }

        .route-cell {
            font-family: 'Consolas', 'Monaco', monospace;
            color: #555;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            border: none;
        }

        .status-released {
            background: #e8f5e9;
            color: #2e7d32;
        }

        .status-dev {
            background: #fff3e0;
            color: #e65100;
        }

        .status-badge:hover {
            transform: scale(1.05);
        }

        .input {
            width: 100%;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 13px;
            background: #fff;
            color: #1e293b;
        }

        .input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .order-input {
            width: 96px;
        }

        .drawer-create {
            padding: 14px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            align-items: center;
            background: #f8fafc;
        }

        .checkbox-label {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            color: #475569;
            font-size: 13px;
            white-space: nowrap;
        }

        .action-btn {
            border: 1px solid #d0d7e3;
            border-radius: 6px;
            padding: 6px 10px;
            background: #fff;
            color: #334155;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s ease;
        }

        .action-btn:hover {
            border-color: #94a3b8;
            background: #f8fafc;
        }

        .action-btn.primary {
            border-color: #667eea;
            background: #667eea;
            color: #fff;
        }

        .action-btn.primary:hover {
            background: #5668d8;
            border-color: #5668d8;
        }

        .action-btn.danger {
            border-color: #ef4444;
            color: #b91c1c;
            background: #fff5f5;
        }

        .action-btn.danger:hover {
            background: #fee2e2;
        }

        .actions-cell {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .back-link {
            display: inline-block;
            margin-top: 16px;
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
        }

        .back-link:hover {
            text-decoration: underline;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="shell">
        <div class="header">
            <div class="header-left">
                <h1>頁面管理</h1>
                <p>管理頁面狀態、抽屜分類與排序（Released：所有人可見 / Dev：僅管理員可見）</p>
            </div>
            <div class="header-right">
                {% if admin_user %}
                <div class="admin-info">
                    <div class="name">{{ admin_user.displayName }}</div>
                    <div>{{ admin_user.mail }}</div>
                </div>
                {% endif %}
                <a href="{{ url_for('auth.logout') }}" class="logout-btn">登出</a>
            </div>
        </div>

        <div class="panel">
            <div class="panel-header">
                <div>
                    <h2>抽屜管理</h2>
                    <div class="panel-subtitle">可新增、改名、排序、設定 admin-only，空抽屜才能刪除</div>
                </div>
            </div>
            <div class="drawer-create">
                <input id="new-drawer-name" class="input" type="text" placeholder="新抽屜名稱（例如：自訂分類）">
                <input id="new-drawer-order" class="input order-input" type="number" min="1" placeholder="排序">
                <label class="checkbox-label">
                    <input id="new-drawer-admin-only" type="checkbox">
                    僅管理員可見
                </label>
                <button id="create-drawer-btn" class="action-btn primary">新增抽屜</button>
            </div>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名稱</th>
                            <th>排序</th>
                            <th>可見性</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="drawers-tbody">
                        <tr>
                            <td colspan="5" class="loading">載入中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="panel">
            <div class="panel-header">
                <div>
                    <h2>所有頁面</h2>
                    <div class="panel-subtitle">可切換 Released/Dev，並設定抽屜歸屬與抽屜內排序</div>
                </div>
            </div>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>路由</th>
                            <th>名稱</th>
                            <th>狀態</th>
                            <th>抽屜歸屬</th>
                            <th>排序</th>
                        </tr>
                    </thead>
                    <tbody id="pages-tbody">
                        <tr>
                            <td colspan="5" class="loading">載入中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <a href="{{ url_for('portal_index') }}" class="back-link">返回首頁</a>
    </div>
{% endblock %}

{% block scripts %}
    <script>
        const pagesTbody = document.getElementById('pages-tbody');
        const drawersTbody = document.getElementById('drawers-tbody');
        const createDrawerBtn = document.getElementById('create-drawer-btn');
        const newDrawerNameInput = document.getElementById('new-drawer-name');
        const newDrawerOrderInput = document.getElementById('new-drawer-order');
        const newDrawerAdminOnlyInput = document.getElementById('new-drawer-admin-only');
        const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content || '';

        let drawersCache = [];
        let pagesCache = [];

        function withCsrfHeaders(headers = {}) {
            return csrfToken ? { ...headers, 'X-CSRF-Token': csrfToken } : headers;
        }

        function escapeHtml(value) {
            const div = document.createElement('div');
            div.textContent = value ?? '';
            return div.innerHTML;
        }

        function escapeAttr(value) {
            return escapeHtml(String(value ?? '')).replace(/\"/g, '&quot;');
        }

        async function parseJsonResponse(response) {
            try {
                return await response.json();
            } catch (error) {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                throw error;
            }
        }

        async function apiFetch(url, options = {}) {
            const config = { ...options };
            config.headers = withCsrfHeaders(config.headers || {});
            const response = await fetch(url, config);
            const data = await parseJsonResponse(response);
            if (!response.ok || data.success === false) {
                throw new Error(data.error || `HTTP ${response.status}`);
            }
            return data;
        }

        function drawerOptionsHtml(selectedDrawerId) {
            const normalized = selectedDrawerId || '';
            const options = ['<option value="">未分類</option>'];
            drawersCache.forEach((drawer) => {
                const selected = drawer.id === normalized ? 'selected' : '';
                options.push(
                    `<option value="${escapeAttr(drawer.id)}" ${selected}>${escapeHtml(drawer.name)}</option>`
                );
            });
            return options.join('');
        }

        function renderDrawers(drawers) {
            if (!drawers || drawers.length === 0) {
                drawersTbody.innerHTML = '<tr><td colspan="5" class="loading">尚無抽屜</td></tr>';
                return;
            }

            drawersTbody.innerHTML = drawers.map((drawer) => `
                <tr data-drawer-id="${escapeAttr(drawer.id)}">
                    <td class="route-cell">${escapeHtml(drawer.id)}</td>
                    <td><input class="input drawer-name-input" type="text" value="${escapeAttr(drawer.name)}"></td>
                    <td><input class="input order-input drawer-order-input" type="number" min="1" value="${escapeAttr(String(drawer.order ?? ''))}"></td>
                    <td>
                        <label class="checkbox-label">
                            <input class="drawer-admin-only-input" type="checkbox" ${drawer.admin_only ? 'checked' : ''}>
                            僅管理員
                        </label>
                    </td>
                    <td class="actions-cell">
                        <button class="action-btn" data-action="save-drawer">儲存</button>
                        <button class="action-btn danger" data-action="delete-drawer">刪除</button>
                    </td>
                </tr>
            `).join('');
        }

        function renderPages(pages) {
            if (!pages || pages.length === 0) {
                pagesTbody.innerHTML = '<tr><td colspan="5" class="loading">尚無頁面設定</td></tr>';
                return;
            }

            pagesTbody.innerHTML = pages.map((page) => `
                <tr data-route="${escapeAttr(page.route)}">
                    <td class="route-cell">${escapeHtml(page.route)}</td>
                    <td>${escapeHtml(page.name)}</td>
                    <td>
                        <button class="status-badge status-${page.status}" data-action="toggle-status">
                            ${page.status === 'released' ? 'Released' : 'Dev'}
                        </button>
                    </td>
                    <td>
                        <select class="input drawer-select">
                            ${drawerOptionsHtml(page.drawer_id)}
                        </select>
                    </td>
                    <td>
                        <input
                            class="input order-input page-order-input"
                            type="number"
                            min="1"
                            value="${escapeAttr(String(page.order ?? ''))}"
                            placeholder="未設定"
                        >
                    </td>
                </tr>
            `).join('');
        }

        async function loadDrawers() {
            const data = await apiFetch('/admin/api/drawers');
            drawersCache = data.drawers || [];
            renderDrawers(drawersCache);
            renderPages(pagesCache);
        }

        async function loadPages() {
            const data = await apiFetch('/admin/api/pages');
            pagesCache = data.pages || [];
            renderPages(pagesCache);
        }

        async function refreshAll() {
            await loadDrawers();
            await loadPages();
        }

        async function createDrawer() {
            const name = newDrawerNameInput.value.trim();
            const orderRaw = newDrawerOrderInput.value.trim();
            const adminOnly = newDrawerAdminOnlyInput.checked;

            if (!name) {
                window.MES?.toast?.error?.('請輸入抽屜名稱');
                return;
            }

            const payload = {
                name,
                admin_only: adminOnly,
            };
            if (orderRaw !== '') {
                payload.order = Number(orderRaw);
            }

            try {
                await apiFetch('/admin/api/drawers', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload),
                });
                window.MES?.toast?.success?.(`已新增抽屜：${name}`);
                newDrawerNameInput.value = '';
                newDrawerOrderInput.value = '';
                newDrawerAdminOnlyInput.checked = false;
                await refreshAll();
            } catch (error) {
                window.MES?.toast?.error?.(`新增抽屜失敗: ${error.message}`);
            }
        }

        async function saveDrawerFromRow(row) {
            const drawerId = row.dataset.drawerId;
            const name = row.querySelector('.drawer-name-input')?.value.trim() || '';
            const orderRaw = row.querySelector('.drawer-order-input')?.value.trim() || '';
            const adminOnly = row.querySelector('.drawer-admin-only-input')?.checked || false;

            if (!drawerId) {
                return;
            }

            const payload = { name, admin_only: adminOnly };
            if (orderRaw !== '') {
                payload.order = Number(orderRaw);
            }

            try {
                await apiFetch(`/admin/api/drawers/${encodeURIComponent(drawerId)}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload),
                });
                window.MES?.toast?.success?.(`已更新抽屜：${drawerId}`);
                await refreshAll();
            } catch (error) {
                window.MES?.toast?.error?.(`更新抽屜失敗: ${error.message}`);
            }
        }

        async function deleteDrawerById(drawerId) {
            if (!drawerId) {
                return;
            }
            if (!window.confirm(`確定刪除抽屜「${drawerId}」？`)) {
                return;
            }

            try {
                await apiFetch(`/admin/api/drawers/${encodeURIComponent(drawerId)}`, {
                    method: 'DELETE',
                });
                window.MES?.toast?.success?.(`已刪除抽屜：${drawerId}`);
                await refreshAll();
            } catch (error) {
                window.MES?.toast?.error?.(`刪除抽屜失敗: ${error.message}`);
            }
        }

        async function updatePage(route, payload, successMessage) {
            try {
                await apiFetch(`/admin/api/pages${route}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload),
                });
                if (successMessage) {
                    window.MES?.toast?.success?.(successMessage);
                }
                await loadPages();
            } catch (error) {
                window.MES?.toast?.error?.(`更新頁面失敗: ${error.message}`);
                await loadPages();
            }
        }

        async function togglePageStatus(route, currentStatus) {
            const nextStatus = currentStatus === 'released' ? 'dev' : 'released';
            await updatePage(route, { status: nextStatus }, `已更新: ${route} → ${nextStatus}`);
        }

        pagesTbody.addEventListener('click', async (event) => {
            const button = event.target.closest('button[data-action="toggle-status"]');
            if (!button) {
                return;
            }
            const row = button.closest('tr[data-route]');
            if (!row) {
                return;
            }
            const route = row.dataset.route;
            const currentStatus = button.classList.contains('status-released') ? 'released' : 'dev';
            if (route) {
                await togglePageStatus(route, currentStatus);
            }
        });

        pagesTbody.addEventListener('change', async (event) => {
            const row = event.target.closest('tr[data-route]');
            if (!row) {
                return;
            }
            const route = row.dataset.route;
            if (!route) {
                return;
            }

            if (event.target.classList.contains('drawer-select')) {
                const drawerId = event.target.value || null;
                await updatePage(route, { drawer_id: drawerId }, `已更新抽屜歸屬: ${route}`);
                return;
            }

            if (event.target.classList.contains('page-order-input')) {
                const value = event.target.value.trim();
                const payload = { order: value === '' ? null : Number(value) };
                await updatePage(route, payload, `已更新排序: ${route}`);
            }
        });

        drawersTbody.addEventListener('click', async (event) => {
            const button = event.target.closest('button[data-action]');
            if (!button) {
                return;
            }

            const row = button.closest('tr[data-drawer-id]');
            if (!row) {
                return;
            }

            const drawerId = row.dataset.drawerId;
            if (button.dataset.action === 'save-drawer') {
                await saveDrawerFromRow(row);
                return;
            }
            if (button.dataset.action === 'delete-drawer') {
                await deleteDrawerById(drawerId);
            }
        });

        createDrawerBtn.addEventListener('click', createDrawer);
        newDrawerNameInput.addEventListener('keydown', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                createDrawer();
            }
        });

        refreshAll().catch((error) => {
            pagesTbody.innerHTML = `<tr><td colspan="5" class="loading">載入失敗: ${escapeHtml(error.message)}</td></tr>`;
            drawersTbody.innerHTML = `<tr><td colspan="5" class="loading">載入失敗: ${escapeHtml(error.message)}</td></tr>`;
            window.MES?.toast?.error?.(`載入失敗: ${error.message}`);
        });
    </script>
{% endblock %}
