// ── Core State & Helpers ──────────────────────────────────────────────
// These variables are also set by the PHP inline script; we ensure they exist.
window.selectedTablesSet = window.selectedTablesSet || new Set(window.savedTables || []);
window.expandedTablesSet = window.expandedTablesSet || new Set(window.savedExpandedTables || []);
window.tableListSort = window.tableListSort || window.savedTableListSort || 'name_asc';
window.tableDetailsCache = window.tableDetailsCache || {};
window.tableTypeMap = window.tableTypeMap || {};
window.allRelations = window.allRelations || [];
window.isPageUnloading = window.isPageUnloading || false;
window.linkMode = window.linkMode || false;
window.linkSource = window.linkSource || null;
window.allTables = window.allTables || [];

// Resolve visual colours from the Tables semantic token layer. Keeping this
// lookup here prevents canvas/SweetAlert visuals from bypassing CSS themes.
function tablesThemeColor(token, fallback = 'currentColor') {
    const value = getComputedStyle(document.documentElement).getPropertyValue(token).trim();
    return value || fallback;
}

function tablesThemeColorInput(token, input) {
    const value = tablesThemeColor(token, input?.value || '');
    if (/^#[0-9a-f]{6}$/i.test(value)) return value;
    if (/^#[0-9a-f]{3}$/i.test(value)) {
        return `#${value.slice(1).split('').map(character => character + character).join('')}`;
    }

    const probe = document.createElement('span');
    probe.style.color = value;
    probe.hidden = true;
    document.body.appendChild(probe);
    const resolved = getComputedStyle(probe).color;
    probe.remove();
    const channels = resolved.match(/[\d.]+/g)?.slice(0, 3).map(Number);
    if (!channels || channels.length !== 3) return input?.value || '';
    return `#${channels.map(channel => Math.max(0, Math.min(255, Math.round(channel))).toString(16).padStart(2, '0')).join('')}`;
}

// Helper: update table type map from table list
function updateTableTypeMap(tables) {
    window.tableTypeMap = {};
    tables.forEach(t => {
        const name = t.name || t;
        const type = t.type || 'TABLE';
        window.tableTypeMap[name] = type;
    });
}

// Expose helpers
window.updateTableTypeMap = updateTableTypeMap;
window.tablesThemeColor = tablesThemeColor;
window.tablesThemeColorInput = tablesThemeColorInput;
