// ==========================================
// Debug Modal — Root Component
// ==========================================
// Preact modal with tabs: Console, Network, State, REPL.
// Global overlay — not a routed surface.
// Mounts via mountDebugModal(el, engine).
//
// v0.37.18: Preact rebuild of debug modal (CR P2-5).

import { debugEngine } from './engine.js';
import { ConsoleTab } from './console-tab.js';
import { NetworkTab } from './network-tab.js';
import { StateTab } from './state-tab.js';
import { ReplTab } from './repl-tab.js';
import { DebugBadge } from './badge.js';

const { h, render } = window.preact;
const html = window.html;
const { useState, useEffect, useCallback, useRef } = window.hooks;

const TABS = ['console', 'network', 'state', 'repl'];

function DebugModal({ engine }) {
    const [open, setOpen] = useState(false);
    const [activeTab, setActiveTab] = useState('console');
    const [tick, setTick] = useState(0);
    const overlayRef = useRef(null);

    // Subscribe to engine for reactive re-render
    useEffect(() => {
        return engine.subscribe(() => setTick(t => t + 1));
    }, [engine]);

    // Listen for toggle events (Ctrl+Shift+L, badge click)
    useEffect(() => {
        const toggle = () => setOpen(prev => !prev);
        window.addEventListener('debug:toggle', toggle);
        return () => window.removeEventListener('debug:toggle', toggle);
    }, []);

    // Expose global open/close for backward compat
    useEffect(() => {
        window.openDebugModal = () => setOpen(true);
        window.closeDebugModal = () => setOpen(false);
    }, []);

    // Close on overlay click
    const onOverlayClick = useCallback((e) => {
        if (e.target === overlayRef.current) setOpen(false);
    }, []);

    // Close on Escape
    useEffect(() => {
        if (!open) return;
        const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
        document.addEventListener('keydown', onKey);
        return () => document.removeEventListener('keydown', onKey);
    }, [open]);

    const onClear = useCallback(async () => {
        if (window.sw?.confirm) {
            const ok = await window.sw.confirm('Clear all debug logs?');
            if (!ok) return;
        }
        engine.clear();
    }, [engine]);

    const onPurge = useCallback(async () => {
        if (window.sw?.confirm) {
            const ok = await window.sw.confirm(
                'Purge all cached files and reload?\n\n' +
                'This clears the Service Worker cache and forces a fresh download of all assets.'
            );
            if (!ok) return;
        }
        engine.purgeCache();
    }, [engine]);

    return html`
        <${DebugBadge} engine=${engine} />
        ${open && html`
            <div class="modal-overlay active" ref=${overlayRef} onClick=${onOverlayClick}>
                <div class="modal modal-wide">
                    <div class="modal-header">
                        <h2>Debug Log</h2>
                        <button class="modal-close" onClick=${() => setOpen(false)}>\u2715</button>
                    </div>
                    <div class="modal-tabs">
                        ${TABS.map(tab => html`
                            <button key=${tab}
                                    class="debug-tab${activeTab === tab ? ' active' : ''}${tab === 'repl' && !_replVisible() ? ' debug-tab--hidden' : ''}"
                                    onClick=${() => setActiveTab(tab)}>
                                ${tab.charAt(0).toUpperCase() + tab.slice(1)}
                                ${tab === 'console' && html`${' '}<span class="badge">${engine.entries.length}</span>`}
                                ${tab === 'network' && html`${' '}<span class="badge">${engine.networkLog.length}</span>`}
                            </button>`)}
                    </div>
                    <div class="modal-body debug-modal-body">
                        ${activeTab === 'console' && html`<${ConsoleTab} entries=${engine.entries} />`}
                        ${activeTab === 'network' && html`<${NetworkTab} networkLog=${engine.networkLog} />`}
                        ${activeTab === 'state' && html`<${StateTab} engine=${engine} />`}
                        ${activeTab === 'repl' && html`<${ReplTab} visible=${true} />`}
                    </div>
                    <div class="modal-footer debug-modal-footer">
                        <div class="debug-footer-left">
                            <button class="btn-danger btn-small" onClick=${() => { setActiveTab('console'); engine.runDiagnostics(); }}>Diagnostics</button>
                            <button class="btn-danger btn-small" onClick=${onPurge}>Purge Cache</button>
                        </div>
                        <div class="debug-footer-right">
                            <button class="btn-secondary btn-small" onClick=${onClear}>Clear</button>
                            <button class="btn-secondary btn-small" onClick=${() => engine.copyLog()}>Copy</button>
                            <button class="btn-secondary btn-small" onClick=${() => engine.downloadLog()}>Export</button>
                        </div>
                    </div>
                </div>
            </div>`}`;
}

function _replVisible() {
    const isAdmin = window.sw?.auth?.user?.role === 'admin';
    const debugParam = new URLSearchParams(window.location.search).has('debug');
    return isAdmin || debugParam;
}

/**
 * Mount the debug modal into a target element.
 * Call after Preact globals are available.
 */
export function mountDebugModal(el) {
    if (!el) return;
    render(html`<${DebugModal} engine=${debugEngine} />`, el);
}
