'use client';

import {createContext, useEffect, useState} from "react";
import Cookies from "js-cookie";

type ThemeType = "light" | "dark";

export const ThemeContext = createContext<{
    theme: ThemeType;
    toggleTheme: () => void;
}>({
    theme: "light",
    toggleTheme: () => {
    },
});

export const ThemeProvider = ({children}: { children: React.ReactNode }) => {
    const [theme, setTheme] = useState<ThemeType | null>(null);

    useEffect(() => {
        const saved = Cookies.get("theme") as ThemeType | undefined;
        if (saved === "dark" || saved === "light") {
            setTheme(saved);
        } else {
            const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
            const defaultTheme: ThemeType = prefersDark ? "dark" : "light";
            setTheme(defaultTheme);
            Cookies.set("theme", defaultTheme, {expires: 365});
        }
    }, []);

    useEffect(() => {
        if (!theme) return;
        document.documentElement.setAttribute("data-theme", theme);
    }, [theme]);

    const toggleTheme = () => {
        const next = theme === "dark" ? "light" : "dark";
        setTheme(next);
        Cookies.set("theme", next, {expires: 365});
    };

    if (!theme) return null;

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