import { useEffect, useState } from 'react';

// Three UI themes: light (default), mid (soft dark), dark (full dark).
// The value lands on <html data-theme="…"> and app/globals.css remaps the
// light-utility classes for mid/dark. Persisted in localStorage('theme').
export type Theme = 'light' | 'mid' | 'dark';
export const THEMES: Theme[] = ['light', 'mid', 'dark'];

const LEGACY_MAP: Record<string, Theme> = {
    corporate: 'light',   // old daisyui light theme name
    dark: 'dark',
};

export function normalizeTheme(raw: string | null): Theme {
    if (raw && (THEMES as string[]).includes(raw)) return raw as Theme;
    if (raw && LEGACY_MAP[raw]) return LEGACY_MAP[raw];
    return 'light';
}

export function applyTheme(t: Theme) {
    const html = document.documentElement;
    html.setAttribute('data-theme', t);
    // keep the tailwind `dark` class in sync for any dark: variants
    html.classList.toggle('dark', t !== 'light');
}

const useTheme = () => {
    const [theme, setThemeState] = useState<Theme>('light');

    const setTheme = (t: Theme) => {
        setThemeState(t);
        localStorage.setItem('theme', t);
        applyTheme(t);
    };

    // cycle light → mid → dark → light
    const toggleTheme = () => {
        const next = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
        setTheme(next);
    };

    useEffect(() => {
        const t = normalizeTheme(localStorage.getItem('theme'));
        setThemeState(t);
        applyTheme(t);
    }, []);

    return { theme, setTheme, toggleTheme };
};

export default useTheme;
