/**
 * Cross-entity navigation — navigate to a specific card on any tab/subtab.
 */

import { switchTab } from '../features/tabs.ts';

/**
 * Navigate to a card on any tab/subtab, expanding the section and scrolling to it.
 *
 * @param {string} tab        Main tab: 'dashboard' | 'automations' | 'targets' | 'streams'
 * @param {string|null} subTab  Sub-tab key or null
 * @param {string|null} sectionKey  CardSection key to expand, or null
 * @param {string} cardAttr   Data attribute to find the card (e.g. 'data-device-id')
 * @param {string} cardValue  Value of the data attribute
 */
export function navigateToCard(tab: string, subTab: string | null, sectionKey: string | null, cardAttr: string, cardValue: string) {
    // Push current location to history so browser back returns here
    history.pushState(null, '', location.hash || '#');

    // Switch to the target tab, allowing data load if needed.
    // skipLoad only when tab data is already in the DOM (cards exist).
    const tabPanel = document.getElementById(`tab-${tab}`);
    const hasCards = tabPanel && tabPanel.querySelector('.card');
    switchTab(tab, { skipLoad: !!hasCards });

    requestAnimationFrame(() => {
        if (subTab) {
            if (tab === 'targets' && typeof window.switchTargetSubTab === 'function') {
                window.switchTargetSubTab(subTab);
            } else if (tab === 'streams' && typeof window.switchStreamTab === 'function') {
                window.switchStreamTab(subTab);
            } else if (tab === 'automations' && typeof window.switchAutomationTab === 'function') {
                window.switchAutomationTab(subTab);
            }
        }

        // Expand section if collapsed
        if (sectionKey) {
            const content = document.querySelector(`[data-cs-content="${CSS.escape(sectionKey)}"]`) as HTMLElement | null;
            const header = document.querySelector(`[data-cs-toggle="${CSS.escape(sectionKey)}"]`);
            if (content && content.style.display === 'none') {
                content.style.display = '';
                const chevron = header?.querySelector('.cs-chevron') as HTMLElement | null;
                if (chevron) chevron.style.transform = 'rotate(90deg)';
                const map = JSON.parse(localStorage.getItem('sections_collapsed') || '{}');
                map[sectionKey] = false;
                localStorage.setItem('sections_collapsed', JSON.stringify(map));
            }
        }

        // Scope card search to the destination tab panel (avoid matching
        // dashboard cards that share the same data-* attributes).
        const tabPanel = document.getElementById(`tab-${tab}`);
        const scope = tabPanel || document;

        // Check if card already exists (data previously loaded)
        const existing = scope.querySelector(`[${cardAttr}="${CSS.escape(cardValue)}"]`);
        if (existing) {
            _highlightCard(existing);
            return;
        }

        // Card not in DOM — trigger data load and wait for it to appear
        _triggerTabLoad(tab);
        _waitForCard(cardAttr, cardValue, 5000, scope).then((card: any) => {
            if (card) _highlightCard(card);
        });
    });
}

let _highlightTimer: ReturnType<typeof setTimeout> | 0 = 0;
let _overlayTimer: ReturnType<typeof setTimeout> | 0 = 0;
let _prevCard: Element | null = null;

function _highlightCard(card: Element) {
    // Clear previous highlight if still active
    if (_prevCard) _prevCard.classList.remove('card-highlight');
    clearTimeout(_highlightTimer);

    card.scrollIntoView({ behavior: 'smooth', block: 'center' });
    card.classList.add('card-highlight');
    _prevCard = card;
    _showDimOverlay(2000);
    _highlightTimer = setTimeout(() => {
        card.classList.remove('card-highlight');
        _prevCard = null;
    }, 2000);
}

/** Trigger the tab's data load function (used when card wasn't found in DOM). */
function _triggerTabLoad(tab: string) {
    if (tab === 'dashboard' && typeof window.loadDashboard === 'function') window.loadDashboard();
    else if (tab === 'automations' && typeof window.loadAutomations === 'function') window.loadAutomations();
    else if (tab === 'streams' && typeof window.loadPictureSources === 'function') window.loadPictureSources();
    else if (tab === 'targets' && typeof window.loadTargetsTab === 'function') window.loadTargetsTab();
}

function _showDimOverlay(duration: number) {
    clearTimeout(_overlayTimer);
    let overlay = document.getElementById('nav-dim-overlay');
    if (!overlay) {
        overlay = document.createElement('div');
        overlay.id = 'nav-dim-overlay';
        overlay.className = 'nav-dim-overlay';
        document.body.appendChild(overlay);
    }
    overlay.classList.add('active');
    _overlayTimer = setTimeout(() => overlay.classList.remove('active'), duration);
}

function _waitForCard(cardAttr: string, cardValue: string, timeout: number, scope: Document | HTMLElement = document) {
    const root = scope === document ? document.body : scope as HTMLElement;
    return new Promise(resolve => {
        const card = scope.querySelector(`[${cardAttr}="${CSS.escape(cardValue)}"]`);
        if (card) { resolve(card); return; }

        const timer = setTimeout(() => { observer.disconnect(); resolve(null); }, timeout);
        const observer = new MutationObserver(() => {
            const el = scope.querySelector(`[${cardAttr}="${CSS.escape(cardValue)}"]`);
            if (el) { observer.disconnect(); clearTimeout(timer); resolve(el); }
        });
        observer.observe(root, { childList: true, subtree: true });
    });
}
