'use client';

/**
 * Theme context for the Executive dashboard. Renders the `.noc` root that
 * scopes every design token (theme.css) and carries `data-mode="dark|light"`.
 * Dark is primary; the choice persists to localStorage. Wrap the whole
 * /executive subtree (including /wall) in this.
 */
import { createContext, useCallback, useContext, useEffect, useState } from 'react';

type Mode = 'dark' | 'light';

interface ThemeCtx {
    mode: Mode;
    toggle: () => void;
    setMode: (m: Mode) => void;
}

const Ctx = createContext<ThemeCtx | null>(null);
const STORAGE_KEY = 'exec-theme';

export function ThemeProvider({
    children,
    initialMode = 'dark',
}: {
    children: React.ReactNode;
    initialMode?: Mode;
}) {
    const [mode, setModeState] = useState<Mode>(initialMode);

    useEffect(() => {
        try {
            const saved = localStorage.getItem(STORAGE_KEY) as Mode | null;
            // localStorage is client-only; read it after mount to avoid a
            // hydration mismatch (server can't know the saved theme). Intentional.
            // eslint-disable-next-line react-hooks/set-state-in-effect
            if (saved === 'dark' || saved === 'light') setModeState(saved);
        } catch {
            /* localStorage unavailable — keep default */
        }
    }, []);

    const setMode = useCallback((m: Mode) => {
        setModeState(m);
        try {
            localStorage.setItem(STORAGE_KEY, m);
        } catch {
            /* ignore */
        }
    }, []);

    const toggle = useCallback(() => {
        setModeState((prev) => {
            const next = prev === 'dark' ? 'light' : 'dark';
            try {
                localStorage.setItem(STORAGE_KEY, next);
            } catch {
                /* ignore */
            }
            return next;
        });
    }, []);

    return (
        <Ctx.Provider value={{ mode, toggle, setMode }}>
            {/* Fixed-viewport, non-scrolling root: the Executive app is built for
                projection on a fixed landscape screen — every page fits 100vh and
                clips rather than scrolls. */}
            <div className="noc" data-mode={mode} style={{ height: '100vh', overflow: 'hidden' }}>
                {children}
            </div>
        </Ctx.Provider>
    );
}

export function useTheme(): ThemeCtx {
    const ctx = useContext(Ctx);
    if (!ctx) throw new Error('useTheme must be used within <ThemeProvider>');
    return ctx;
}
