// ── Table Settings ─────────────────────────────────────────────────────
// Note: isPageUnloading is already declared in core.js

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('#miscTableList li').forEach(li => {
        li.addEventListener('click', () => {
            const tableName = li.dataset.table;
            if (!tableName) return;
            document.querySelectorAll('#miscTableList li').forEach(l => l.classList.remove('active'));
            li.classList.add('active');
            loadTableSettings(tableName);
        });
    });
});

// Save on page hide (navigation, refresh, close) using sendBeacon
window.addEventListener('pagehide', () => {
    if (typeof isPageUnloading !== 'undefined') isPageUnloading = true;
    if (currentTableName) {
        const data = {};
        document.querySelectorAll('.table-setting').forEach(el => {
            data[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
        });
        if (Object.keys(data).length) {
            navigator.sendBeacon(
                `${baseUrl}/project/${projectSlug}/misc/save`,
                JSON.stringify({ section: 'table', tableName: currentTableName, data })
            );
        }
    }
});

async function loadTableSettings(tableName) {
    currentTableName = tableName;
    document.getElementById('selectedTableLabel').textContent = tableName;

    let config = null;
    if (currentConfig.byTable && currentConfig.byTable[tableName]) {
        config = currentConfig.byTable[tableName];
        renderTableSettings(config);
        return;
    }

    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/load/${tableName}`);
        const data = await res.json();
        if (data.success) {
            if (!currentConfig.byTable) currentConfig.byTable = {};
            currentConfig.byTable[tableName] = data.config;
            renderTableSettings(data.config);
        } else {
            renderTableSettings(defaultTableConfig);
        }
    } catch (err) {
        renderTableSettings(defaultTableConfig);
    }
}

function renderTableSettings(cfg) {
    const container = document.getElementById('tableSettingsContent');
    const hint = (t) => `<i class="bi bi-info-circle misc-hint" data-bs-toggle="tooltip" title="${t}"></i>`;
    container.innerHTML = `
        <div class="row g-2 mt-2">
            <div class="col-md-4"><label class="form-label small mb-1">Records Per Page ${hint('How many rows show on each list page before pagination.')}</label><input type="number" class="form-control form-control-sm table-setting" data-key="recordsPerPage" value="${cfg.recordsPerPage || 20}"></div>
            <div class="col-md-4"><label class="form-label small mb-1">Records Per Page Options ${hint('The choices in the “rows per page” dropdown, comma-separated (e.g. 10,20,50,100).')}</label><input type="text" class="form-control form-control-sm table-setting" data-key="recordsPerPageOptions" value="${cfg.recordsPerPageOptions || '10,20,50,100'}"></div>
            <div class="col-md-4"><label class="form-label small mb-1">Default Sort Order ${hint('Direction the list is sorted by default — Ascending (A→Z, low→high) or Descending.')}</label>
                <select class="form-select form-select-sm table-setting" data-key="defaultSortOrder">
                    <option value="ASC" ${cfg.defaultSortOrder === 'ASC' ? 'selected' : ''}>Ascending</option>
                    <option value="DESC" ${cfg.defaultSortOrder === 'DESC' ? 'selected' : ''}>Descending</option>
                </select>
            </div>
            <div class="col-12 mt-2">
                <div class="form-check form-check-inline small"><input class="form-check-input table-setting" type="checkbox" data-key="rowHighlight" ${cfg.rowHighlight ? 'checked' : ''}><label class="form-check-label">Row Highlighting ${hint('Highlights the row under the mouse on list pages for easier scanning.')}</label></div>
                <div class="form-check form-check-inline small"><input class="form-check-input table-setting" type="checkbox" data-key="nextPrevButtons" ${cfg.nextPrevButtons ? 'checked' : ''}><label class="form-check-label">Next/Prev Buttons ${hint('Shows Previous / Next record buttons on the view and edit pages.')}</label></div>
                <div class="form-check form-check-inline small"><input class="form-check-input table-setting" type="checkbox" data-key="warnLeave" ${cfg.warnLeave ? 'checked' : ''}><label class="form-check-label">Warn Before Leave ${hint('Warns the user about unsaved changes before they leave an add/edit form.')}</label></div>
                <div class="form-check form-check-inline small"><input class="form-check-input table-setting" type="checkbox" data-key="loadingBox" ${cfg.loadingBox ? 'checked' : ''}><label class="form-check-label">Loading Indicator ${hint('Shows a loading spinner/overlay while data is being fetched.')}</label></div>
                <div class="form-check form-check-inline small"><input class="form-check-input table-setting" type="checkbox" data-key="hideUntilSearch" ${cfg.hideUntilSearch ? 'checked' : ''}><label class="form-check-label">Hide Data Until Search ${hint('Starts the list empty and only shows rows after the user runs a search — good for very large tables.')}</label></div>
            </div>
        </div>`;
    container.querySelectorAll('.table-setting').forEach(el => el.addEventListener('change', saveTableSettings));
    if (typeof initMiscTooltips === 'function') initMiscTooltips(container);
}

async function saveTableSettings() {
    if (typeof isPageUnloading !== 'undefined' && isPageUnloading) return;
    if (!currentTableName) return;

    const data = {};
    document.querySelectorAll('.table-setting').forEach(el => {
        data[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
    });

    // Update local cache for central Save button
    if (!currentConfig.byTable) currentConfig.byTable = {};
    currentConfig.byTable[currentTableName] = data;

    // Immediate save to server (real‑time)
    await fetch(`${baseUrl}/project/${projectSlug}/misc/save`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ section: 'table', tableName: currentTableName, data })
    }).catch(() => { });
}