/**
 * Tab switching — switchTab, initTabs, startAutoRefresh, hash routing.
 */

import { apiKey, authRequired, refreshInterval, setRefreshInterval, dashboardPollInterval } from '../core/state.ts';
import { getActiveSubTab, setActiveSubTab, callTabLoader, callSubTabSwitcher, getSubTabConfig, getTabConfig } from '../core/tab-registry.ts';

/** Parse location.hash into {tab, subTab}. */
export function parseHash(): { tab?: string; subTab?: string } {
    const hash = location.hash.replace(/^#/, '');
    if (!hash) return {};
    const [tab, subTab] = hash.split('/');
    return { tab, subTab };
}

/** Update the URL hash without triggering popstate. */
function _setHash(tab: string, subTab: string | null): void {
    const hash = '#' + (subTab ? `${tab}/${subTab}` : tab);
    history.replaceState(null, '', hash);
}

let _suppressHashUpdate = false;
let _activeTab: string | null = null;

const _tabScrollPositions: Record<string, number> = {};

export function switchTab(name: string, { updateHash = true, skipLoad = false }: { updateHash?: boolean; skipLoad?: boolean } = {}): void {
    if (_activeTab === name) return;
    // Save scroll position of the tab we're leaving
    if (_activeTab) _tabScrollPositions[_activeTab] = window.scrollY;
    _activeTab = name;

    document.querySelectorAll('.tab-btn').forEach(btn => {
        const isActive = (btn as HTMLElement).dataset.tab === name;
        btn.classList.toggle('active', isActive);
        btn.setAttribute('aria-selected', String(isActive));
    });
    document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.toggle('active', panel.id === `tab-${name}`));
    localStorage.setItem('activeTab', name);

    // Update background tab indicator
    if (typeof window._updateTabIndicator === 'function') window._updateTabIndicator(name);

    // Restore scroll position for this tab
    requestAnimationFrame(() => window.scrollTo(0, _tabScrollPositions[name] || 0));

    if (updateHash && !_suppressHashUpdate) {
        _setHash(name, getActiveSubTab(name));
    }

    // Authenticated when either auth is disabled or we have an apiKey
    const isAuthed = !authRequired || !!apiKey;

    if (name === 'dashboard') {
        // Use window.* to avoid circular imports with feature modules
        if (!skipLoad && isAuthed) callTabLoader(name);
    } else {
        // Perf poll keeps running across all tabs so the transport-bar
        // Uptime / CPU / Mem cells stay live. Only stopped on auth loss
        // or when the tab is hidden (visibilitychange handler).
        if (typeof window.stopUptimeTimer === 'function') window.stopUptimeTimer();
        // Clean up WebSockets when leaving targets tab
        if (name !== 'targets') {
            if (typeof window.disconnectAllKCWebSockets === 'function') window.disconnectAllKCWebSockets();
            if (typeof window.disconnectAllLedPreviewWS === 'function') window.disconnectAllLedPreviewWS();
        }
        if (!isAuthed || skipLoad) return;
        callTabLoader(name);
    }
}

export function initTabs(): void {
    // Hash takes priority over localStorage
    const hashRoute = parseHash();
    let saved;

    if (hashRoute.tab && document.getElementById(`tab-${hashRoute.tab}`)) {
        saved = hashRoute.tab;
        // Pre-set sub-tab so the sub-tab switch functions pick it up
        if (hashRoute.subTab) {
            setActiveSubTab(saved, hashRoute.subTab);
        }
    } else {
        saved = localStorage.getItem('activeTab');
    }

    if (!saved || !document.getElementById(`tab-${saved}`)) saved = 'dashboard';
    switchTab(saved);
}

/** Update hash when sub-tab changes. Called from targets.js / streams.js. */
export function updateSubTabHash(tab: string, subTab: string): void {
    _setHash(tab, subTab);
}

/** Update the count badge on a main tab button. Disabled — badges removed from tab headers. */
export function updateTabBadge(_tabName: string, _count: number): void {}

export function startAutoRefresh(): void {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }

    setRefreshInterval(setInterval(() => {
        const isAuthed = !authRequired || !!apiKey;
        if (!isAuthed || document.hidden) return;
        const activeTab = localStorage.getItem('activeTab') || 'dashboard';
        const cfg = getTabConfig(activeTab);
        if (!cfg?.autoRefresh) return;
        // Skip refresh while user interacts with a picker or slider
        if (activeTab === 'targets') {
            const panel = document.getElementById('targets-panel-content');
            if (panel && panel.contains(document.activeElement) && document.activeElement!.matches('input')) return;
        }
        callTabLoader(activeTab);
    }, dashboardPollInterval));
}

/**
 * Handle browser back/forward via popstate.
 * Called from app.js.
 */
export function handlePopState(): void {
    const hashRoute = parseHash();
    if (!hashRoute.tab) return;

    const currentTab = localStorage.getItem('activeTab');
    _suppressHashUpdate = true;

    if (hashRoute.tab !== currentTab) {
        switchTab(hashRoute.tab, { updateHash: false });
    }

    if (hashRoute.subTab) {
        const subCfg = getSubTabConfig(hashRoute.tab);
        if (subCfg) {
            const currentSub = localStorage.getItem(subCfg.storageKey);
            if (hashRoute.subTab !== currentSub) {
                callSubTabSwitcher(hashRoute.tab, hashRoute.subTab);
            }
        }
    }

    _suppressHashUpdate = false;
}
