const STORAGE_KEY = 'cookie_consent'
const ONE_YEAR_SECONDS = 60 * 60 * 24 * 365

const toBoolean = (value) => value === true

const withRequiredDefaults = (preferences = {}) => ({
    tecnici: true,
    analitici: toBoolean(preferences.analitici),
    profilazione: toBoolean(preferences.profilazione)
})

const normalizeConsent = (value) => {
    if (!value) return null

    if (value === 'accepted_all') {
        return {
            value: 'accepted_all',
            preferences: { tecnici: true, analitici: true, profilazione: true }
        }
    }

    if (value === 'rejected_all') {
        return {
            value: 'rejected_all',
            preferences: { tecnici: true, analitici: false, profilazione: false }
        }
    }

    try {
        const parsed = JSON.parse(value)
        if (parsed?.value !== 'custom') return null
        return {
            value: 'custom',
            preferences: withRequiredDefaults(parsed.preferences)
        }
    } catch {
        return null
    }
}

const serializeConsent = (consent) => {
    if (consent.value === 'accepted_all' || consent.value === 'rejected_all') {
        return consent.value
    }

    return JSON.stringify({
        value: 'custom',
        preferences: withRequiredDefaults(consent.preferences)
    })
}

const setCategoryCookie = (name, granted) => {
    document.cookie = `${name}=${granted ? 'granted' : 'denied'}; path=/; max-age=${ONE_YEAR_SECONDS}; SameSite=Lax`
}

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

    try {
        const raw = localStorage.getItem(STORAGE_KEY)
        return normalizeConsent(raw)
    } catch {
        return null
    }
}

export const applyConsent = (consent) => {
    if (typeof window === 'undefined' || !consent) return

    const preferences = withRequiredDefaults(consent.preferences)
    const root = document.documentElement

    root.dataset.cookieConsent = consent.value
    root.dataset.cookieTecnici = 'granted'
    root.dataset.cookieAnalitici = preferences.analitici ? 'granted' : 'denied'
    root.dataset.cookieProfilazione = preferences.profilazione ? 'granted' : 'denied'

    setCategoryCookie('cm_cookie_tecnici', true)
    setCategoryCookie('cm_cookie_analitici', preferences.analitici)
    setCategoryCookie('cm_cookie_profilazione', preferences.profilazione)

    window.dispatchEvent(
        new CustomEvent('cookie-consent-updated', {
            detail: { value: consent.value, preferences }
        })
    )
}

export const saveConsent = (consent) => {
    if (typeof window === 'undefined' || !consent) return

    try {
        localStorage.setItem(STORAGE_KEY, serializeConsent(consent))
    } catch {
        // no-op if storage is unavailable
    }
}

export const initializeStoredConsent = () => {
    const consent = getStoredConsent()
    if (consent) applyConsent(consent)
    return consent
}
