// CookieConsent — GDPR-compliant, two-level UX
// Level 1: simple banner  →  Level 2: granular settings
// GA4: G-L21WP3BF8G  ·  FB Pixel: 1187015862786796

const { useState: useCookieState, useEffect: useCookieEffect } = React;

const CONSENT_KEY     = 'galandrai_cookie_consent';
const CONSENT_VERSION = 1;
const GA4_ID          = 'G-L21WP3BF8G';
const FB_PIXEL_ID     = '1187015862786796';
const GDPR_URL        = '/zasady-ochrany-osobnich-udaju'; // ← doplňte URL vaší GDPR stránky

/* ─── Script loaders (fire once) ───────────────────────────────────── */
function loadGA4() {
  if (window.__GA4_LOADED__) return;
  window.__GA4_LOADED__ = true;
  const s = document.createElement('script');
  s.async = true;
  s.src = `https://www.googletagmanager.com/gtag/js?id=${GA4_ID}`;
  document.head.appendChild(s);
  window.dataLayer = window.dataLayer || [];
  window.gtag = function () { window.dataLayer.push(arguments); };
  window.gtag('js', new Date());
  window.gtag('config', GA4_ID, { anonymize_ip: true });
}

function loadFBPixel() {
  if (window.__FB_PIXEL_LOADED__) return;
  window.__FB_PIXEL_LOADED__ = true;
  !function(f,b,e,v,n,t,s){
    if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s);
  }(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');
  window.fbq('init', FB_PIXEL_ID);
  window.fbq('track', 'PageView');
}

function applyConsent(c) {
  if (c.analytics) loadGA4();
  if (c.marketing) loadFBPixel();
}

/* ─── Checkbox ──────────────────────────────────────────────────────── */
function Checkbox({ checked, locked }) {
  return (
    <span style={{
      width: '22px', height: '22px', borderRadius: '5px', flexShrink: 0,
      border: `2px solid ${checked ? (locked ? 'rgba(255,255,255,0.25)' : 'var(--accent)') : 'rgba(255,255,255,0.2)'}`,
      background: checked ? (locked ? 'rgba(255,255,255,0.12)' : 'var(--accent)') : 'transparent',
      display: 'grid', placeItems: 'center',
      transition: 'all 200ms',
    }}>
      {checked && (
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
          stroke={locked ? 'rgba(255,255,255,0.5)' : 'white'}
          strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
      )}
    </span>
  );
}

/* ─── Category row ──────────────────────────────────────────────────── */
function CategoryRow({ title, desc, checked, onChange, locked, last }) {
  return (
    <div>
      <button
        onClick={() => !locked && onChange(!checked)}
        style={{
          width: '100%', background: 'none', border: 'none',
          padding: '18px 0 14px', cursor: locked ? 'default' : 'pointer',
          textAlign: 'left', display: 'flex', alignItems: 'flex-start', gap: '14px',
        }}
      >
        <Checkbox checked={checked} locked={locked} />
        <span style={{ flex: 1 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
            <span style={{
              fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '15px',
              color: 'var(--text-primary)', letterSpacing: '-0.01em',
            }}>{title}</span>
            {locked && (
              <span style={{
                fontFamily: 'var(--font-mono)', fontSize: '9px', letterSpacing: '0.1em',
                textTransform: 'uppercase',
                border: '1px solid rgba(255,255,255,0.18)',
                borderRadius: '4px', padding: '2px 7px',
                color: 'var(--text-tertiary)',
              }}>vždy aktivní</span>
            )}
          </span>
          <span style={{
            display: 'block', marginTop: '6px',
            fontFamily: 'var(--font-body)', fontSize: '13px',
            color: 'var(--text-tertiary)', lineHeight: 1.55,
          }}>{desc}</span>
        </span>
      </button>
      {!last && <div style={{ height: '1px', background: 'var(--border-subtle)' }} />}
    </div>
  );
}

/* ─── Modal card wrapper ────────────────────────────────────────────── */
function ModalWrap({ children }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '20px', cursor: 'none',
    }}>
      <div style={{
        width: '100%', maxWidth: '440px',
        background: '#111113',
        border: '1px solid rgba(255,255,255,0.1)',
        borderRadius: '16px',
        boxShadow: '0 40px 100px rgba(0,0,0,0.85)',
        overflow: 'hidden',
      }}>
        {children}
      </div>
    </div>
  );
}

/* ─── Shared button styles ──────────────────────────────────────────── */
const btnBase = {
  flex: 1, padding: '13px 16px', borderRadius: '8px',
  fontFamily: 'var(--font-display)', fontWeight: 600,
  fontSize: '14px', letterSpacing: '-0.01em',
  cursor: 'pointer', border: 'none',
  transition: 'background 200ms, color 200ms',
};
const btnPrimary = { ...btnBase, background: 'var(--accent)', color: '#fff' };
const btnSecondary = {
  ...btnBase,
  background: 'rgba(255,255,255,0.06)',
  border: '1px solid rgba(255,255,255,0.1)',
  color: 'var(--text-primary)',
};

/* ─── Level 1: Banner ───────────────────────────────────────────────── */
function BannerView({ onAcceptAll, onRejectAll, onSettings }) {
  return (
    <ModalWrap>
      <div style={{ padding: '24px 24px 20px' }}>
        <h2 style={{
          fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: '18px', letterSpacing: '-0.02em',
          color: 'var(--text-primary)', margin: '0 0 12px',
          display: 'flex', alignItems: 'center', gap: '8px',
        }}>
          <span>🍪</span> Tento web používá cookies
        </h2>
        <p style={{
          fontFamily: 'var(--font-body)', fontSize: '13px',
          color: 'var(--text-secondary)', lineHeight: 1.6, margin: '0',
        }}>
          Používáme nezbytné cookies pro chod webu a s vaším souhlasem i analytické
          a marketingové cookies, abychom věděli, co vás zajímá.{' '}
          <a href={GDPR_URL} style={{ color: 'var(--accent)', textDecoration: 'underline', textUnderlineOffset: '3px' }}>
            Zásady ochrany osobních údajů
          </a>.
        </p>
      </div>

      <div style={{ padding: '0 24px 24px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
        {/* Odmítnout / Přijmout */}
        <div style={{ display: 'flex', gap: '8px' }}>
          <button
            onClick={onRejectAll}
            style={btnSecondary}
            onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
            onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
          >Odmítnout vše</button>
          <button
            onClick={onAcceptAll}
            style={btnPrimary}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--accent-hover)'}
            onMouseLeave={e => e.currentTarget.style.background = 'var(--accent)'}
          >Přijmout vše</button>
        </div>
        {/* Nastavení */}
        <button
          onClick={onSettings}
          style={{ ...btnSecondary, flex: 'none', width: '100%', textAlign: 'center' }}
          onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
          onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
        >Nastavení</button>
      </div>
    </ModalWrap>
  );
}

/* ─── Level 2: Settings ─────────────────────────────────────────────── */
function SettingsView({ onBack, onSave }) {
  const [analytics, setAnalytics] = useCookieState(false);
  const [marketing, setMarketing] = useCookieState(false);

  const categories = [
    {
      title: 'Nezbytné cookies',
      desc: 'Zajišťují základní funkčnost webu (session, zabezpečení). Jsou aktivní vždy a nelze je odmítnout, neboť bez nich by web nefungoval správně.',
      checked: true, locked: true,
      onChange: () => {},
    },
    {
      title: 'Analytické cookies (Google Analytics)',
      desc: 'Anonymizované statistiky o návštěvnosti a chování uživatelů na webu. Tato data není možné spojit s konkrétní osobou. Aktivují se pouze po udělení vašeho souhlasu.',
      checked: analytics, locked: false,
      onChange: setAnalytics,
    },
    {
      title: 'Marketingové cookies (Meta Pixel)',
      desc: 'Slouží pro cílené zobrazení reklam a měření výkonu reklamních kampaní na platformách Meta (Facebook, Instagram). Aktivují se pouze po udělení vašeho souhlasu.',
      checked: marketing, locked: false,
      onChange: setMarketing,
    },
  ];

  return (
    <ModalWrap>
      <div style={{ padding: '22px 24px 0' }}>
        <h2 style={{
          fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: '18px', letterSpacing: '-0.02em',
          color: 'var(--text-primary)', margin: '0 0 4px',
        }}>Nastavení cookies</h2>
      </div>

      <div style={{ padding: '0 24px' }}>
        {categories.map((cat, i) => (
          <CategoryRow
            key={i}
            {...cat}
            last={i === categories.length - 1}
          />
        ))}
      </div>

      <div style={{ padding: '16px 24px 24px', display: 'flex', gap: '8px' }}>
        <button
          onClick={onBack}
          style={btnSecondary}
          onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
          onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
        >Zpět</button>
        <button
          onClick={() => onSave(analytics, marketing)}
          style={btnPrimary}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--accent-hover)'}
          onMouseLeave={e => e.currentTarget.style.background = 'var(--accent)'}
        >Uložit nastavení</button>
      </div>
    </ModalWrap>
  );
}

/* ─── Floating re-open button ───────────────────────────────────────── */
function CookieFloatBtn({ onClick }) {
  const [hov, setHov] = useCookieState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      title="Nastavení cookies"
      style={{
        position: 'fixed', bottom: '24px', left: '39px', zIndex: 8000,
        width: hov ? '136px' : '40px', height: '40px',
        borderRadius: '20px', border: '1px solid rgba(255,255,255,0.12)',
        background: 'rgba(17,17,19,0.92)',
        backdropFilter: 'blur(12px)',
        cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: '7px',
        padding: '0 0 0 11px', overflow: 'hidden',
        transition: 'width 280ms cubic-bezier(0.65,0,0.35,1), box-shadow 200ms',
        boxShadow: hov ? '0 4px 20px rgba(0,0,0,0.5)' : '0 2px 10px rgba(0,0,0,0.4)',
      }}
    >
      <span style={{ fontSize: '15px', flexShrink: 0, lineHeight: 1 }}>🍪</span>
      <span style={{
        fontFamily: 'var(--font-mono)', fontSize: '10px', letterSpacing: '0.08em',
        textTransform: 'uppercase', color: 'var(--text-secondary)',
        whiteSpace: 'nowrap',
        opacity: hov ? 1 : 0,
        transition: 'opacity 180ms',
      }}>Cookies</span>
    </button>
  );
}

/* ─── Root ──────────────────────────────────────────────────────────── */
function CookieConsent() {
  const [consent,   setConsent]   = useCookieState(null);
  const [view, setView] = useCookieState('hidden'); // 'hidden' | 'banner' | 'settings'

  useCookieEffect(() => {
    try {
      const raw = localStorage.getItem(CONSENT_KEY);
      if (raw) {
        const stored = JSON.parse(raw);
        if (stored.version !== CONSENT_VERSION) {
          setView('banner');
        } else {
          setConsent(stored);
          applyConsent(stored);
          setView('hidden');
        }
      } else {
        setView('banner');
      }
    } catch {
      setView('banner');
    }
  }, []);

  const save = (analytics, marketing) => {
    const c = {
      version: CONSENT_VERSION,
      timestamp: new Date().toISOString(),
      necessary: true, analytics, marketing,
    };
    try { localStorage.setItem(CONSENT_KEY, JSON.stringify(c)); } catch {}
    setConsent(c);
    applyConsent(c);
    setView('hidden');
  };

  return (
    <>
      {view === 'banner'   && (
        <BannerView
          onAcceptAll={() => save(true, true)}
          onRejectAll={() => save(false, false)}
          onSettings={() => setView('settings')}
        />
      )}
      {view === 'settings' && (
        <SettingsView
          onBack={() => setView('banner')}
          onSave={save}
        />
      )}
      {view === 'hidden' && consent && (
        <CookieFloatBtn onClick={() => setView('banner')} />
      )}
    </>
  );
}

window.CookieConsent = CookieConsent;
