// cookie-banner.jsx - LGPD-compliant cookie consent banner.
// Persists choice in localStorage; banner appears only on first visit
// or when user has not yet made a choice. Three actions: Accept all,
// Reject (essential only), or Read policy.
const { useState: useStateCB, useEffect: useEffectCB } = React;

const COOKIE_STORAGE_KEY = 'sncia_cookie_consent';

const CookieBanner = () => {
  const { lang } = useLang();
  const [visible, setVisible] = useStateCB(false);

  useEffectCB(() => {
    try {
      const saved = localStorage.getItem(COOKIE_STORAGE_KEY);
      if (!saved) {
        // Defer reveal to avoid jarring flash on initial paint
        const t = setTimeout(() => setVisible(true), 800);
        return () => clearTimeout(t);
      }
    } catch (e) { /* localStorage may be blocked; show banner safely */
      setVisible(true);
    }
  }, []);

  const persist = (choice) => {
    try {
      localStorage.setItem(COOKIE_STORAGE_KEY, JSON.stringify({
        choice,
        at: new Date().toISOString(),
        v: 1
      }));
    } catch (e) { /* ignore - best-effort */ }
    setVisible(false);
    // Notify the rest of the app (e.g. analytics gating)
    window.dispatchEvent(new CustomEvent('sncia:cookie-consent', { detail: { choice } }));
  };

  const openPrivacy = (e) => {
    e.preventDefault();
    window.dispatchEvent(new CustomEvent('sncia:open-legal', { detail: { which: 'privacy' } }));
  };

  if (!visible) return null;

  const T = lang === 'pt' ? {
    title: 'Sua privacidade',
    body: 'Utilizamos cookies essenciais para o funcionamento do site e cookies analíticos para entender como você navega e melhorar a experiência. Você pode aceitar todos ou recusar os opcionais.',
    accept: 'Aceitar todos',
    reject: 'Apenas essenciais',
    learn: 'Saiba mais'
  } : {
    title: 'Your privacy',
    body: 'We use essential cookies to run this site and analytics cookies to understand how you browse and improve the experience. You can accept all or decline the optional ones.',
    accept: 'Accept all',
    reject: 'Essentials only',
    learn: 'Learn more'
  };

  return (
    <div
      className="cookie-banner"
      role="dialog"
      aria-modal="false"
      aria-labelledby="cookie-banner-title"
      aria-describedby="cookie-banner-body">
      <div className="cookie-banner-inner">
        <div className="cookie-banner-text">
          <h4 id="cookie-banner-title">{T.title}</h4>
          <p id="cookie-banner-body">
            {T.body}{' '}
            <a href="#privacy" onClick={openPrivacy} className="cookie-link">{T.learn}</a>
          </p>
        </div>
        <div className="cookie-banner-actions">
          <button type="button" className="cta-btn ghost" onClick={() => persist('essentials')}>
            {T.reject}
          </button>
          <button type="button" className="cta-btn" onClick={() => persist('all')}>
            {T.accept}
          </button>
        </div>
      </div>
    </div>
  );
};

window.CookieBanner = CookieBanner;
