{% extends 'admin/base.html' %}

{% block title %}{{ t('menus.title') }}{% endblock %}

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📋 {{ t('menus.title') }}</h2>
        <p>{{ t('menus.subtitle') }}</p>
    </div>
    <button type="button" class="btn btn-primary" onclick="saveActiveMenu()">💾 {{ t('menus.save_menu') }}</button>
</div>

<!-- Location Tabs: Header / Footer -->
<div class="menu-tabs">
    <button class="menu-tab active" onclick="switchLocationTab('header', event)">📌 {{ t('menus.header_menu') }}</button>
    <button class="menu-tab" onclick="switchLocationTab('footer', event)">📎 {{ t('menus.footer_menu') }}</button>
</div>

<!-- ============================================================ -->
<!-- HEADER MENU FORM                                             -->
<!-- ============================================================ -->
<div id="header-form" class="menu-form">
    <div class="info-box">
        <p>💡 {{ t('menus.header_info')|safe }}</p>
    </div>

    <form method="POST" id="header-menu-form">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="menu_location" value="header">
        <input type="hidden" name="menu_structure" id="header-menu-structure" value="">

        <div class="menu-builder-layout">

            <!-- ── TOP: visual menu builder ───────────────────────── -->
            <div class="menu-builder" id="header-builder">
                <div class="menu-builder__title">{{ t('menus.header_menu') }}</div>
                <div class="menu-builder__note">{{ t('menus.drag_to_reorder') }} · {{ t('menus.drag_to_nest') }}</div>

                <div class="menu-builder__list" id="header-builder-list"
                     ondragover="onBuilderDragOver(event, 'header')"
                     ondrop="onBuilderDrop(event, 'header')"
                     ondragleave="onBuilderDragLeave(event, 'header')">

                    {% if header_items %}
                        {% for item in header_items %}
                        <div class="menu-item-row"
                             draggable="true"
                             data-temp-id="srv-{{ item.id }}"
                             data-type="{{ item.page_type or 'page' }}"
                             data-id="{{ item.page_id or item.post_id or '' }}"
                             data-parent=""
                             data-translation-group="{{ (item.page.translation_group if item.page else (item.post.translation_group if item.post else '')) or '' }}"
                             ondragstart="onItemDragStart(event)"
                             ondragend="onItemDragEnd(event)">
                            <span class="menu-item-row__handle" title="{{ t('menus.drag_to_reorder') }}">⠿</span>
                            <span class="menu-item-row__label">{{ item.label }}</span>
                            <span class="menu-item-row__lang">{{ item.language|upper }}</span>
                            <div class="menu-item-row__actions">
                                <button type="button" class="menu-item-row__add-child"
                                        onclick="nestItem(this, 'header')"
                                        title="{{ t('menus.add_submenu_item') }}">⤵ {{ t('menus.child_item') }}</button>
                                <button type="button" class="menu-item-row__remove"
                                        onclick="removeItem(this, 'header')"
                                        title="{{ t('menus.remove_item') }}">✕</button>
                            </div>
                        </div>
                        {% if parent_map.header.get(item.id) %}
                        <div class="menu-submenu" data-parent-temp="srv-{{ item.id }}">
                            {% for child in parent_map.header[item.id] %}
                            <div class="menu-item-row"
                                 draggable="true"
                                 data-temp-id="srv-child-{{ child.id }}"
                                 data-type="{{ child.page_type or 'page' }}"
                                 data-id="{{ child.page_id or child.post_id or '' }}"
                                 data-parent="srv-{{ item.id }}"
                                 data-translation-group="{{ (child.page.translation_group if child.page else (child.post.translation_group if child.post else '')) or '' }}"
                                 ondragstart="onItemDragStart(event)"
                                 ondragend="onItemDragEnd(event)">
                                <span class="menu-item-row__handle">⠿</span>
                                <span class="menu-item-row__label">{{ child.label }}</span>
                                <span class="menu-item-row__lang">{{ child.language|upper }}</span>
                                <div class="menu-item-row__actions">
                                    <button type="button" class="menu-item-row__add-child"
                                            onclick="unnestItem(this, 'header')"
                                            title="{{ t('menus.parent_item') }}">⤴ {{ t('menus.parent_item') }}</button>
                                    <button type="button" class="menu-item-row__remove"
                                            onclick="removeItem(this, 'header')"
                                            title="{{ t('menus.remove_item') }}">✕</button>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% endif %}
                        {% endfor %}
                    {% else %}
                    <div class="menu-builder__empty" id="header-builder-empty">
                        <p>{{ t('menus.no_menu_items') }}</p>
                    </div>
                    {% endif %}
                </div>

                <div class="menu-builder__footer">
                    <p class="menu-builder__submenu-note">{{ t('menus.submenu_note') }}</p>
                </div>
            </div><!-- /.menu-builder -->

            <!-- ── BOTTOM: content picker ──────────────────────────── -->
            <div class="menu-picker">
                <div class="content-tabs">
                    <button type="button" class="content-tab active" onclick="switchContentTab('header', 'pages', event)">📄 {{ t('sidebar.pages') }}</button>
                    <button type="button" class="content-tab" onclick="switchContentTab('header', 'posts', event)">📝 {{ t('sidebar.posts') }}</button>
                </div>

                <!-- Pages panel -->
                <div id="header-pages-panel" class="content-panel active">
                    <div class="filter-bar">
                        <input type="text" id="header-pages-search" placeholder="🔍 {{ t('pages.search_placeholder') }}">
                        <select id="header-pages-lang">
                            <option value="all">{{ t('menus.all_languages') }}</option>
                            {% for lang in active_languages %}
                            <option value="{{ lang.code }}">{{ lang.name }}</option>
                            {% endfor %}
                        </select>
                        <select id="header-pages-sort">
                            <option value="">{{ t('table.title') }}</option>
                            <option value="title-asc">{{ t('table.title') }} A→Z</option>
                            <option value="title-desc">{{ t('table.title') }} Z→A</option>
                        </select>
                        <select id="header-pages-date">
                            <option value="">{{ t('menus.published') }}</option>
                            <option value="date-desc">{{ t('table.newest_first') }}</option>
                            <option value="date-asc">{{ t('table.oldest_first') }}</option>
                        </select>
                        <span class="selected-counter" id="header-pages-counter"></span>
                    </div>
                    <table class="content-table" id="header-pages-table">
                        <thead>
                            <tr>
                                <th class="cb-cell">☑</th>
                                <th>{{ t('table.title') }}</th>
                                <th>{{ t('menus.menu_label') }}</th>
                                <th>{{ t('menus.lang') }}</th>
                                <th>{{ t('menus.published') }}</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <!-- Posts panel -->
                <div id="header-posts-panel" class="content-panel">
                    <div class="filter-bar">
                        <input type="text" id="header-posts-search" placeholder="🔍 {{ t('posts.search_placeholder') }}">
                        <select id="header-posts-lang">
                            <option value="all">{{ t('menus.all_languages') }}</option>
                            {% for lang in active_languages %}
                            <option value="{{ lang.code }}">{{ lang.name }}</option>
                            {% endfor %}
                        </select>
                        <select id="header-posts-sort">
                            <option value="">{{ t('table.title') }}</option>
                            <option value="title-asc">{{ t('table.title') }} A→Z</option>
                            <option value="title-desc">{{ t('table.title') }} Z→A</option>
                        </select>
                        <select id="header-posts-date">
                            <option value="">{{ t('menus.published') }}</option>
                            <option value="date-desc">{{ t('table.newest_first') }}</option>
                            <option value="date-asc">{{ t('table.oldest_first') }}</option>
                        </select>
                        <span class="selected-counter" id="header-posts-counter"></span>
                    </div>
                    <table class="content-table" id="header-posts-table">
                        <thead>
                            <tr>
                                <th class="cb-cell">☑</th>
                                <th>{{ t('table.title') }}</th>
                                <th>{{ t('menus.menu_label') }}</th>
                                <th>{{ t('menus.lang') }}</th>
                                <th>{{ t('menus.published') }}</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div><!-- /.menu-picker -->

        </div><!-- /.menu-builder-layout -->
    </form>
</div><!-- /#header-form -->
<div class="pagination-footer" id="header-pages-pagination"></div>
<div class="pagination-footer" id="header-posts-pagination" style="display:none"></div>


<!-- ============================================================ -->
<!-- FOOTER MENU FORM                                             -->
<!-- ============================================================ -->
<div id="footer-form" class="menu-form" style="display:none;">
    <div class="info-box">
        <p>💡 {{ t('menus.footer_info') }}</p>
    </div>

    <form method="POST" id="footer-menu-form">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="menu_location" value="footer">
        <input type="hidden" name="menu_structure" id="footer-menu-structure" value="">

        <div class="menu-builder-layout">

            <!-- ── TOP: visual menu builder ───────────────────────── -->
            <div class="menu-builder" id="footer-builder">
                <div class="menu-builder__title">{{ t('menus.footer_menu') }}</div>
                <div class="menu-builder__note">{{ t('menus.drag_to_reorder') }}</div>

                <div class="menu-builder__list" id="footer-builder-list"
                     ondragover="onBuilderDragOver(event, 'footer')"
                     ondrop="onBuilderDrop(event, 'footer')"
                     ondragleave="onBuilderDragLeave(event, 'footer')">

                    {% if footer_items %}
                        {% for item in footer_items %}
                        <div class="menu-item-row"
                             draggable="true"
                             data-temp-id="srv-{{ item.id }}"
                             data-type="{{ item.page_type or 'page' }}"
                             data-id="{{ item.page_id or item.post_id or '' }}"
                             data-parent=""
                             data-translation-group="{{ (item.page.translation_group if item.page else (item.post.translation_group if item.post else '')) or '' }}"
                             ondragstart="onItemDragStart(event)"
                             ondragend="onItemDragEnd(event)">
                            <span class="menu-item-row__handle">⠿</span>
                            <span class="menu-item-row__label">{{ item.label }}</span>
                            <span class="menu-item-row__lang">{{ item.language|upper }}</span>
                            <div class="menu-item-row__actions">
                                <button type="button" class="menu-item-row__remove"
                                        onclick="removeItem(this, 'footer')"
                                        title="{{ t('menus.remove_item') }}">✕</button>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                    <div class="menu-builder__empty" id="footer-builder-empty">
                        <p>{{ t('menus.no_menu_items') }}</p>
                    </div>
                    {% endif %}
                </div>

                <div class="menu-builder__footer">
                    <p class="menu-builder__submenu-note">{{ t('menus.submenu_note') }}</p>
                </div>
            </div><!-- /.menu-builder -->

            <!-- ── BOTTOM: content picker ──────────────────────────── -->
            <div class="menu-picker">
                <div class="content-tabs">
                    <button type="button" class="content-tab active" onclick="switchContentTab('footer', 'pages', event)">📄 {{ t('sidebar.pages') }}</button>
                    <button type="button" class="content-tab" onclick="switchContentTab('footer', 'posts', event)">📝 {{ t('sidebar.posts') }}</button>
                </div>

                <!-- Pages panel -->
                <div id="footer-pages-panel" class="content-panel active">
                    <div class="filter-bar">
                        <input type="text" id="footer-pages-search" placeholder="🔍 {{ t('pages.search_placeholder') }}">
                        <select id="footer-pages-lang">
                            <option value="all">{{ t('menus.all_languages') }}</option>
                            {% for lang in active_languages %}
                            <option value="{{ lang.code }}">{{ lang.name }}</option>
                            {% endfor %}
                        </select>
                        <select id="footer-pages-sort">
                            <option value="">{{ t('table.title') }}</option>
                            <option value="title-asc">{{ t('table.title') }} A→Z</option>
                            <option value="title-desc">{{ t('table.title') }} Z→A</option>
                        </select>
                        <select id="footer-pages-date">
                            <option value="">{{ t('menus.published') }}</option>
                            <option value="date-desc">{{ t('table.newest_first') }}</option>
                            <option value="date-asc">{{ t('table.oldest_first') }}</option>
                        </select>
                        <span class="selected-counter" id="footer-pages-counter"></span>
                    </div>
                    <table class="content-table" id="footer-pages-table">
                        <thead>
                            <tr>
                                <th class="cb-cell">☑</th>
                                <th>{{ t('table.title') }}</th>
                                <th>{{ t('menus.menu_label') }}</th>
                                <th>{{ t('menus.lang') }}</th>
                                <th>{{ t('menus.published') }}</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <!-- Posts panel -->
                <div id="footer-posts-panel" class="content-panel">
                    <div class="filter-bar">
                        <input type="text" id="footer-posts-search" placeholder="🔍 {{ t('posts.search_placeholder') }}">
                        <select id="footer-posts-lang">
                            <option value="all">{{ t('menus.all_languages') }}</option>
                            {% for lang in active_languages %}
                            <option value="{{ lang.code }}">{{ lang.name }}</option>
                            {% endfor %}
                        </select>
                        <select id="footer-posts-sort">
                            <option value="">{{ t('table.title') }}</option>
                            <option value="title-asc">{{ t('table.title') }} A→Z</option>
                            <option value="title-desc">{{ t('table.title') }} Z→A</option>
                        </select>
                        <select id="footer-posts-date">
                            <option value="">{{ t('menus.published') }}</option>
                            <option value="date-desc">{{ t('table.newest_first') }}</option>
                            <option value="date-asc">{{ t('table.oldest_first') }}</option>
                        </select>
                        <span class="selected-counter" id="footer-posts-counter"></span>
                    </div>
                    <table class="content-table" id="footer-posts-table">
                        <thead>
                            <tr>
                                <th class="cb-cell">☑</th>
                                <th>{{ t('table.title') }}</th>
                                <th>{{ t('menus.menu_label') }}</th>
                                <th>{{ t('menus.lang') }}</th>
                                <th>{{ t('menus.published') }}</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div><!-- /.menu-picker -->

        </div><!-- /.menu-builder-layout -->
    </form>
</div><!-- /#footer-form -->
<div class="pagination-footer" id="footer-pages-pagination" style="display:none"></div>
<div class="pagination-footer" id="footer-posts-pagination" style="display:none"></div>

{% endblock %}


{% block extra_js %}
<script>
/* ===================================================================
   MENU BUILDER — combo: HTML5 drag-and-drop + button controls
   No external libraries. Pure vanilla JS.

   Data model:
     Each .menu-item-row in the builder has dataset:
       temp-id  — unique client id ("t-1" new, "srv-42" loaded from DB)
       type     — "page" | "post"
       id       — DB content id (page.id or post.id)
       parent   — temp-id of parent row, or "" for top-level

     Submenus are .menu-submenu divs that follow their parent row
     in the DOM. data-parent-temp links them to the parent row.

   On submit, serializeMenu() walks the DOM and serialises to JSON
   for app.py's admin_menus POST handler (menu_structure field).
=================================================================== */

var _tempCounter = 1000;
function newTempId() { return 't-' + (++_tempCounter); }

/* ── i18n strings (injected from Jinja, used in JS-created DOM) ── */
var _i18n = {
    add_submenu_item: "{{ t('menus.add_submenu_item') | e }}",
    child_item:       "{{ t('menus.child_item') | e }}",
    parent_item:      "{{ t('menus.parent_item') | e }}",
    drag_to_reorder:  "{{ t('menus.drag_to_reorder') | e }}",
    remove_item:      "{{ t('menus.remove_item') | e }}",
    no_menu_items:    "{{ t('menus.no_menu_items') | e }}"
};

/* ── HTML escape helper ────────────────────────────────────────── */
function escHtml(s) {
    return String(s)
        .replace(/&/g,'&amp;').replace(/</g,'&lt;')
        .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

/* ================================================================
   PICKER STATE — survives pagination; source of truth for checks/labels
================================================================ */
var _pickerI18n = {
    custom_label_placeholder: "{{ t('menus.custom_label_placeholder') | e }}",
    no_pages:          "{{ t('menus.no_pages') | e }}",
    no_posts:          "{{ t('menus.no_posts') | e }}",
    create_first_page: "{{ t('menus.create_first_page') | e }}",
    create_first_post: "{{ t('menus.create_first_post') | e }}",
    url_new_page:      "{{ url_for('admin_pages_new') }}",
    url_new_post:      "{{ url_for('admin_posts_new') }}",
    loading:           "{{ t('common.loading') | e }}",
    prev:              "{{ t('pagination.prev') | e }}",
    next:              "{{ t('pagination.next') | e }}",
    per_page:          "{{ t('pagination.per_page') | e }}",
    per_page_suffix:   "{{ t('pagination.per_page_suffix') | e }}"
};

/* checked[location][type] = { id: true }   — which items are in the builder */
/* labels[location][type]  = { id: "text" } — custom labels typed by user    */
/* checkedGroups[location][type] = { translation_group: true } — checked translation groups (for sibling auto-check across pages) */
var pickerState = {
    checked: { header: { pages: {}, posts: {} }, footer: { pages: {}, posts: {} } },
    labels:  { header: { pages: {}, posts: {} }, footer: { pages: {}, posts: {} } },
    checkedGroups: { header: { pages: {}, posts: {} }, footer: { pages: {}, posts: {} } },
    currentPage: { header: { pages: 1, posts: 1 }, footer: { pages: 1, posts: 1 } }
};

/* ── Initialize from server data ── */
(function() {
    var initChecked = {
        header: {
            pages: {{ checked.header.pages | list | tojson }},
            posts: {{ checked.header.posts | list | tojson }}
        },
        footer: {
            pages: {{ checked.footer.pages | list | tojson }},
            posts: {{ checked.footer.posts | list | tojson }}
        }
    };
    var initLabels = {{ menu_labels | tojson }};
    var initGroups = {{ checked_groups | tojson }};

    ['header', 'footer'].forEach(function(loc) {
        ['pages', 'posts'].forEach(function(type) {
            (initChecked[loc][type] || []).forEach(function(id) {
                pickerState.checked[loc][type][String(id)] = true;
            });
            (initGroups[loc][type] || []).forEach(function(tg) {
                pickerState.checkedGroups[loc][type][tg] = true;
            });
        });
        var locLabels = initLabels[loc] || {};
        for (var key in locLabels) {
            if (!locLabels[key]) continue;
            // key = "page_123" or "post_456"
            var parts = key.split('_');
            var type = parts[0] + 's';   // "pages" or "posts"
            var id   = parts.slice(1).join('_');
            if (pickerState.labels[loc][type]) {
                pickerState.labels[loc][type][id] = locLabels[key];
            }
        }
    });
})();

/* ── Save label from input before leaving page (called on input blur) ── */
function savePickerLabel(location, type, id, input) {
    var val = input.value.trim();
    if (val) {
        pickerState.labels[location][type][String(id)] = val;
    } else {
        delete pickerState.labels[location][type][String(id)];
    }
}

/* ── Debounced search ── */
var _searchTimers = {};
function onPickerSearch(location, type) {
    var key = location + '-' + type;
    clearTimeout(_searchTimers[key]);
    _searchTimers[key] = setTimeout(function() {
        loadPickerPage(location, type, 1);
    }, 300);
}

function onPickerFilter(location, type) {
    loadPickerPage(location, type, 1);
}

/* ================================================================
   LOAD PICKER PAGE — fetch from API and render
================================================================ */
function loadPickerPage(location, type, page) {
    var prefix = location + '-' + type;
    var search = document.getElementById(prefix + '-search');
    var lang   = document.getElementById(prefix + '-lang');
    var sortSel = document.getElementById(prefix + '-sort');
    var dateSel = document.getElementById(prefix + '-date');

    var params = new URLSearchParams();
    params.set('type', type);
    params.set('page', page || 1);
    params.set('per_page', _pickerPerPage[prefix] || 20);
    if (search && search.value.trim()) params.set('search', search.value.trim());
    if (lang && lang.value !== 'all') params.set('lang', lang.value);

    var sortVal = '';
    if (sortSel && sortSel.value) { sortVal = sortSel.value; }
    else if (dateSel && dateSel.value) { sortVal = dateSel.value; }
    if (sortVal) params.set('sort', sortVal);

    var table = document.getElementById(prefix + '-table');
    var tbody = table ? table.querySelector('tbody') : null;
    if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center p-4">' + _pickerI18n.loading + '</td></tr>';

    fetch('/admin/api/menu-picker?' + params.toString())
        .then(function(r) { return r.json(); })
        .then(function(data) {
            pickerState.currentPage[location][type] = data.page;
            renderPickerRows(location, type, data);
            renderPickerPagination(location, type, data);
            updateCounters();
        })
        .catch(function(err) {
            if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center p-4">⚠ ' + escHtml(err.message) + '</td></tr>';
        });
}

/* ── Render table rows ── */
function renderPickerRows(location, type, data) {
    var prefix = location + '-' + type;
    var tbody = document.getElementById(prefix + '-table').querySelector('tbody');
    var singularType = type === 'pages' ? 'page' : 'post';

    if (data.total === 0) {
        var noMsg  = type === 'pages' ? _pickerI18n.no_pages : _pickerI18n.no_posts;
        var newUrl = type === 'pages' ? _pickerI18n.url_new_page : _pickerI18n.url_new_post;
        var newTxt = type === 'pages' ? _pickerI18n.create_first_page : _pickerI18n.create_first_post;
        tbody.innerHTML = '<tr><td colspan="5"><div class="empty-state">'
            + '<p>' + noMsg + '</p>'
            + '<a href="' + newUrl + '">' + newTxt + '</a>'
            + '</div></td></tr>';
        return;
    }

    var html = '';
    data.items.forEach(function(item) {
        var id = String(item.id);
        var tg = item.translation_group || '';
        var isChecked = !!pickerState.checked[location][type][id];

        // Auto-check siblings: if this item's translation_group is already checked, check this row too
        if (!isChecked && tg && pickerState.checkedGroups[location][type][tg]) {
            isChecked = true;
            pickerState.checked[location][type][id] = true;
        }

        // Register translation_group if this item is checked
        if (isChecked && tg) {
            pickerState.checkedGroups[location][type][tg] = true;
        }

        var labelVal  = pickerState.labels[location][type][id] || '';
        var placeholder = _pickerI18n.custom_label_placeholder.replace('{lang}', item.language.toUpperCase());

        html += '<tr data-item-type="' + singularType + '"'
            + ' data-item-id="' + id + '"'
            + ' data-item-label="' + escHtml(item.title) + '"'
            + ' data-item-lang="' + escHtml(item.language.toUpperCase()) + '"'
            + ' data-translation-group="' + escHtml(item.translation_group || '') + '"'
            + (isChecked ? ' class="row-checked"' : '') + '>'
            + '<td class="cb-cell">'
            +   '<input type="checkbox" onchange="toggleRow(this,\'' + location + '\')"'
            +   (isChecked ? ' checked' : '') + '>'
            + '</td>'
            + '<td>'
            +   '<div class="title-cell">' + escHtml(item.title) + '</div>'
            +   '<div class="slug-cell">/' + escHtml(item.slug) + '</div>'
            + '</td>'
            + '<td>'
            +   '<input type="text" class="label-input"'
            +   ' placeholder="' + escHtml(placeholder) + '"'
            +   ' value="' + escHtml(labelVal) + '"'
            +   ' onblur="savePickerLabel(\'' + location + '\',\'' + type + '\',\'' + id + '\',this)">'
            + '</td>'
            + '<td><span class="lang-badge">' + escHtml(item.language.toUpperCase()) + '</span></td>'
            + '<td class="date-cell">' + (item.published_at || '—') + '</td>'
            + '</tr>';
    });
    tbody.innerHTML = html;
}

/* ── Render pagination controls ── */
function renderPickerPagination(location, type, data) {
    var prefix = location + '-' + type;
    var container = document.getElementById(prefix + '-pagination');
    if (!container) return;

    var html = '';

    // Pagination buttons (only if more than 1 page)
    if (data.total_pages > 1) {
        html += '<div class="pagination">';

        if (data.page > 1) {
            html += '<a href="#" onclick="loadPickerPage(\'' + location + '\',\'' + type + '\',' + (data.page - 1) + ');return false">' + _pickerI18n.prev + '</a>';
        }

        var start = Math.max(1, data.page - 2);
        var end   = Math.min(data.total_pages, data.page + 2);

        if (start > 1) {
            html += '<a href="#" onclick="loadPickerPage(\'' + location + '\',\'' + type + '\',1);return false">1</a>';
            if (start > 2) html += '<span class="pagination-ellipsis">…</span>';
        }

        for (var i = start; i <= end; i++) {
            if (i === data.page) {
                html += '<span class="current">' + i + '</span>';
            } else {
                html += '<a href="#" onclick="loadPickerPage(\'' + location + '\',\'' + type + '\',' + i + ');return false">' + i + '</a>';
            }
        }

        if (end < data.total_pages) {
            if (end < data.total_pages - 1) html += '<span class="pagination-ellipsis">…</span>';
            html += '<a href="#" onclick="loadPickerPage(\'' + location + '\',\'' + type + '\',' + data.total_pages + ');return false">' + data.total_pages + '</a>';
        }

        if (data.page < data.total_pages) {
            html += '<a href="#" onclick="loadPickerPage(\'' + location + '\',\'' + type + '\',' + (data.page + 1) + ');return false">' + _pickerI18n.next + '</a>';
        }

        html += '</div>';
    }

    // Per-page selector (always visible)
    html += '<div class="per-page-selector">'
        + _pickerI18n.per_page + ' '
        + '<select onchange="onPickerPerPage(\'' + location + '\',\'' + type + '\',this.value)">'
        + '<option value="20"' + (data.per_page === 20 ? ' selected' : '') + '>20</option>'
        + '<option value="50"' + (data.per_page === 50 ? ' selected' : '') + '>50</option>'
        + '<option value="100"' + (data.per_page === 100 ? ' selected' : '') + '>100</option>'
        + '</select>'
        + ' ' + _pickerI18n.per_page_suffix
        + '</div>';

    container.innerHTML = html;
}

/* ── Per-page change handler ── */
var _pickerPerPage = {};
function onPickerPerPage(location, type, val) {
    _pickerPerPage[location + '-' + type] = parseInt(val, 10);
    loadPickerPage(location, type, 1);
}

/* ================================================================
   LOCATION / CONTENT TABS
================================================================ */
var _activeLocation = 'header';
var _activeContentTab = { header: 'pages', footer: 'pages' };

function _updatePaginationVisibility() {
    ['header', 'footer'].forEach(function(loc) {
        ['pages', 'posts'].forEach(function(type) {
            var el = document.getElementById(loc + '-' + type + '-pagination');
            if (el) el.style.display = (loc === _activeLocation && type === _activeContentTab[loc]) ? '' : 'none';
        });
    });
}

function switchLocationTab(location, e) {
    _activeLocation = location;
    document.querySelectorAll('.menu-tab').forEach(function(t) { t.classList.remove('active'); });
    e.target.classList.add('active');
    document.getElementById('header-form').style.display = location === 'header' ? 'block' : 'none';
    document.getElementById('footer-form').style.display = location === 'footer' ? 'block' : 'none';
    _updatePaginationVisibility();
}

window.saveActiveMenu = function() {
    serializeMenu(_activeLocation);
    document.getElementById(_activeLocation + '-menu-form').submit();
};

function switchContentTab(location, type, e) {
    _activeContentTab[location] = type;
    var form = document.getElementById(location + '-form');
    form.querySelectorAll('.content-tab').forEach(function(t) { t.classList.remove('active'); });
    e.target.classList.add('active');
    form.querySelectorAll('.content-panel').forEach(function(p) { p.classList.remove('active'); });
    document.getElementById(location + '-' + type + '-panel').classList.add('active');
    _updatePaginationVisibility();
}

/* ================================================================
   CHECKBOX → BUILDER SYNC
================================================================ */
function toggleRow(checkbox, location) {
    var row = checkbox.closest('tr');
    var type = row.dataset.itemType + 's';   // 'page' → 'pages'
    var id   = row.dataset.itemId;
    var tg   = row.dataset.translationGroup || '';

    if (checkbox.checked) {
        // ── Check this row ──
        row.classList.add('row-checked');
        pickerState.checked[location][type][id] = true;

        // Add ONE builder item (only for the clicked row)
        addItemToBuilder(location, {
            tempId: newTempId(),
            type:   row.dataset.itemType,
            id:     id,
            label:  row.dataset.itemLabel,
            lang:   row.dataset.itemLang,
            tg:     tg,
            parent: ''
        });

        // ── Auto-check visible translation siblings ──
        if (tg) {
            pickerState.checkedGroups[location][type][tg] = true;
            var table = row.closest('table');
            if (table) {
                table.querySelectorAll('tbody tr').forEach(function(siblingRow) {
                    if (siblingRow === row) return;
                    if (siblingRow.dataset.translationGroup !== tg) return;
                    if (siblingRow.dataset.itemType + 's' !== type) return;
                    var sibId = siblingRow.dataset.itemId;
                    if (!pickerState.checked[location][type][sibId]) {
                        pickerState.checked[location][type][sibId] = true;
                        siblingRow.classList.add('row-checked');
                        var cb = siblingRow.querySelector('input[type="checkbox"]');
                        if (cb) cb.checked = true;
                    }
                });
            }
        }
    } else {
        // ── Uncheck this row ──
        row.classList.remove('row-checked');
        delete pickerState.checked[location][type][id];
        delete pickerState.labels[location][type][id];
        var lbl = row.querySelector('.label-input');
        if (lbl) lbl.value = '';
        removeFromBuilderById(location, row.dataset.itemType, id);

        // ── Auto-uncheck visible translation siblings ──
        if (tg) {
            delete pickerState.checkedGroups[location][type][tg];
            var table = row.closest('table');
            if (table) {
                table.querySelectorAll('tbody tr').forEach(function(siblingRow) {
                    if (siblingRow === row) return;
                    if (siblingRow.dataset.translationGroup !== tg) return;
                    if (siblingRow.dataset.itemType + 's' !== type) return;
                    var sibId = siblingRow.dataset.itemId;
                    delete pickerState.checked[location][type][sibId];
                    delete pickerState.labels[location][type][sibId];
                    siblingRow.classList.remove('row-checked');
                    var cb = siblingRow.querySelector('input[type="checkbox"]');
                    if (cb) cb.checked = false;
                    var sibLbl = siblingRow.querySelector('.label-input');
                    if (sibLbl) sibLbl.value = '';
                    // Remove sibling from builder too (in case it was added separately)
                    removeFromBuilderById(location, siblingRow.dataset.itemType, sibId);
                });
            }
        }
    }
    updateCounters();
}

/* ================================================================
   BUILDER — ADD / REMOVE ITEMS
================================================================ */
function addItemToBuilder(location, item) {
    var list  = document.getElementById(location + '-builder-list');
    var empty = document.getElementById(location + '-builder-empty');
    if (empty) empty.remove();

    var isFooter = (location === 'footer');
    var row = document.createElement('div');
    row.className   = 'menu-item-row';
    row.draggable   = true;
    row.dataset.tempId = item.tempId;
    row.dataset.type   = item.type;
    row.dataset.id     = item.id;
    row.dataset.parent = item.parent || '';
    row.dataset.translationGroup = item.tg || '';
    row.addEventListener('dragstart', onItemDragStart);
    row.addEventListener('dragend',   onItemDragEnd);

    var nestBtn = isFooter ? '' :
        '<button type="button" class="menu-item-row__add-child" '
        + 'onclick="nestItem(this,\'' + location + '\')" '
        + 'title="' + _i18n.add_submenu_item + '">⤵ ' + _i18n.child_item + '</button>';

    row.innerHTML =
        '<span class="menu-item-row__handle" title="' + _i18n.drag_to_reorder + '">⠿</span>'
        + '<span class="menu-item-row__label">' + escHtml(item.label) + '</span>'
        + '<span class="menu-item-row__lang">'  + escHtml(item.lang)  + '</span>'
        + '<div class="menu-item-row__actions">'
        +   nestBtn
        +   '<button type="button" class="menu-item-row__remove" '
        +     'onclick="removeItem(this,\'' + location + '\')" '
        +     'title="' + _i18n.remove_item + '">✕</button>'
        + '</div>';

    list.appendChild(row);
}

function removeItem(btn, location) {
    var row  = btn.closest('.menu-item-row');
    var tid  = row.dataset.tempId;
    var tg   = row.dataset.translationGroup || '';
    var type = row.dataset.type + 's';  // 'page' → 'pages'
    var list = document.getElementById(location + '-builder-list');

    // Remove child submenu and uncheck its items in the table
    var sub = list.querySelector('.menu-submenu[data-parent-temp="' + tid + '"]');
    if (sub) {
        sub.querySelectorAll('.menu-item-row').forEach(function(c) {
            uncheckTableRow(location, c.dataset.type, c.dataset.id);
        });
        sub.remove();
    }

    uncheckTableRow(location, row.dataset.type, row.dataset.id);
    row.remove();

    // Clear translation group and uncheck all visible siblings in the picker table
    if (tg) {
        delete pickerState.checkedGroups[location][type][tg];
        ['header', 'footer'].forEach(function(loc) {
            if (loc !== location) return;
            ['pages', 'posts'].forEach(function(tp) {
                var table = document.getElementById(loc + '-' + tp + '-table');
                if (!table) return;
                table.querySelectorAll('tbody tr').forEach(function(siblingRow) {
                    if (siblingRow.dataset.translationGroup !== tg) return;
                    var sibId = siblingRow.dataset.itemId;
                    delete pickerState.checked[location][type][sibId];
                    delete pickerState.labels[location][type][sibId];
                    siblingRow.classList.remove('row-checked');
                    var cb = siblingRow.querySelector('input[type="checkbox"]');
                    if (cb) cb.checked = false;
                    var sibLbl = siblingRow.querySelector('.label-input');
                    if (sibLbl) sibLbl.value = '';
                });
            });
        });
    }

    showEmptyIfNeeded(location);
    updateCounters();
}

function removeFromBuilderById(location, type, id) {
    var list = document.getElementById(location + '-builder-list');
    // Top-level
    list.querySelectorAll(':scope > .menu-item-row').forEach(function(row) {
        if (row.dataset.type === type && row.dataset.id === String(id)) {
            var tid = row.dataset.tempId;
            var sub = list.querySelector('.menu-submenu[data-parent-temp="' + tid + '"]');
            if (sub) sub.remove();
            row.remove();
        }
    });
    // Inside submenus
    list.querySelectorAll('.menu-submenu .menu-item-row').forEach(function(row) {
        if (row.dataset.type === type && row.dataset.id === String(id)) {
            var sub = row.closest('.menu-submenu');
            row.remove();
            if (sub && !sub.querySelector('.menu-item-row')) sub.remove();
        }
    });
    showEmptyIfNeeded(location);
}

/* ================================================================
   NEST / UNNEST BUTTONS
================================================================ */
function nestItem(btn, location) {
    var row  = btn.closest('.menu-item-row');
    var list = document.getElementById(location + '-builder-list');

    // Find closest preceding top-level row
    var prev = null;
    var siblings = Array.from(list.children);
    var idx = siblings.indexOf(row);
    for (var i = idx - 1; i >= 0; i--) {
        if (siblings[i].classList.contains('menu-item-row') && !siblings[i].dataset.parent) {
            prev = siblings[i]; break;
        }
    }
    if (!prev) return;

    var parentTid = prev.dataset.tempId;
    row.dataset.parent = parentTid;

    // Get or create submenu container right after prev (or its existing submenu)
    var sub = list.querySelector('.menu-submenu[data-parent-temp="' + parentTid + '"]');
    if (!sub) {
        sub = document.createElement('div');
        sub.className = 'menu-submenu';
        sub.dataset.parentTemp = parentTid;
        var insertAfter = prev.nextSibling;
        list.insertBefore(sub, insertAfter);
    }

    // Swap button to "unnest"
    btn.textContent = '⤴ ' + _i18n.parent_item;
    btn.setAttribute('onclick', 'unnestItem(this,\'' + location + '\')');
    btn.title = _i18n.parent_item;

    sub.appendChild(row);
}

function unnestItem(btn, location) {
    var row  = btn.closest('.menu-item-row');
    var sub  = row.closest('.menu-submenu');
    var list = document.getElementById(location + '-builder-list');

    row.dataset.parent = '';

    // Swap button back to "nest"
    btn.textContent = '⤵ ' + _i18n.child_item;
    btn.setAttribute('onclick', 'nestItem(this,\'' + location + '\')');
    btn.title = _i18n.add_submenu_item;

    list.appendChild(row);
    if (sub && !sub.querySelector('.menu-item-row')) sub.remove();
}

/* ================================================================
   DRAG AND DROP — HTML5 native
================================================================ */
var _drag = {
    row:      null,   // element being dragged
    location: null
};

function onItemDragStart(e) {
    _drag.row      = e.currentTarget;
    _drag.location = _drag.row.closest('.menu-builder').id.replace('-builder','');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', _drag.row.dataset.tempId);
    setTimeout(function() { _drag.row.classList.add('is-dragging'); }, 0);
}

function onItemDragEnd(e) {
    if (_drag.row) _drag.row.classList.remove('is-dragging');
    _removeIndicator();
    _drag.row = null;
}

function onBuilderDragOver(e, location) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    if (!_drag.row) return;

    var list = document.getElementById(location + '-builder-list');
    var info = _resolveDropTarget(e.clientY, e.clientX, list, location);

    // Highlight nest-target row
    list.querySelectorAll('.menu-item-row.nest-target').forEach(function(r) {
        r.classList.remove('nest-target');
    });
    if (info.mode === 'nest' && info.target) {
        info.target.classList.add('nest-target');
        _removeIndicator();
    } else {
        _showIndicator(list, info.insertBefore);
    }
}

function onBuilderDragLeave(e, location) {
    var list = document.getElementById(location + '-builder-list');
    if (!list.contains(e.relatedTarget)) {
        _removeIndicator();
        list.querySelectorAll('.nest-target').forEach(function(r) { r.classList.remove('nest-target'); });
    }
}

function onBuilderDrop(e, location) {
    e.preventDefault();
    _removeIndicator();
    var list = document.getElementById(location + '-builder-list');
    list.querySelectorAll('.nest-target').forEach(function(r) { r.classList.remove('nest-target'); });
    if (!_drag.row) return;

    var row  = _drag.row;
    var info = _resolveDropTarget(e.clientY, e.clientX, list, location);

    if (info.mode === 'nest' && info.target && info.target !== row) {
        // ── Nest row under target ──────────────────────────────────
        var parentTid = info.target.dataset.tempId;
        var sub = list.querySelector('.menu-submenu[data-parent-temp="' + parentTid + '"]');
        if (!sub) {
            sub = document.createElement('div');
            sub.className = 'menu-submenu';
            sub.dataset.parentTemp = parentTid;
            // Insert right after target row (before any existing next sibling)
            var nextSib = info.target.nextSibling;
            list.insertBefore(sub, nextSib);
        }
        row.dataset.parent = parentTid;
        var nestBtn = row.querySelector('[onclick*="nestItem"]');
        if (nestBtn) {
            nestBtn.textContent = '⤴ ' + _i18n.parent_item;
            nestBtn.setAttribute('onclick', 'unnestItem(this,\'' + location + '\')');
            nestBtn.title = _i18n.parent_item;
        }
        sub.appendChild(row);

    } else {
        // ── Reorder ────────────────────────────────────────────────
        var insertBefore = info.insertBefore;
        if (insertBefore && insertBefore !== row) {
            list.insertBefore(row, insertBefore);
        } else if (!insertBefore) {
            list.appendChild(row);
        }
        row.dataset.parent = '';
        var unnestBtn = row.querySelector('[onclick*="unnestItem"]');
        if (unnestBtn) {
            unnestBtn.textContent = '⤵ ' + _i18n.child_item;
            unnestBtn.setAttribute('onclick', 'nestItem(this,\'' + location + '\')');
            unnestBtn.title = _i18n.add_submenu_item;
        }
    }

    showEmptyIfNeeded(location);
}

/*
  Resolves what should happen at the current cursor position.

  Returns { mode: 'reorder'|'nest', target, insertBefore }

  Logic:
  - Walk all .menu-item-row elements (top-level and inside submenus)
  - Find the one the cursor is directly over (clientY within its bounding rect)
  - If that row is a top-level row AND cursor is in its lower-middle 40%
    (below the midpoint but not the last 10px = insert-after zone) → mode 'nest'
  - Otherwise → mode 'reorder', find the correct insertBefore in list.children
*/
function _resolveDropTarget(clientY, clientX, list, location) {
    var dragged = _drag.row;
    var hoveredRow = null;

    // Find which .menu-item-row the cursor is physically over
    list.querySelectorAll('.menu-item-row').forEach(function(r) {
        if (r === dragged) return;
        var rect = r.getBoundingClientRect();
        if (clientY >= rect.top && clientY <= rect.bottom) {
            hoveredRow = r;
        }
    });

    // Nest mode: cursor over a top-level row in the middle band (25%–80% vertically)
    if (hoveredRow
        && !hoveredRow.dataset.parent
        && location !== 'footer')
    {
        var rr   = hoveredRow.getBoundingClientRect();
        var relY = (clientY - rr.top) / rr.height;
        if (relY > 0.25 && relY < 0.80) {
            return { mode: 'nest', target: hoveredRow, insertBefore: null };
        }
    }

    // Reorder mode: find insertion point among list's direct children
    var insertBefore = null;
    Array.from(list.children).forEach(function(el) {
        if (el === dragged) return;
        if (el.id === 'menu-drop-indicator') return;
        var rect = el.getBoundingClientRect();
        var mid  = rect.top + rect.height / 2;
        if (clientY < mid && (insertBefore === null || rect.top < insertBefore.getBoundingClientRect().top)) {
            insertBefore = el;
        }
    });

    return { mode: 'reorder', target: hoveredRow, insertBefore: insertBefore };
}

var _indicatorEl = null;
function _showIndicator(list, target) {
    _removeIndicator();
    _indicatorEl = document.createElement('div');
    _indicatorEl.id = 'menu-drop-indicator';
    _indicatorEl.className = 'menu-drop-zone is-over';
    list.insertBefore(_indicatorEl, target || null);
}
function _removeIndicator() {
    if (_indicatorEl) { _indicatorEl.remove(); _indicatorEl = null; }
}

/* ================================================================
   TABLE HELPERS
================================================================ */
function updateCounters() {
    ['header', 'footer'].forEach(function(loc) {
        ['pages', 'posts'].forEach(function(type) {
            var ctr = document.getElementById(loc + '-' + type + '-counter');
            if (!ctr) return;
            var n = Object.keys(pickerState.checked[loc][type]).length;
            ctr.textContent = n > 0 ? (n + ' {{ t("table.selected") }}') : '';
        });
    });
}

function uncheckTableRow(location, type, id) {
    var pluralType = type + 's';  // 'page' → 'pages'
    delete pickerState.checked[location][pluralType][String(id)];
    delete pickerState.labels[location][pluralType][String(id)];

    // If the row is currently visible in the table, update it
    var prefix = location + '-' + pluralType;
    var table = document.getElementById(prefix + '-table');
    if (table) {
        table.querySelectorAll('tbody tr').forEach(function(row) {
            if (row.dataset.itemId === String(id)) {
                row.classList.remove('row-checked');
                var cb = row.querySelector('input[type="checkbox"]');
                if (cb) cb.checked = false;
                var lbl = row.querySelector('.label-input');
                if (lbl) lbl.value = '';
            }
        });
    }
    updateCounters();
}

function showEmptyIfNeeded(location) {
    var list = document.getElementById(location + '-builder-list');
    if (!list.querySelector('.menu-item-row')) {
        var d = document.createElement('div');
        d.className = 'menu-builder__empty';
        d.id = location + '-builder-empty';
        d.innerHTML = '<p>' + _i18n.no_menu_items + '</p>';
        list.appendChild(d);
    }
}

/* ================================================================
   FORM SERIALIZATION — inject hidden label inputs from pickerState
================================================================ */
function serializeMenu(location) {
    var list   = document.getElementById(location + '-builder-list');
    var hidden = document.getElementById(location + '-menu-structure');
    var form   = document.getElementById(location + '-menu-form');
    var result = [];

    Array.from(list.children).forEach(function(el) {
        if (el.classList.contains('menu-item-row')) {
            result.push({
                temp_id: el.dataset.tempId,
                type:    el.dataset.type,
                id:      el.dataset.id,
                parent:  null
            });
        } else if (el.classList.contains('menu-submenu')) {
            var pTid = el.dataset.parentTemp;
            el.querySelectorAll('.menu-item-row').forEach(function(child) {
                result.push({
                    temp_id: child.dataset.tempId,
                    type:    child.dataset.type,
                    id:      child.dataset.id,
                    parent:  pTid
                });
            });
        }
    });

    hidden.value = JSON.stringify(result);

    // Inject hidden inputs for custom labels from pickerState
    // (rows on other pages are not in DOM, so we must add them here)
    form.querySelectorAll('input.picker-label-hidden').forEach(function(el) { el.remove(); });
    ['pages', 'posts'].forEach(function(type) {
        var singularType = type === 'pages' ? 'page' : 'post';
        var labels = pickerState.labels[location][type];
        for (var id in labels) {
            if (!labels[id]) continue;
            var inp = document.createElement('input');
            inp.type = 'hidden';
            inp.className = 'picker-label-hidden';
            inp.name = 'label_' + singularType + '_' + id;
            inp.value = labels[id];
            form.appendChild(inp);
        }
    });
}

/* ── Attach filter/sort event listeners ── */
function initPickerEvents() {
    ['header', 'footer'].forEach(function(loc) {
        ['pages', 'posts'].forEach(function(type) {
            var prefix = loc + '-' + type;
            var search  = document.getElementById(prefix + '-search');
            var lang    = document.getElementById(prefix + '-lang');
            var sortSel = document.getElementById(prefix + '-sort');
            var dateSel = document.getElementById(prefix + '-date');

            if (search) search.addEventListener('input', function() { onPickerSearch(loc, type); });
            if (lang)   lang.addEventListener('change', function() { onPickerFilter(loc, type); });
            if (sortSel) sortSel.addEventListener('change', function() {
                if (dateSel) dateSel.selectedIndex = 0;
                onPickerFilter(loc, type);
            });
            if (dateSel) dateSel.addEventListener('change', function() {
                if (sortSel) sortSel.selectedIndex = 0;
                onPickerFilter(loc, type);
            });
        });
    });
}

/* ── Init ──────────────────────────────────────────────────────── */
window.addEventListener('DOMContentLoaded', function() {
    initPickerEvents();
    // Load first page of each picker
    ['header', 'footer'].forEach(function(loc) {
        ['pages', 'posts'].forEach(function(type) {
            loadPickerPage(loc, type, 1);
        });
    });
    updateCounters();
});
</script>

{% endblock %}
