// ── Left Panel Table List ────────────────────────────────────────────
const systemGeneratedTables = new Set([
    'component_library',
    'field_encryption',
    'group_permissions',
    'groups',
    'notifications',
    'page_designs',
    'page_permissions',
    'password_resets',
    'record_locks',
    'remember_tokens',
    'row_security_rules',
    'security_audit',
    'social_auth_accounts',
    'user_2fa',
    'user_groups',
    'user_sessions',
    'users'
]);

function tableNameOf(table) {
    return table.name || table;
}

function tableTypeOf(table) {
    return table.type || 'TABLE';
}

function isSystemGeneratedTable(tableName) {
    // Prefer the shared source of truth (window.PP_SYSTEM, mirrors
    // core/SystemTables.php). The local Set is only a fallback if it hasn't loaded.
    if (window.PP_SYSTEM && typeof window.PP_SYSTEM.isSystem === 'function') {
        return window.PP_SYSTEM.isSystem(tableName);
    }
    const name = String(tableName || '').toLowerCase();
    return systemGeneratedTables.has(name)
        || name.startsWith('pp_')
        || name.startsWith('ppphp_')
        || name.startsWith('system_');
}

function safeTableDomId(tableName) {
    return 'chk_' + String(tableName).replace(/[^a-zA-Z0-9_-]/g, '_');
}

function tableListEscape(value) {
    return String(value ?? '').replace(/[&<>"']/g, char => ({
        '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'
    }[char]));
}

function createTableListItem(t) {
    const tableName = tableNameOf(t);
    const type = tableTypeOf(t);
    const systemTable = isSystemGeneratedTable(tableName);
    const icon = type === 'VIEW' ? 'bi-eye' : 'bi-table';
    const id = safeTableDomId(tableName);

    const li = document.createElement('li');
    li.className = 'table-list-item';
    li.innerHTML = `
        <input type="checkbox" class="table-check" id="${id}" value="${tableListEscape(tableName)}">
        <label for="${id}" class="table-row-label">
            <i class="bi ${icon}"></i>
            <span class="table-row-name" title="${tableListEscape(tableName)}">${tableListEscape(tableName)}</span>
        </label>
        <span class="table-row-meta" title="${systemTable ? 'System-generated protected table' : (type === 'VIEW' ? 'View' : 'Project table')}">
            ${systemTable ? '<i class="bi bi-shield-lock"></i>' : (type === 'VIEW' ? '<span>VIEW</span>' : '')}
        </span>
    `;
    li.dataset.table = tableName;
    li.dataset.type = type;
    li.dataset.scope = systemTable ? 'system' : 'project';

    li.addEventListener('click', (e) => {
        if (e.target.closest('input, label')) return;
        const cb = li.querySelector('.table-check');
        cb.checked = !cb.checked;
        cb.dispatchEvent(new Event('change'));
    });

    const cb = li.querySelector('.table-check');
    cb.addEventListener('change', () => handleTableToggle(tableName, cb.checked));

    return li;
}

function createTableGroup(label, tables, options = {}) {
    const group = document.createElement('li');
    const collapsed = !!options.collapsed;
    const groupId = options.groupId || label.toLowerCase().replace(/[^a-z0-9]+/g, '-');
    group.className = 'table-group';
    group.dataset.group = groupId;
    if (collapsed) group.classList.add('collapsed');

    const header = document.createElement('button');
    header.type = 'button';
    header.className = 'table-group-header';
    header.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
    header.innerHTML = `
        <span class="table-group-title"><i class="bi ${collapsed ? 'bi-chevron-right' : 'bi-chevron-down'}"></i>${label}</span>
        <span class="table-group-count" data-total="${tables.length}">${tables.length}</span>
    `;

    const body = document.createElement('ul');
    body.className = 'table-group-body';

    tables.forEach(table => body.appendChild(createTableListItem(table)));
    header.addEventListener('click', () => {
        const isCollapsed = group.classList.toggle('collapsed');
        header.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true');
        const icon = header.querySelector('i');
        if (icon) icon.className = `bi ${isCollapsed ? 'bi-chevron-right' : 'bi-chevron-down'}`;
    });

    group.appendChild(header);
    group.appendChild(body);
    return group;
}

function applyTableFilter() {
    const input = document.getElementById('tableFilter');
    const term = (input?.value || '').trim().toLowerCase();

    document.querySelectorAll('#tableList .table-group').forEach(group => {
        let visible = 0;
        group.querySelectorAll('.table-list-item').forEach(item => {
            const name = (item.dataset.table || '').toLowerCase();
            const matches = term === '' || name.includes(term);
            item.hidden = !matches;
            if (matches) visible++;
        });

        const count = group.querySelector('.table-group-count');
        if (count) {
            const total = count.dataset.total || String(visible);
            count.textContent = term === '' ? total : `${visible}/${total}`;
        }
        group.hidden = term !== '' && visible === 0;
    });
    updateSelectAllButtons();
}

function renderTableList(tables) {
    const list = document.getElementById('tableList');
    list.innerHTML = '';
    if (tables.length === 0) {
        list.innerHTML = '<li class="text-muted px-3 py-2">No tables found</li>';
        return;
    }

    const projectTables = [];
    const systemTables = [];
    tables.forEach(t => {
        const tableName = tableNameOf(t);
        if (isSystemGeneratedTable(tableName)) systemTables.push(t);
        else projectTables.push(t);
    });

    list.appendChild(createTableGroup('Project', projectTables, { groupId: 'project' }));
    if (systemTables.length > 0) {
        list.appendChild(createTableGroup('System-Generated', systemTables, { groupId: 'system-generated', collapsed: true }));
    }
    updateTableTypeMap(tables);
    applyTableFilter();
}

function handleTableToggle(tableName, isChecked) {
    if (isChecked) {
        window.selectedTablesSet.add(tableName);
    } else {
        window.selectedTablesSet.delete(tableName);
    }
    if (typeof renderSelectedCards === 'function') renderSelectedCards();
    updateSelectAllButtons();
}

function updateSelectAllButtons() {
    const stats = document.getElementById('tableListStats');
    if (!stats) return;
    const projectItems = Array.from(document.querySelectorAll('#tableList .table-list-item[data-scope="project"]'));
    const selected = projectItems.filter(item => window.selectedTablesSet?.has(item.dataset.table)).length;
    const total = projectItems.length;
    const visible = projectItems.filter(item => !item.hidden).length;
    const term = (document.getElementById('tableFilter')?.value || '').trim();
    stats.textContent = term ? `${selected} selected · ${visible}/${total}` : `${selected} selected · ${total} total`;
}

// Select All / Deselect All
document.getElementById('btnSelectAll')?.addEventListener('click', () => {
    document.querySelectorAll('#tableList .table-list-item[data-scope="project"] .table-check').forEach(cb => {
        cb.checked = true;
        cb.dispatchEvent(new Event('change'));
    });
});
document.getElementById('btnDeselectAll')?.addEventListener('click', () => {
    document.querySelectorAll('.table-check').forEach(cb => { cb.checked = false; cb.dispatchEvent(new Event('change')); });
});
document.getElementById('tableFilter')?.addEventListener('input', () => {
    applyTableFilter();
    if (typeof window.autoSaveTablesState === 'function') window.autoSaveTablesState();
});
if (document.getElementById('tableFilter') && typeof window.savedTableListFilter === 'string') {
    document.getElementById('tableFilter').value = window.savedTableListFilter;
}

// Expose functions
window.handleTableToggle = handleTableToggle;
window.renderTableList = renderTableList;
window.updateSelectAllButtons = updateSelectAllButtons;
window.isSystemGeneratedTable = isSystemGeneratedTable;
window.applyTableFilter = applyTableFilter;
