'use client'

import { createContext, useContext, useEffect, useState, ReactNode } from 'react'

type Theme = 'light' | 'dark'

interface ThemeContextType {
    theme: Theme
    toggleTheme: () => void
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined)

export function ThemeProvider({ children }: { children: ReactNode }) {
    const [theme, setTheme] = useState<Theme>('light')
    const [mounted, setMounted] = useState(false)

    useEffect(() => {
        setMounted(true)
        const savedTheme = localStorage.getItem('theme') as Theme | null
        if (savedTheme) {
            setTheme(savedTheme)
        } else {
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
            setTheme(prefersDark ? 'dark' : 'light')
        }
    }, [])

    useEffect(() => {
        if (!mounted) return
        localStorage.setItem('theme', theme)
        const root = document.documentElement
        if (theme === 'dark') {
            root.classList.add('dark')
            root.setAttribute('dark', 'true')
            root.setAttribute('data-theme', 'dark')
        } else {
            root.classList.remove('dark')
            root.removeAttribute('dark')
            root.setAttribute('data-theme', 'light')
        }
    }, [theme, mounted])

    const toggleTheme = () => {
        setTheme((prev) => (prev === 'light' ? 'dark' : 'light'))
    }
    if (!mounted) {
        return <>{children}</>
    }
    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    )
}

export function useTheme() {
    const context = useContext(ThemeContext)
    if (context === undefined) {
        return {
            theme: 'light',
            toggleTheme: () => {
                if (process.env.NODE_ENV !== 'production') {
                    console.warn('useTheme fallback: ThemeProvider is missing in the tree.')
                }
            },
        }
    }
    return context
}

