// site/consent-banner.jsx — GDPR consent banner.
// (Filename intentionally avoids "cookie" so ad/content blockers don't drop it.)
// Stores choice in localStorage under 'showtime-cookie-consent'.
// Values: 'all' | 'essential'. No value = not yet decided → show banner.
// Future tracker scripts should check useCookieConsent() before loading.

const CONSENT_KEY = 'showtime-cookie-consent';

function readConsent() {
  try { return localStorage.getItem(CONSENT_KEY); } catch (e) { return 'essential'; }
}

function writeConsent(value) {
  try { localStorage.setItem(CONSENT_KEY, value); } catch (e) {}
}

function useCookieConsent() {
  const [consent, setConsent] = React.useState(() => readConsent());
  const decide = React.useCallback((value) => {
    writeConsent(value);
    setConsent(value);
    if (value === 'all' && typeof window.grantAnalyticsConsent === 'function') {
      window.grantAnalyticsConsent();
    }
  }, []);
  return { consent, decide };
}

function CookieBanner() {
  const { consent, decide } = useCookieConsent();
  const t = useT();

  if (consent !== null) return null;

  return (
    <div className="sw-cookie-banner" role="dialog" aria-label="Cookie consent">
      <p className="sw-cookie-banner__text">
        {t('cookie.body')}{' '}
        <a className="sw-cookie-banner__link" href="/cookie-policy/">{t('cookie.policy')}</a>
      </p>
      <div className="sw-cookie-banner__actions">
        <button className="sw-btn sw-btn--ghost sw-btn--ghost-dark sw-btn--sm" onClick={() => decide('essential')}>
          {t('cookie.essential')}
        </button>
        <button className="sw-btn sw-btn--yellow sw-btn--sm" onClick={() => decide('all')}>
          {t('cookie.accept')}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { useCookieConsent, CookieBanner });
