'use client';

import { useState, useEffect, useCallback } from 'react';

export type ConsentLevel = 'all' | 'essential' | null;

interface CookieConsent {
    level: ConsentLevel;
    timestamp: string;
}

const CONSENT_KEY = 'cookie_consent';

/**
 * Hook for managing GDPR-compliant cookie consent
 */
export function useCookieConsent() {
    const [consent, setConsent] = useState<CookieConsent | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    // Load consent from localStorage on mount
    useEffect(() => {
        try {
            const stored = localStorage.getItem(CONSENT_KEY);
            if (stored) {
                setConsent(JSON.parse(stored));
            }
        } catch (e) {
            console.warn('[CookieConsent] Failed to load consent:', e);
        }
        setIsLoading(false);
    }, []);

    // Accept all cookies (essential + functional)
    const acceptAll = useCallback(() => {
        const newConsent: CookieConsent = {
            level: 'all',
            timestamp: new Date().toISOString(),
        };
        localStorage.setItem(CONSENT_KEY, JSON.stringify(newConsent));
        setConsent(newConsent);
    }, []);

    // Accept only essential cookies
    const acceptEssential = useCallback(() => {
        const newConsent: CookieConsent = {
            level: 'essential',
            timestamp: new Date().toISOString(),
        };
        localStorage.setItem(CONSENT_KEY, JSON.stringify(newConsent));
        setConsent(newConsent);
    }, []);

    // Reset consent (for settings page)
    const resetConsent = useCallback(() => {
        localStorage.removeItem(CONSENT_KEY);
        setConsent(null);
    }, []);

    return {
        hasConsent: consent !== null,
        consentLevel: consent?.level ?? null,
        consentTimestamp: consent?.timestamp ?? null,
        isLoading,
        acceptAll,
        acceptEssential,
        resetConsent,
    };
}
