<?php ob_start(); ?>

<div class="content-header">
    <h2><?= __('admin.menus.title') ?></h2>
</div>

<?php foreach ($menus as $menu): ?>
<?php $items = $itemsByMenu[$menu['id']] ?? []; ?>

<div class="form-card" id="menu-<?= (int) $menu['id'] ?>" style="margin-bottom: 2rem;">
    <div class="menu-section-header" style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
        <h4 style="margin:0;"><?= e($menu['name']) ?> <small style="font-weight:normal; color:#888;">(<?= e($menu['location']) ?>)</small></h4>
        <button class="btn btn-sm btn-primary" onclick="toggleAddForm('add-form-<?= (int) $menu['id'] ?>')"><?= __('admin.menus.add_item') ?></button>
    </div>

    <?php if (empty($items)): ?>
    <p class="text-muted" style="margin-bottom:1rem;"><?= __('admin.menus.no_items') ?></p>
    <?php else: ?>
    <div class="table-responsive">
    <table class="data-table" style="margin-bottom:1rem;">
        <thead>
            <tr>
                <th style="width:40px;">#</th>
                <th><?= __('admin.menus.label') ?></th>
                <th><?= __('admin.menus.url') ?></th>
                <th><?= __('admin.menus.target') ?></th>
                <th><?= __('admin.menus.order') ?></th>
                <th><?= __('admin.common.visible') ?></th>
                <th><?= __('admin.common.actions') ?></th>
            </tr>
        </thead>
        <tbody id="sortable-<?= (int) $menu['id'] ?>">
            <?php foreach ($items as $item): ?>
            <tr data-id="<?= (int) $item['id'] ?>">
                <td style="color:#aaa;">☰</td>
                <td><strong><?= e($item['label']) ?></strong></td>
                <td><code><?= e($item['url']) ?></code></td>
                <td><?= e($item['target'] ?? '_self') ?></td>
                <td><?= (int) $item['sort_order'] ?></td>
                <td>
                    <?php if ($item['is_visible']): ?>
                    <span class="badge badge-success"><?= __('admin.common.visible') ?></span>
                    <?php else: ?>
                    <span class="badge badge-draft"><?= __('admin.common.hidden') ?></span>
                    <?php endif; ?>
                </td>
                <td class="actions">
                    <button class="btn btn-sm btn-secondary"
                            onclick="toggleEditForm('edit-row-<?= (int) $item['id'] ?>')"><?= __('admin.common.edit') ?></button>
                    <form method="POST" action="/admin/menus/items/delete/<?= (int) $item['id'] ?>"
                          class="inline-form" onsubmit="return confirm('<?= __('admin.menus.confirm_delete') ?>')">
                        <?= $csrf->field() ?>
                        <button type="submit" class="btn btn-sm btn-danger"><?= __('admin.common.delete') ?></button>
                    </form>
                </td>
            </tr>
            <tr id="edit-row-<?= (int) $item['id'] ?>" class="edit-inline-row" style="display:none;">
                <td colspan="7" style="padding:1rem; background:#f8f9fa;">
                    <form method="POST" action="/admin/menus/items/update/<?= (int) $item['id'] ?>"
                          class="admin-form" style="display:grid; grid-template-columns:1fr 1fr 1fr auto auto auto; gap:.75rem; align-items:end;">
                        <?= $csrf->field() ?>
                        <div class="form-group" style="margin:0;">
                            <label><?= __('admin.menus.label') ?></label>
                            <input type="text" name="label" value="<?= e($item['label']) ?>" required>
                        </div>
                        <div class="form-group" style="margin:0;">
                            <label><?= __('admin.menus.url') ?></label>
                            <input type="text" name="url" value="<?= e($item['url']) ?>" required>
                        </div>
                        <div class="form-group" style="margin:0;">
                            <label><?= __('admin.menus.target') ?></label>
                            <select name="target">
                                <option value="_self"  <?= ($item['target'] ?? '_self') === '_self'  ? 'selected' : '' ?>><?= __('admin.menus.target_self') ?></option>
                                <option value="_blank" <?= ($item['target'] ?? '_self') === '_blank' ? 'selected' : '' ?>><?= __('admin.menus.target_blank') ?></option>
                            </select>
                        </div>
                        <div class="form-group" style="margin:0;">
                            <label><?= __('admin.menus.order') ?></label>
                            <input type="number" name="sort_order" value="<?= (int) $item['sort_order'] ?>" style="width:70px;">
                        </div>
                        <div class="form-group" style="margin:0;">
                            <label><?= __('admin.common.visible') ?></label>
                            <select name="is_visible">
                                <option value="1" <?= $item['is_visible'] ? 'selected' : '' ?>><?= __('admin.common.yes') ?></option>
                                <option value="0" <?= !$item['is_visible'] ? 'selected' : '' ?>><?= __('admin.common.no') ?></option>
                            </select>
                        </div>
                        <div style="display:flex; gap:.5rem; padding-top:1.4rem;">
                            <button type="submit" class="btn btn-sm btn-primary"><?= __('admin.common.save') ?></button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="toggleEditForm('edit-row-<?= (int) $item['id'] ?>')"><?= __('admin.common.cancel') ?></button>
                        </div>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>

    <!-- Menu Preview (Phase 5.1) -->
    <?php if (!empty($items)): ?>
    <?php $visibleItems = array_filter($items, fn($i) => (int)$i['is_visible'] === 1); ?>
    <?php $hiddenCount  = count($items) - count($visibleItems); ?>
    <div class="menu-preview" style="margin-bottom:1rem; padding:.75rem 1rem; background:#f8f9fa; border:1px solid #e5e7eb; border-radius:6px;">
        <div style="font-size:.75rem; font-weight:600; color:#888; text-transform:uppercase; letter-spacing:.05em; margin-bottom:.6rem;">
            <?= __('admin.menus.preview_title') ?>
        </div>
        <nav style="display:flex; flex-wrap:wrap; align-items:center; gap:.25rem;">
            <?php if (empty($visibleItems)): ?>
            <span style="font-size:.85rem; color:#aaa; font-style:italic;"><?= __('admin.menus.no_visible') ?></span>
            <?php else: ?>
            <?php foreach ($visibleItems as $vi): ?>
            <a href="<?= e($vi['url']) ?>"
               target="<?= e($vi['target'] ?? '_self') ?>"
               style="display:inline-block; padding:.35rem .75rem; background:#fff; border:1px solid #d1d5db;
                      border-radius:4px; font-size:.85rem; color:#374151; text-decoration:none;
                      white-space:nowrap;"
               title="<?= e($vi['url']) ?>"
               onclick="return false;"><?= e($vi['label']) ?><?= ($vi['target'] ?? '_self') === '_blank' ? ' <span style="font-size:.7rem;color:#9ca3af;" title="Opens in new tab">↗</span>' : '' ?></a>
            <?php endforeach; ?>
            <?php endif; ?>
            <?php if ($hiddenCount > 0): ?>
            <span style="font-size:.78rem; color:#9ca3af; margin-left:.25rem;"
                  title="<?= $hiddenCount ?> hidden item(s) not shown to visitors">
                + <?= __('admin.menus.hidden_count', [':count' => $hiddenCount]) ?>
            </span>
            <?php endif; ?>
        </nav>
    </div>
    <?php endif; ?>

    <!-- Add item form (hidden by default) -->
    <div id="add-form-<?= (int) $menu['id'] ?>" class="add-item-form" style="display:none; background:#f0f4f8; padding:1rem; border-radius:6px;">
        <h5 style="margin-top:0;"><?= __('admin.menus.add_to_menu', [':menu' => e($menu['name'])]) ?></h5>
        <form method="POST" action="/admin/menus/items/store" class="admin-form"
              style="display:grid; grid-template-columns:1fr 1fr auto auto auto; gap:.75rem; align-items:end;">
            <?= $csrf->field() ?>
            <input type="hidden" name="menu_id" value="<?= (int) $menu['id'] ?>">
            <div class="form-group" style="margin:0;">
                <label><?= __('admin.menus.label') ?> <span style="color:red">*</span></label>
                <input type="text" name="label" placeholder="<?= __('admin.menus.label_placeholder') ?>" required>
            </div>
            <div class="form-group" style="margin:0;">
                <label><?= __('admin.menus.url') ?> <span style="color:red">*</span></label>
                <input type="text" name="url" placeholder="<?= __('admin.menus.url_placeholder') ?>" required>
            </div>
            <div class="form-group" style="margin:0;">
                <label><?= __('admin.menus.target') ?></label>
                <select name="target">
                    <option value="_self"><?= __('admin.menus.target_self') ?></option>
                    <option value="_blank"><?= __('admin.menus.target_blank') ?></option>
                </select>
            </div>
            <div class="form-group" style="margin:0;">
                <label><?= __('admin.common.visible') ?></label>
                <select name="is_visible">
                    <option value="1"><?= __('admin.common.yes') ?></option>
                    <option value="0"><?= __('admin.common.no') ?></option>
                </select>
            </div>
            <div style="display:flex; gap:.5rem; padding-top:1.4rem;">
                <button type="submit" class="btn btn-sm btn-primary"><?= __('admin.menus.add_btn') ?></button>
                <button type="button" class="btn btn-sm btn-secondary"
                        onclick="toggleAddForm('add-form-<?= (int) $menu['id'] ?>')"><?= __('admin.common.cancel') ?></button>
            </div>
        </form>
        <?php if (!empty($pages)): ?>
        <p style="margin:.75rem 0 0; font-size:.85rem; color:#666;">
            <strong><?= __('admin.menus.quick_fill') ?></strong>
            <?php foreach ($pages as $p): ?>
            <button type="button" class="btn btn-sm btn-secondary"
                    style="margin:.2rem;"
                    onclick="prefillAddForm(<?= (int) $menu['id'] ?>, '<?= e(addslashes($p['title'])) ?>', '/<?= e($p['slug']) ?>')">
                <?= e($p['title']) ?>
            </button>
            <?php endforeach; ?>
        </p>
        <?php endif; ?>
    </div>
</div>

<?php endforeach; ?>

<script>
function toggleAddForm(id) {
    const el = document.getElementById(id);
    if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
}

function toggleEditForm(id) {
    const el = document.getElementById(id);
    if (el) el.style.display = el.style.display === 'none' ? 'table-row' : 'none';
}

function prefillAddForm(menuId, label, url) {
    const form = document.querySelector('#add-form-' + menuId + ' form');
    if (!form) return;
    form.querySelector('[name="label"]').value = label;
    form.querySelector('[name="url"]').value = url;
}

// Drag-and-drop reorder (sortable rows within each menu table)
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('[id^="sortable-"]').forEach(function (tbody) {
        const menuId = tbody.id.replace('sortable-', '');
        let dragged = null;

        tbody.querySelectorAll('tr[data-id]').forEach(function (row) {
            row.setAttribute('draggable', 'true');
            row.style.cursor = 'grab';

            row.addEventListener('dragstart', function () {
                dragged = row;
                row.style.opacity = '0.5';
            });
            row.addEventListener('dragend', function () {
                row.style.opacity = '';
                dragged = null;
                saveOrder(tbody, menuId);
            });
            row.addEventListener('dragover', function (e) {
                e.preventDefault();
                const target = e.target.closest('tr[data-id]');
                if (target && target !== dragged) {
                    const rect = target.getBoundingClientRect();
                    const mid = rect.top + rect.height / 2;
                    if (e.clientY < mid) {
                        tbody.insertBefore(dragged, target);
                    } else {
                        tbody.insertBefore(dragged, target.nextSibling);
                    }
                }
            });
        });
    });

    function saveOrder(tbody, menuId) {
        const ids = Array.from(tbody.querySelectorAll('tr[data-id]'))
                         .map(row => row.getAttribute('data-id'));

        // CSRF field name is '_csrf_token' (see app/Core/Csrf.php)
        const csrfInput = document.querySelector('input[name="_csrf_token"]');
        const csrfToken = csrfInput ? csrfInput.value : '';
        if (!csrfToken) return;

        const body = new URLSearchParams();
        body.append('_csrf_token', csrfToken);
        body.append('order', JSON.stringify(ids));

        fetch('/admin/menus/items/reorder', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: body.toString()
        }).catch(function () {
            // Silently ignore – page can be refreshed to confirm order
        });
    }
});
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
