// ── Initialization & Event Listeners ────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
    initializePageTooltips(document);
    // Seed the in-memory cache from the server snapshot so table-switch flushing
    // and the navbar Save always have every table's latest config.
    if (typeof pagesConfig === 'object' && pagesConfig) {
        Object.keys(pagesConfig).forEach(t => { allPagesStates[t] = pagesConfig[t]; });
    }

    // Mobile toggle
    const btnToggle = document.getElementById('btnTogglePageList');
    const leftPanel = document.querySelector('.left-panel');
    if (btnToggle && leftPanel) {
        btnToggle.addEventListener('click', () => {
            leftPanel.classList.toggle('collapsed');
            btnToggle.innerHTML = leftPanel.classList.contains('collapsed')
                ? '<i class="bi bi-list"></i> Tables'
                : '<i class="bi bi-x-lg"></i> Hide';
        });
    }

    // Left panel click → load table config
    const tableItems = Array.from(document.querySelectorAll('#pagesTableList li'));
    const selectTable = li => {
            const tableName = li.dataset.table;
            if (!tableName) return;
            document.querySelectorAll('#pagesTableList li').forEach(l => l.classList.remove('active'));
            li.classList.add('active');
            loadTableConfig(tableName);
    };
    tableItems.forEach(li => {
        li.addEventListener('click', () => selectTable(li));
        li.addEventListener('keydown', event => {
            if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                selectTable(li);
            }
        });
    });

    // Dense projects remain usable with 100+ tables: filter locally and keep
    // the visible-result count accurate without touching project state.
    const tableSearch = document.getElementById('pagesTableSearch');
    const clearTableSearch = document.getElementById('clearPagesTableSearch');
    const tableCount = document.getElementById('pagesTableCount');
    const tableEmpty = document.getElementById('pagesTableEmpty');
    const filterTables = () => {
        const query = (tableSearch?.value || '').trim().toLocaleLowerCase();
        let visible = 0;
        tableItems.forEach(item => {
            const matches = !query || (item.dataset.table || '').toLocaleLowerCase().includes(query);
            item.hidden = !matches;
            if (matches) visible += 1;
        });
        if (tableCount) tableCount.textContent = query ? `${visible}/${tableItems.length}` : String(tableItems.length);
        if (tableEmpty) tableEmpty.hidden = visible !== 0;
        if (clearTableSearch) clearTableSearch.hidden = query === '';
    };
    tableSearch?.addEventListener('input', filterTables);
    clearTableSearch?.addEventListener('click', () => {
        tableSearch.value = '';
        filterTables();
        tableSearch.focus();
    });

    if (currentTableName) {
        document.querySelectorAll('#pagesTableList li').forEach(li => {
            if (li.dataset.table === currentTableName) li.classList.add('active');
        });
        loadTableConfig(currentTableName);
    }

    // Key Columns modal save
    document.getElementById('btnSaveKeyColumns')?.addEventListener('click', () => {
        const checked = [];
        document.querySelectorAll('#keyColumnsBody .key-col-check:checked').forEach(cb => checked.push(cb.value));
        currentKeyColumns = checked;
        autoSaveCurrentPageState();
        renderConfig();
        bootstrap.Modal.getInstance(document.getElementById('keyColumnsModal')).hide();
    });

    // Page Settings modal save
    document.getElementById('btnSavePageSettings')?.addEventListener('click', () => {
        const pageType = document.getElementById('pageSettingsModal')?.dataset.pageType || '';
        if (!currentConfig) currentConfig = {};
        // `settings` must be a plain OBJECT. An empty PHP array serialises to `[]`,
        // which arrives here as a JS ARRAY — and setting `.list` on an array is
        // dropped by JSON.stringify, so the save silently loses the settings.
        if (!currentConfig.settings || Array.isArray(currentConfig.settings)) currentConfig.settings = {};
        if (pageType === 'list') {
            currentConfig.settings.list = {
                scrollTable: document.getElementById('listScrollTable')?.checked ?? false,
                reorderFields: document.getElementById('listReorderFields')?.checked ?? false,
                resizableColumns: document.getElementById('listResizableColumns')?.checked ?? false,
                pinColumns: document.getElementById('listPinColumns')?.checked ?? false,
                savedViews: document.getElementById('listSavedViews')?.checked ?? false,
                groupBy: document.getElementById('listGroupBy')?.value || '',
                kanbanField: document.getElementById('listKanbanField')?.value || '',
                clickActions: clickActions.slice()
            };
        } else if (pageType === 'add') {
            currentConfig.settings.add = {
                showInPopup: document.getElementById('addShowInPopup')?.checked ?? false,
                afterAdd: document.getElementById('addAfterAction')?.value ?? 'list',
                closePopup: document.getElementById('addClosePopup')?.checked ?? false
            };
        } else if (pageType === 'edit') {
            currentConfig.settings.edit = {
                showInPopup: document.getElementById('editShowInPopup')?.checked ?? false,
                afterEdit: document.getElementById('editAfterAction')?.value ?? 'list',
                closePopup: document.getElementById('editClosePopup')?.checked ?? false
            };
        } else if (pageType === 'view') {
            const val = id => (document.getElementById(id)?.value || '').trim();
            currentConfig.settings.view = {
                showInPopup: document.getElementById('viewShowInPopup')?.checked ?? false,
                hideEmptyFields: document.getElementById('viewHideEmpty')?.checked ?? false,
                seo: {
                    enabled: document.getElementById('seoEnabled')?.checked ?? false,
                    public_read: document.getElementById('seoPublicRead')?.checked ?? false,
                    prefix: val('seoPrefix'),
                    slug_column: val('seoSlugCol'),
                    title_column: val('seoTitleCol'),
                    title_template: val('seoTitleTpl'),
                    description_field: val('seoDescField'),
                    og_image_field: val('seoOgField'),
                    og_image_default: val('seoOgDefault'),
                    robots: document.getElementById('seoRobots')?.value || 'index',
                    lastmod_column: val('seoLastmod'),
                    changefreq: document.getElementById('seoFreq')?.value || '',
                    priority: val('seoPriority')
                }
            };
        } else if (pageType === 'pdf') {
            const pdfSource = document.querySelector('input[name="pdfSource"]:checked')?.value || 'print';
            currentConfig.settings.pdf = {
                orientation: document.getElementById('pdfOrientation')?.value ?? 'portrait',
                source: pdfSource,
                // Keep the legacy booleans in sync for backward compatibility.
                printPage: pdfSource === 'print',
                viewPage: pdfSource === 'view'
            };
        } else if (pageType === 'export') {
            // Registry-driven: a plain list of format ids, so new formats need no
            // new settings key. An empty list means "export disabled".
            currentConfig.settings.export = {
                formats: Array.from(document.querySelectorAll('.pp-exp-fmt:checked')).map(cb => cb.value),
                includeHeaders: document.getElementById('expHeaders')?.checked ?? true
            };
        } else if (pageType === 'import') {
            currentConfig.settings.import = {
                readers: Array.from(document.querySelectorAll('.pp-imp-fmt:checked')).map(cb => cb.value),
                modes: Array.from(document.querySelectorAll('.pp-imp-mode:checked')).map(cb => cb.value),
                delimiter: document.getElementById('impDelim')?.value || 'auto',
                maxMb: parseInt(document.getElementById('impMaxMb')?.value, 10) || 8,
                allowPaste: document.getElementById('impPaste')?.checked ?? true,
                allowUpload: document.getElementById('impUpload')?.checked ?? true,
                hasHeaderDefault: document.getElementById('impHeaders')?.checked ?? true,
                validateDefault: document.getElementById('impValidate')?.checked ?? false
            };
        } else if (pageType === 'cards') {
            const body = Array.from(document.querySelectorAll('.pp-card-body-cb:checked')).map(cb => cb.value);
            const badgeColors = {};
            document.querySelectorAll('.pp-badge-color-row').forEach(row => {
                const key = (row.querySelector('.pp-bc-value')?.value || '').trim() || '*';
                const col = row.querySelector('.pp-bc-color')?.value || '';
                if (col) badgeColors[key] = col;
            });
            currentConfig.settings.cards = {
                title: document.getElementById('cardTitle')?.value || '',
                subtitle: document.getElementById('cardSubtitle')?.value || '',
                image: document.getElementById('cardImage')?.value || '',
                badge: document.getElementById('cardBadge')?.value || '',
                badgeColors: badgeColors,
                body: body,
                perRow: parseInt(document.getElementById('cardPerRow')?.value || '0', 10) || 0,
                showLabels: document.getElementById('cardShowLabels')?.checked ?? true,
                actions: document.getElementById('cardActions')?.checked ?? true
            };
        }
        // Clicking the modal's Save is an EXPLICIT save — persist immediately
        // (not the 300ms debounce, which is discarded if the user navigates to
        // another full-page SPA module right after → the reported "settings reset").
        if (typeof saveCurrentConfig === 'function') saveCurrentConfig();
        else autoSaveCurrentPageState();
        bootstrap.Modal.getInstance(document.getElementById('pageSettingsModal')).hide();
    });

    // Delegate "Add Click Action" button
    document.addEventListener('click', (e) => {
        if (e.target.closest('#btnAddClickAction')) openClickActionModal(-1);
    });
});
