import { useState, useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { Link } from 'react-router-dom'; import { Cookie, X } from 'lucide-react'; const CONSENT_KEY = 'cookie_consent'; const CONSENT_VERSION = '1'; type ConsentState = 'pending' | 'accepted' | 'rejected'; function getStoredConsent(): ConsentState { try { const raw = localStorage.getItem(CONSENT_KEY); if (!raw) return 'pending'; const parsed = JSON.parse(raw); if (parsed?.version === CONSENT_VERSION) return parsed.state as ConsentState; return 'pending'; } catch { return 'pending'; } } function storeConsent(state: ConsentState) { localStorage.setItem( CONSENT_KEY, JSON.stringify({ state, version: CONSENT_VERSION, timestamp: Date.now() }), ); } /** * Emit a custom event so analytics.ts can listen for consent changes. */ function dispatchConsentEvent(accepted: boolean) { window.dispatchEvent( new CustomEvent('cookie-consent', { detail: { accepted } }), ); } export function hasAnalyticsConsent(): boolean { return getStoredConsent() === 'accepted'; } export default function CookieConsent() { const { t } = useTranslation(); const [visible, setVisible] = useState(false); useEffect(() => { if (getStoredConsent() === 'pending') { // Small delay so it doesn't block LCP const timer = setTimeout(() => setVisible(true), 1500); return () => clearTimeout(timer); } }, []); function handleAccept() { storeConsent('accepted'); dispatchConsentEvent(true); setVisible(false); } function handleReject() { storeConsent('rejected'); dispatchConsentEvent(false); setVisible(false); } if (!visible) return null; return (
{t( 'cookie.message', 'We use essential cookies for site functionality and optional analytics cookies (Google Analytics) to improve your experience. You can accept or reject non-essential cookies.', )}{' '} {t('cookie.learnMore', 'Learn more')}