/* global React */

// ─── Consent storage ────────────────────────────────────────────────────────
const CONSENT_KEY = 'fromberg-cookie-consent';
// 2.0: Cookiebot-stijl banner + Google Consent Mode v2. Versie-bump = iedereen
// opnieuw om toestemming vragen (nodig omdat defaults en signalen veranderd zijn).
const CONSENT_VERSION = '2.0';

function _getStored() {
  try {
    const raw = localStorage.getItem(CONSENT_KEY);
    if (!raw) return null;
    const c = JSON.parse(raw);
    return c.version === CONSENT_VERSION ? c : null;
  } catch (_) { return null; }
}

// Google Consent Mode v2-update (dataLayer bestaat altijd — zie index.html head).
function _applyConsentMode(c) {
  try {
    window.dataLayer = window.dataLayer || [];
    function gtag(){ window.dataLayer.push(arguments); }
    gtag('consent', 'update', {
      ad_storage: c.marketing ? 'granted' : 'denied',
      ad_user_data: c.marketing ? 'granted' : 'denied',
      ad_personalization: c.marketing ? 'granted' : 'denied',
      analytics_storage: c.statistics ? 'granted' : 'denied',
      personalization_storage: c.preferences ? 'granted' : 'denied',
    });
    window.dataLayer.push({ event: 'fromberg_consent_update', consent: c });
  } catch (_) {}
  try {
    if (c.marketing && typeof window.__loadMetaPixel === 'function') {
      window.__loadMetaPixel(); // laadt pixel + PageView bij eerste toestemming
    } else if (!c.marketing && typeof window.fbq === 'function') {
      window.fbq('consent', 'revoke'); // toestemming ingetrokken → data stoppen
    }
  } catch (_) {}
}

function _save(choices) {
  const c = {
    version: CONSENT_VERSION,
    timestamp: new Date().toISOString(),
    necessary: true,
    preferences: !!choices.preferences,
    statistics: !!choices.statistics,
    marketing: !!choices.marketing,
  };
  try { localStorage.setItem(CONSENT_KEY, JSON.stringify(c)); } catch (_) {}
  _applyConsentMode(c);
  try { window.dispatchEvent(new CustomEvent('fromberg:consent', { detail: c })); } catch (_) {}
  return c;
}

// Public API: getCookieConsent('marketing') → true/false
function getCookieConsent(category) {
  if (category === 'necessary') return true;
  const c = _getStored();
  return c ? !!c[category] : false;
}

// Called from Cookies page "Voorkeuren wijzigen" button
function reopenCookieBanner() {
  if (typeof window.__REOPEN_CONSENT === 'function') window.__REOPEN_CONSENT();
}

// ─── Category definitions ────────────────────────────────────────────────────
const CATS = [
  {
    key: 'necessary', locked: true,
    nl: 'Noodzakelijk', en: 'Necessary',
    desc_nl: 'Vereist voor het functioneren van de website (sessiebeheer, beveiliging, opslaan van uw cookievoorkeur). Kan niet worden uitgeschakeld.',
    desc_en: 'Required for the website to work (session management, security, storing your cookie preference). Cannot be disabled.',
  },
  {
    key: 'preferences', locked: false,
    nl: 'Voorkeuren', en: 'Preferences',
    desc_nl: 'Slaat persoonlijke instellingen op zoals uw taalkeuze (NL/EN).',
    desc_en: 'Saves personal settings such as your language preference (NL/EN).',
  },
  {
    key: 'statistics', locked: false,
    nl: 'Statistieken', en: 'Statistics',
    desc_nl: 'Helpt ons te begrijpen hoe bezoekers de website gebruiken, bijvoorbeeld via Google Analytics. Gegevens worden geanonimiseerd verwerkt.',
    desc_en: 'Helps us understand how visitors use the website, e.g. via Google Analytics. Data is processed anonymously.',
  },
  {
    key: 'marketing', locked: false,
    nl: 'Marketing', en: 'Marketing',
    desc_nl: 'Maakt gerichte advertenties mogelijk via Google Ads en Meta (Facebook/Instagram) om het project onder geïnteresseerden te promoten.',
    desc_en: 'Enables targeted advertising via Google Ads and Meta (Facebook/Instagram) to promote the project.',
  },
];

// ─── Banner component ────────────────────────────────────────────────────────
function CookieConsent({ lang }) {
  const t = (nl, en) => lang === 'en' ? en : nl;
  const stored = _getStored();

  const [visible, setVisible] = React.useState(!stored);
  const [showDetails, setShowDetails] = React.useState(false);
  // AVG: niet-noodzakelijke categorieën staan standaard UIT.
  const [prefs, setPrefs] = React.useState({
    preferences: stored ? stored.preferences : false,
    statistics: stored ? stored.statistics : false,
    marketing: stored ? stored.marketing : false,
  });

  React.useEffect(() => {
    window.__REOPEN_CONSENT = () => {
      const s = _getStored();
      if (s) setPrefs({ preferences: s.preferences, statistics: s.statistics, marketing: s.marketing });
      setVisible(true);
    };
    return () => { delete window.__REOPEN_CONSENT; };
  }, []);

  if (!visible) return null;

  const logConsent = async (choices) => {
    try {
      const base = window.FROMBERG_SUPABASE_URL || '';
      const anon = window.FROMBERG_SUPABASE_ANON_KEY || '';
      if (!base || !anon) return;
      // IP ophalen
      let ip = null;
      try {
        const r = await fetch('https://api.ipify.org?format=json', { signal: AbortSignal.timeout(3000) });
        const d = await r.json();
        ip = d.ip || null;
      } catch (_) {}
      await fetch(`${base}/rest/v1/consent_logs`, {
        method: 'POST',
        headers: { apikey: anon, Authorization: `Bearer ${anon}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({
          site: 'fromberg',
          ip_address: ip,
          choices,
          version: CONSENT_VERSION,
          user_agent: navigator.userAgent.slice(0, 300),
        }),
      });
    } catch (_) {}
  };

  const accept = (choices) => {
    _save(choices);
    setVisible(false);
    logConsent(choices); // fire-and-forget
  };

  const btnBase = {
    borderRadius: 6, padding: '11px 14px', fontSize: 13, cursor: 'pointer',
    fontFamily: 'var(--sans)', lineHeight: 1, flex: '1 1 140px', textAlign: 'center',
  };

  return (
    <>
      {/* Backdrop */}
      <div style={{
        position: 'fixed', inset: 0, zIndex: 9998,
        background: 'rgba(20,28,36,0.70)',
        backdropFilter: 'blur(3px)',
      }} />
      {/* Modal */}
      <div style={{
        position: 'fixed',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: 9999,
        background: '#1E2A38',
        border: '1px solid rgba(255,255,255,0.10)',
        borderRadius: 12,
        boxShadow: '0 24px 80px rgba(0,0,0,0.55)',
        width: 'calc(100% - 40px)',
        maxWidth: 620,
        fontFamily: 'var(--sans)',
        maxHeight: '90svh',
        overflowY: 'auto',
      }}>
      <div style={{ padding: '26px 26px 22px' }}>

        {/* Title + intro */}
        <div style={{ fontSize: 15, fontWeight: 600, color: '#F5F0E8', marginBottom: 8 }}>
          {t('Deze website gebruikt cookies', 'This website uses cookies')}
        </div>
        <p style={{ fontSize: 13, color: '#A5B4BE', lineHeight: 1.6, margin: '0 0 18px' }}>
          {t(
            'Wij gebruiken cookies voor een goede werking van de website, voor statistieken en voor gerichte advertenties. Kies hieronder welke cookies u toestaat. Uw keuze kunt u altijd wijzigen via de cookiepagina. ',
            'We use cookies for website functionality, statistics and targeted advertising. Choose below which cookies you allow. You can change your choice at any time via the cookies page. ',
          )}
          <button
            onClick={() => { if (typeof window.__SET_PAGE === 'function') window.__SET_PAGE('privacy'); }}
            style={{ color: '#C8D4DA', textDecoration: 'underline', textUnderlineOffset: 3, background: 'none', border: 'none', cursor: 'pointer', fontSize: 'inherit', padding: 0 }}
          >
            {t('Meer lezen', 'Read more')}
          </button>
        </p>

        {/* Category strip (Cookiebot-stijl: toggles direct zichtbaar) */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
          border: '1px solid rgba(255,255,255,0.10)',
          borderRadius: 8,
          overflow: 'hidden',
          marginBottom: showDetails ? 10 : 18,
        }}>
          {CATS.map((cat, i) => (
            <div key={cat.key} style={{
              display: 'grid', gap: 8, justifyItems: 'center', alignContent: 'center',
              padding: '13px 10px',
              background: 'rgba(255,255,255,0.04)',
              borderLeft: i > 0 ? '1px solid rgba(255,255,255,0.08)' : 'none',
            }}>
              <span style={{ fontSize: 12, fontWeight: 600, color: '#F5F0E8', whiteSpace: 'nowrap' }}>
                {t(cat.nl, cat.en)}
              </span>
              {cat.locked ? (
                <span aria-label={t('Altijd aan', 'Always on')} style={{
                  width: 40, height: 22, borderRadius: 11, background: 'rgba(198,123,58,0.35)',
                  position: 'relative', display: 'block', opacity: 0.75,
                }}>
                  <span style={{
                    position: 'absolute', top: 3, left: 21, width: 16, height: 16,
                    borderRadius: '50%', background: '#fff', display: 'block',
                  }} />
                </span>
              ) : (
                <button
                  role="switch" aria-checked={prefs[cat.key]}
                  aria-label={t(cat.nl, cat.en)}
                  onClick={() => setPrefs(p => ({ ...p, [cat.key]: !p[cat.key] }))}
                  style={{
                    width: 40, height: 22, borderRadius: 11,
                    background: prefs[cat.key] ? '#C67B3A' : 'rgba(255,255,255,0.15)',
                    border: 'none', cursor: 'pointer', position: 'relative', transition: 'background 0.2s',
                  }}
                >
                  <span style={{
                    position: 'absolute', top: 3,
                    left: prefs[cat.key] ? 21 : 3,
                    width: 16, height: 16, borderRadius: '50%',
                    background: '#fff', transition: 'left 0.18s', display: 'block',
                  }} />
                </button>
              )}
            </div>
          ))}
        </div>

        {/* Details: uitleg per categorie */}
        <div style={{ marginBottom: 18 }}>
          <button onClick={() => setShowDetails(d => !d)}
            style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontSize: 12, color: '#637480', textDecoration: 'underline', textUnderlineOffset: 3, fontFamily: 'var(--sans)' }}>
            {showDetails ? t('↑ Details verbergen', '↑ Hide details') : t('Details tonen ↓', 'Show details ↓')}
          </button>
          {showDetails && (
            <div style={{ display: 'grid', gap: 8, marginTop: 10 }}>
              {CATS.map(cat => (
                <div key={cat.key} style={{ background: 'rgba(255,255,255,0.05)', borderRadius: 8, padding: '10px 14px' }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: '#F5F0E8' }}>
                    {t(cat.nl, cat.en)}
                    {cat.locked && (
                      <span style={{ fontSize: 10, color: '#637480', letterSpacing: '0.07em', textTransform: 'uppercase', marginLeft: 8 }}>
                        {t('Altijd aan', 'Always on')}
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 12, color: '#A5B4BE', marginTop: 3, lineHeight: 1.5 }}>{t(cat.desc_nl, cat.desc_en)}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Buttons — weigeren even prominent als toestaan (AVG) */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <button onClick={() => accept({ preferences: false, statistics: false, marketing: false })}
            style={{ ...btnBase, background: 'transparent', color: '#C8D4DA', border: '1px solid rgba(255,255,255,0.22)', fontWeight: 500 }}>
            {t('Weigeren', 'Deny')}
          </button>
          <button onClick={() => accept(prefs)}
            style={{ ...btnBase, background: 'rgba(255,255,255,0.09)', color: '#F5F0E8', border: '1px solid rgba(255,255,255,0.18)', fontWeight: 500 }}>
            {t('Selectie toestaan', 'Allow selection')}
          </button>
          <button onClick={() => {
              setPrefs({ preferences: true, statistics: true, marketing: true });
              setTimeout(() => accept({ preferences: true, statistics: true, marketing: true }), 450);
            }}
            style={{ ...btnBase, background: '#C67B3A', color: '#fff', border: '1px solid #C67B3A', fontWeight: 600 }}>
            {t('Alles toestaan', 'Allow all')}
          </button>
        </div>

      </div>
      </div>
    </>
  );
}

Object.assign(window, { CookieConsent, getCookieConsent, reopenCookieBanner });
