'use client'
import { useEffect, useState } from 'react'
import type { CookiePreferences, CookieConsentType } from '@/types/cookies'
import { getSavedPreferences } from '@/lib/cookies/utils'

export function useCookieConsent() {
    const [consent, setConsent] = useState<CookieConsentType>(null)
    const [preferences, setPreferences] = useState<CookiePreferences | null>(null)
    const [isInitialized, setIsInitialized] = useState(false)

    useEffect(() => {
        const consent = localStorage.getItem('cookieConsent') as CookieConsentType
        const prefs = getSavedPreferences()

        setConsent(consent)
        setPreferences(prefs)
        setIsInitialized(true)
    }, [])

    // GDPR-compliant check
    const hasConsent = (category: keyof CookiePreferences) => {
        // If not initialized yet, assume no consent
        if (!isInitialized) return false

            // Necessary cookies don't require consent
            if (category === 'necessary') return true

                // If no consent given at all
                if (!consent) return false

                    // If rejected all
                    if (consent === 'rejected') return false

                        // If custom preferences exist
                        if (consent === 'custom' && preferences) {
                            return preferences[category]
                        }

                        // If accepted all
                        return consent === 'accepted'
    }

    return {
        isInitialized,
        consentGiven: consent === 'accepted' || consent === 'custom',
        consentType: consent,
        preferences,
        hasConsent
    }
}
