<?php ob_start(); ?>

<?php
/**
 * Render <option> elements for parent_id select, recursively with depth-based prefix.
 *
 * @param array    $items      Flat list of menu items (with parent_id)
 * @param int|null $selectedId Currently selected parent_id (for pre-selecting)
 * @param int|null $excludeId  Item ID to exclude (prevent circular references), along with its descendants
 * @param int|null $parentId   Current parent to filter for (null = top-level)
 * @param int      $depth      Current nesting depth (for prefix indentation)
 * @param array|null $excludeIds Pre-computed list of IDs to exclude (internal, passed through recursion)
 */
function renderParentOptions(array $items, ?int $selectedId = null, ?int $excludeId = null, ?int $parentId = null, int $depth = 0, ?array $excludeIds = null): void
{
    // On the first call, compute the full exclusion list (self + descendants)
    if ($excludeIds === null) {
        $excludeIds = [];
        if ($excludeId !== null) {
            $excludeIds = collectDescendantIds($items, $excludeId);
            $excludeIds[] = $excludeId;
        }
    }

    foreach ($items as $item) {
        $itemParent = $item['parent_id'] !== null ? (int) $item['parent_id'] : null;
        if ($itemParent !== $parentId) {
            continue;
        }

        $itemId = (int) $item['id'];

        // Skip excluded IDs (self + descendants)
        if (in_array($itemId, $excludeIds, true)) {
            continue;
        }

        // Max nesting depth: prevent creating items deeper than level 2
        if ($depth >= 2) {
            continue;
        }

        $prefix = str_repeat('── ', $depth + 1);
        $selected = ($selectedId !== null && $selectedId === $itemId) ? ' selected' : '';

        echo '<option value="' . $itemId . '"' . $selected . '>' . e($prefix . $item['label']) . '</option>';

        // Recurse for children
        renderParentOptions($items, $selectedId, $excludeId, $itemId, $depth + 1, $excludeIds);
    }
}

/**
 * Collect all descendant IDs of a given item (recursively).
 */
function collectDescendantIds(array $items, int $parentId): array
{
    $ids = [];
    foreach ($items as $item) {
        $itemParent = $item['parent_id'] !== null ? (int) $item['parent_id'] : null;
        if ($itemParent === $parentId) {
            $childId = (int) $item['id'];
            $ids[] = $childId;
            $ids = array_merge($ids, collectDescendantIds($items, $childId));
        }
    }
    return $ids;
}

/**
 * Flatten a tree structure into a flat list with depth information.
 */
function flattenTreeWithDepth(array $tree, int $depth = 0): array
{
    $flat = [];
    foreach ($tree as $item) {
        $children = $item['children'] ?? [];
        unset($item['children']);
        $item['_depth'] = $depth;
        $flat[] = $item;
        if (!empty($children)) {
            $flat = array_merge($flat, flattenTreeWithDepth($children, $depth + 1));
        }
    }
    return $flat;
}
?>

<?php admin_content_header(__('admin.menus.title'), 'menu'); ?>

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

<div class="form-card" id="menu-<?= (int) $menu['id'] ?>">
    <div class="menu-section-header">
        <h4><?= e($menu['name']) ?> <small class="text-muted">(<?= 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($flatItems)): ?>
    <p class="text-muted"><?= __('admin.menus.no_items') ?></p>
    <?php else: ?>
    <div class="table-responsive">
    <table class="data-table">
        <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 ($flatItems as $item): ?>
            <?php $depth = (int) ($item['_depth'] ?? 0); ?>
            <tr data-id="<?= (int) $item['id'] ?>" data-parent-id="<?= (int) ($item['parent_id'] ?? 0) ?>" data-depth="<?= $depth ?>">
                <td class="drag-handle"><?= icon('grip-vertical', 16) ?></td>
                <td>
                    <div style="padding-left: <?= $depth * 24 ?>px;">
                        <?php if ($depth > 0): ?>
                        <span class="text-muted" style="font-family: monospace; margin-right: 4px;">&boxur;&horbar;</span>
                        <?php endif; ?>
                        <strong><?= e($item['label']) ?></strong>
                    </div>
                </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">
                    <?php if ($depth < 2): ?>
                    <button class="btn btn-sm btn-secondary" style="padding: 2px 6px; min-width: auto;"
                            onclick="openAddFormWithParent(<?= (int) $menu['id'] ?>, <?= (int) $item['id'] ?>)"
                            title="<?= __('admin.menus.add_sub_item') ?>"><?= icon('plus', 14) ?></button>
                    <?php endif; ?>
                    <button class="btn btn-sm btn-secondary"
                            onclick="toggleEditForm('edit-row-<?= (int) $item['id'] ?>')"><?= __('admin.common.edit') ?></button>
                    <form method="POST" action="<?= admin_url('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">
                    <form method="POST" action="<?= admin_url('menus/items/update/' . (int) $item['id']) ?>"
                          class="admin-form inline-edit-grid">
                        <?= $csrf->field() ?>
                        <div class="form-group">
                            <label class="form-label"><?= __('admin.menus.label') ?></label>
                            <input type="text" name="label" value="<?= e($item['label']) ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label"><?= __('admin.menus.url') ?></label>
                            <input type="text" name="url" value="<?= e($item['url']) ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label"><?= __('admin.menus.parent') ?? 'Parent' ?></label>
                            <select name="parent_id">
                                <option value="0">-- <?= __('admin.menus.no_parent') ?? 'Kein &uuml;bergeordnetes Element' ?> --</option>
                                <?php renderParentOptions($items, (int) ($item['parent_id'] ?? 0) ?: null, (int) $item['id']); ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-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">
                            <label class="form-label"><?= __('admin.menus.order') ?></label>
                            <input type="number" name="sort_order" value="<?= (int) $item['sort_order'] ?>" style="width:70px;">
                        </div>
                        <div class="form-group">
                            <label class="form-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 class="inline-edit-actions">
                            <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 (hierarchical) -->
    <?php if (!empty($tree)): ?>
    <?php
        $visibleCount = 0;
        $totalCount   = count($flatItems);
        foreach ($flatItems as $fi) {
            if ((int) $fi['is_visible'] === 1) $visibleCount++;
        }
        $hiddenCount = $totalCount - $visibleCount;
    ?>
    <div class="menu-preview">
        <div class="menu-preview-label"><?= __('admin.menus.preview_title') ?></div>
        <nav class="menu-preview-nav" style="flex-direction: column; align-items: flex-start;">
            <?php if ($visibleCount === 0): ?>
            <span class="text-muted"><?= __('admin.menus.no_visible') ?></span>
            <?php else: ?>
            <?php renderMenuPreviewTree($tree); ?>
            <?php endif; ?>
            <?php if ($hiddenCount > 0): ?>
            <span class="menu-preview-hidden-count"
                  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-panel" style="display:none;">
        <h5><?= __('admin.menus.add_to_menu', [':menu' => e($menu['name'])]) ?></h5>
        <form method="POST" action="<?= admin_url('menus/items/store') ?>" class="admin-form add-item-grid">
            <?= $csrf->field() ?>
            <input type="hidden" name="menu_id" value="<?= (int) $menu['id'] ?>">
            <div class="form-group">
                <label class="form-label"><?= __('admin.menus.label') ?> <span class="text-danger">*</span></label>
                <input type="text" name="label" placeholder="<?= __('admin.menus.label_placeholder') ?>" required>
            </div>
            <div class="form-group">
                <label class="form-label"><?= __('admin.menus.url') ?> <span class="text-danger">*</span></label>
                <input type="text" name="url" placeholder="<?= __('admin.menus.url_placeholder') ?>" required>
            </div>
            <div class="form-group">
                <label class="form-label"><?= __('admin.menus.parent') ?? 'Parent' ?></label>
                <select name="parent_id" id="add-parent-<?= (int) $menu['id'] ?>">
                    <option value="0">-- <?= __('admin.menus.no_parent') ?? 'Kein &uuml;bergeordnetes Element' ?> --</option>
                    <?php renderParentOptions($items); ?>
                </select>
            </div>
            <div class="form-group">
                <label class="form-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">
                <label class="form-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 class="inline-edit-actions">
                <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)): ?>
        <div class="quick-fill-bar">
            <strong><?= __('admin.menus.quick_fill') ?></strong>
            <?php foreach ($pages as $p): ?>
            <button type="button" class="btn btn-sm btn-secondary"
                    onclick="prefillAddForm(<?= (int) $menu['id'] ?>, '<?= e(addslashes($p['title'])) ?>', '/<?= e($p['slug']) ?>')">
                <?= e($p['title']) ?>
            </button>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php endforeach; ?>

<?php
/**
 * Render the hierarchical menu preview (recursive).
 */
function renderMenuPreviewTree(array $tree, int $depth = 0): void
{
    foreach ($tree as $item) {
        if (!(int) $item['is_visible']) {
            // Still recurse children in case they are visible
            if (!empty($item['children'])) {
                renderMenuPreviewTree($item['children'], $depth + 1);
            }
            continue;
        }

        $indent = $depth * 20;
        echo '<div style="padding-left: ' . $indent . 'px; display: flex; align-items: center; gap: 4px;">';
        if ($depth > 0) {
            echo '<span class="text-muted" style="font-family: monospace; font-size: 12px;">&boxur;&horbar;</span>';
        }
        echo '<a href="' . e($item['url']) . '"'
           . ' target="' . e($item['target'] ?? '_self') . '"'
           . ' class="menu-preview-link"'
           . ' title="' . e($item['url']) . '"'
           . ' onclick="return false;">'
           . e($item['label']);
        if (($item['target'] ?? '_self') === '_blank') {
            echo ' <span class="text-muted" title="Opens in new tab">' . icon('external-link', 12) . '</span>';
        }
        echo '</a>';
        echo '</div>';

        if (!empty($item['children'])) {
            renderMenuPreviewTree($item['children'], $depth + 1);
        }
    }
}
?>

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

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

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

/**
 * Open the add form for a menu with a specific parent_id pre-selected.
 * Used by the "+" sub-item button on each row.
 */
function openAddFormWithParent(menuId, parentId) {
    var panel = document.getElementById('add-form-' + menuId);
    if (!panel) return;

    // Show the panel if hidden
    panel.style.display = 'block';

    // Pre-select parent_id
    var select = document.getElementById('add-parent-' + menuId);
    if (select) {
        for (var i = 0; i < select.options.length; i++) {
            if (parseInt(select.options[i].value, 10) === parentId) {
                select.selectedIndex = i;
                break;
            }
        }
    }

    // Scroll to the form
    panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });

    // Focus the label input
    var labelInput = panel.querySelector('[name="label"]');
    if (labelInput) {
        setTimeout(function () { labelInput.focus(); }, 100);
    }
}

// Drag-and-drop reorder (sortable rows within each menu table)
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('[id^="sortable-"]').forEach(function (tbody) {
        var menuId = tbody.id.replace('sortable-', '');
        var 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();
                var target = e.target.closest('tr[data-id]');
                if (target && target !== dragged) {
                    var rect = target.getBoundingClientRect();
                    var mid = rect.top + rect.height / 2;
                    if (e.clientY < mid) {
                        tbody.insertBefore(dragged, target);
                    } else {
                        tbody.insertBefore(dragged, target.nextSibling);
                    }
                }
            });
        });
    });

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

        var csrfInput = document.querySelector('input[name="_csrf_token"]');
        var csrfToken = csrfInput ? csrfInput.value : '';
        if (!csrfToken) return;

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

        fetch('<?= admin_url('menus/items/reorder') ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: body.toString()
        }).catch(function () {});
    }
});
</script>

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