"use client";

import { createContext, useCallback, useContext, useEffect, useState } from "react";

interface AppContextValue {
    theme: "dark" | "light";
    toggleTheme: () => void;
}

const AppContext = createContext<AppContextValue | null>(null);

function getInitialTheme(): "dark" | "light" {
    if (typeof window === "undefined") return "dark";
    const stored = localStorage.getItem("tools-hub-theme");
    if (stored === "light" || stored === "dark") return stored;
    return "dark";
}

function applyTheme(theme: "dark" | "light") {
    if (typeof document === "undefined") return;
    const html = document.documentElement;
    if (theme === "light") {
        html.classList.add("light");
    } else {
        html.classList.remove("light");
    }
}

export function AppProvider({ children }: { children: React.ReactNode }) {
    const [theme, setThemeState] = useState<"dark" | "light">("dark");

    useEffect(() => {
        const initial = getInitialTheme();
        setThemeState(initial);
        applyTheme(initial);
    }, []);

    const setTheme = useCallback((value: "dark" | "light") => {
        setThemeState(value);
        applyTheme(value);
        localStorage.setItem("tools-hub-theme", value);
    }, []);

    const toggleTheme = useCallback(() => {
        setTheme(theme === "dark" ? "light" : "dark");
    }, [theme, setTheme]);

    return (
        <AppContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </AppContext.Provider>
    );
}

export function useApp(): AppContextValue {
    const context = useContext(AppContext);
    if (!context) {
        throw new Error("useApp must be used within an AppProvider");
    }
    return context;
}
