const THEME_KEY = 'theme'
const THEME_COOKIE_MAX_AGE = 60 * 60 * 24 * 365

export const getSavedTheme = () => {
    if (typeof window === 'undefined') return null

    try {
        const stored = localStorage.getItem(THEME_KEY)
        if (stored === 'dark' || stored === 'light') return stored

        const cookieTheme = document.cookie
            .split('; ')
            .find((entry) => entry.startsWith(`${THEME_KEY}=`))
            ?.split('=')[1]

        if (cookieTheme === 'dark' || cookieTheme === 'light') return cookieTheme
    } catch {
        // ignore storage access issues
    }

    return null
}

export const saveTheme = (theme) => {
    if (typeof window === 'undefined') return

    try {
        localStorage.setItem(THEME_KEY, theme)
        document.cookie = `${THEME_KEY}=${theme}; path=/; max-age=${THEME_COOKIE_MAX_AGE}; SameSite=Lax`
    } catch {
        // ignore storage access issues
    }
}

export const applyTheme = (theme) => {
    if (typeof document === 'undefined') return

    document.documentElement.setAttribute('data-theme', theme)
    saveTheme(theme)
}
