/* global React */
/* DSGVO-konformer Cookie-Banner mit granularen Kategorien */

const { useState: useStateC, useEffect: useEffectC } = React;

const COOKIE_KEY = 'vc_cookie_consent_v1';
const COOKIE_VERSION = 1;

const DEFAULT_CONSENT = {
  v: COOKIE_VERSION,
  ts: null,
  essential: true,   // nicht abwählbar
  statistik: false,
  marketing: false,
};

function loadConsent() {
  try {
    const raw = localStorage.getItem(COOKIE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (parsed.v !== COOKIE_VERSION) return null;
    return parsed;
  } catch (e) {
    return null;
  }
}

function saveConsent(c) {
  try {
    localStorage.setItem(COOKIE_KEY, JSON.stringify({ ...c, v: COOKIE_VERSION, ts: Date.now() }));
  } catch (e) {}
}

function CookieBanner() {
  const [open, setOpen] = useStateC(false);
  const [expanded, setExpanded] = useStateC(false);
  const [consent, setConsent] = useStateC(DEFAULT_CONSENT);

  useEffectC(() => {
    const existing = loadConsent();
    if (!existing) {
      // Slight delay so the page can paint first
      const t = setTimeout(() => setOpen(true), 800);
      return () => clearTimeout(t);
    } else {
      setConsent(existing);
    }
    // Allow re-open via global hook (footer link)
    window.__openCookieSettings = () => {
      const c = loadConsent() || DEFAULT_CONSENT;
      setConsent(c);
      setExpanded(true);
      setOpen(true);
    };
  }, []);

  const acceptAll = () => {
    const c = { ...DEFAULT_CONSENT, essential: true, statistik: true, marketing: true };
    saveConsent(c);
    setConsent(c);
    setOpen(false);
  };
  const acceptEssential = () => {
    const c = { ...DEFAULT_CONSENT, essential: true, statistik: false, marketing: false };
    saveConsent(c);
    setConsent(c);
    setOpen(false);
  };
  const acceptSelection = () => {
    saveConsent(consent);
    setOpen(false);
  };

  if (!open) return null;

  return (
    <>
      <div className="cb-scrim" onClick={() => {}} />
      <div className="cb" role="dialog" aria-labelledby="cb-title" aria-describedby="cb-desc">
        <div className="cb-head">
          <div className="cb-mark" aria-hidden>
            <svg viewBox="0 0 24 24" width="22" height="22">
              <path d="M12 2 A10 10 0 1 0 22 12 a4 4 0 0 1-4-4 a4 4 0 0 1-4-4 a4 4 0 0 1-2-2 z" fill="var(--brand)" opacity="0.15"/>
              <path d="M12 2 A10 10 0 1 0 22 12 a4 4 0 0 1-4-4 a4 4 0 0 1-4-4 a4 4 0 0 1-2-2 z" fill="none" stroke="var(--brand)" strokeWidth="1.5" strokeLinejoin="round"/>
              <circle cx="9" cy="11" r="1.2" fill="var(--brand-deep)"/>
              <circle cx="13" cy="15" r="1" fill="var(--brand-deep)"/>
              <circle cx="16" cy="11.5" r="0.9" fill="var(--brand-deep)"/>
            </svg>
          </div>
          <div className="cb-title-block">
            <h3 id="cb-title">Datenschutz &amp; Cookies</h3>
            <p id="cb-desc" className="muted">
              Wir verwenden Cookies und ähnliche Technologien, um diese Seite bereitzustellen
              und ihre Nutzung zu analysieren. Sie entscheiden, was Sie zulassen.
            </p>
          </div>
        </div>

        {expanded && (
          <div className="cb-cats">
            <CookieCategory
              title="Notwendig"
              tag="immer aktiv"
              tagTone="ok"
              body="Erforderlich für Grundfunktionen wie Formularschutz, Session-Sicherheit und Spracheinstellungen. Ohne diese funktioniert die Seite nicht."
              detail="Speicherdauer: Session bis 12 Monate · Anbieter: 4its GmbH (Hamburg)"
              checked={true}
              disabled={true}
              onChange={() => {}}
            />
            <CookieCategory
              title="Statistik"
              body="Anonymisierte Reichweitenmessung, damit wir verstehen, welche Inhalte für unsere Kunden relevant sind. IP-Adressen werden gekürzt."
              detail="Speicherdauer: 14 Monate · Anbieter: Matomo (selbst gehostet im 4its-Rechenzentrum)"
              checked={consent.statistik}
              onChange={(v) => setConsent((c) => ({ ...c, statistik: v }))}
            />
            <CookieCategory
              title="Marketing"
              body="Hilft uns, relevante Inhalte und Angebote auf anderen Webseiten anzuzeigen — z. B. LinkedIn-Conversion-Pixel."
              detail="Speicherdauer: bis 24 Monate · Anbieter: LinkedIn Ireland Unlimited Company"
              checked={consent.marketing}
              onChange={(v) => setConsent((c) => ({ ...c, marketing: v }))}
            />
          </div>
        )}

        <div className="cb-meta mono">
          <span><i className="cb-dot" /> Rechtsgrundlage: Art. 6 Abs. 1 lit. a DSGVO · § 25 TTDSG</span>
          <a href="datenschutz.html" target="_blank" rel="noopener">Datenschutzerklärung</a>
          <a href="impressum.html" target="_blank" rel="noopener">Impressum</a>
        </div>

        <div className="cb-actions">
          {!expanded ? (
            <>
              <button className="btn btn-ghost btn-sm" onClick={() => setExpanded(true)}>
                Einstellungen
              </button>
              <button className="btn btn-ghost btn-sm" onClick={acceptEssential}>
                Nur notwendige
              </button>
              <button className="btn btn-brand btn-sm" onClick={acceptAll}>
                Alle akzeptieren
              </button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost btn-sm" onClick={acceptEssential}>
                Nur notwendige
              </button>
              <button className="btn btn-ghost btn-sm" onClick={acceptSelection}>
                Auswahl speichern
              </button>
              <button className="btn btn-brand btn-sm" onClick={acceptAll}>
                Alle akzeptieren
              </button>
            </>
          )}
        </div>
      </div>

      <style>{`
        .cb-scrim {
          position: fixed; inset: 0;
          background: oklch(11% 0.015 240 / 0.45);
          backdrop-filter: blur(2px);
          z-index: 2147483640;
          animation: cb-fade .25s ease;
        }
        .cb {
          position: fixed; left: 50%; bottom: 24px;
          transform: translateX(-50%);
          width: min(720px, calc(100vw - 32px));
          max-height: calc(100vh - 48px);
          overflow-y: auto;
          background: var(--paper);
          border: 1px solid var(--edge);
          border-radius: var(--r-xl);
          box-shadow: 0 24px 64px -20px rgba(15,20,30,.35), 0 8px 24px -8px rgba(15,20,30,.18);
          z-index: 2147483641;
          padding: 28px;
          animation: cb-rise .35s cubic-bezier(.2,.7,.3,1);
        }
        @keyframes cb-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes cb-rise { from { opacity: 0; transform: translate(-50%, 16px); } to { opacity: 1; transform: translate(-50%, 0); } }

        .cb-head { display: flex; gap: 16px; align-items: flex-start; }
        .cb-mark {
          width: 40px; height: 40px;
          display: inline-flex; align-items: center; justify-content: center;
          background: var(--brand-soft); border-radius: 10px;
          flex-shrink: 0;
        }
        .cb-title-block { flex-grow: 1; }
        .cb h3 { font-size: 18px; margin-bottom: 6px; }
        .cb .muted { font-size: 14px; line-height: 1.5; max-width: 60ch; }

        .cb-cats {
          margin-top: 22px;
          display: flex; flex-direction: column; gap: 8px;
          padding-top: 22px;
          border-top: 1px dashed var(--edge);
        }

        .cb-meta {
          display: flex; gap: 18px; align-items: center; flex-wrap: wrap;
          margin-top: 22px; padding-top: 18px;
          border-top: 1px solid var(--edge);
          font-size: 11px; color: var(--mute); letter-spacing: 0.03em;
        }
        .cb-meta a { color: var(--brand-deep); text-decoration: underline; text-underline-offset: 3px; }
        .cb-meta a:hover { color: var(--brand); }
        .cb-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--brand); margin-right: 6px; vertical-align: middle; }

        .cb-actions {
          display: flex; gap: 10px; justify-content: flex-end;
          margin-top: 18px; flex-wrap: wrap;
        }
        @media (max-width: 540px) {
          .cb-actions { flex-direction: column-reverse; }
          .cb-actions .btn { width: 100%; }
        }
      `}</style>
    </>
  );
}

function CookieCategory({ title, tag, tagTone, body, detail, checked, disabled, onChange }) {
  const [show, setShow] = useStateC(false);
  return (
    <div className={`cb-cat ${checked ? 'is-on' : ''} ${disabled ? 'is-disabled' : ''}`}>
      <div className="cb-cat-row">
        <div className="cb-cat-info">
          <button className="cb-cat-toggle-text" onClick={() => setShow(!show)} aria-expanded={show}>
            <span className="cb-cat-arrow">{show ? '▾' : '▸'}</span>
            <span className="cb-cat-title">{title}</span>
            {tag && <span className={`cb-cat-tag cb-cat-tag-${tagTone}`}>{tag}</span>}
          </button>
        </div>
        <button
          type="button"
          role="switch"
          aria-checked={checked}
          disabled={disabled}
          className={`cb-switch ${checked ? 'on' : ''}`}
          onClick={() => !disabled && onChange(!checked)}
        >
          <span className="cb-switch-knob" />
        </button>
      </div>
      {show && (
        <div className="cb-cat-detail">
          <p>{body}</p>
          <div className="mono">{detail}</div>
        </div>
      )}
      <style>{`
        .cb-cat { padding: 14px 16px; border: 1px solid var(--edge); border-radius: 10px; background: var(--paper); transition: border-color .2s; }
        .cb-cat.is-on { border-color: var(--brand-line); background: var(--brand-soft); }
        .cb-cat.is-disabled { background: var(--paper-2); }
        .cb-cat-row { display: flex; justify-content: space-between; align-items: center; gap: 16px; }
        .cb-cat-toggle-text { background: transparent; border: 0; cursor: pointer; padding: 0; display: inline-flex; align-items: center; gap: 8px; font-family: inherit; color: var(--ink-deep); }
        .cb-cat-arrow { font-family: var(--f-mono); color: var(--mute); font-size: 12px; }
        .cb-cat-title { font-weight: 600; font-size: 14px; }
        .cb-cat-tag {
          font-family: var(--f-mono); font-size: 10px;
          padding: 2px 8px; border-radius: 999px;
          letter-spacing: 0.05em; text-transform: uppercase;
        }
        .cb-cat-tag-ok { background: var(--brand); color: white; }
        .cb-cat-detail { margin-top: 12px; padding-top: 12px; border-top: 1px dashed var(--edge); }
        .cb-cat-detail p { font-size: 13px; color: var(--ink-soft); line-height: 1.5; }
        .cb-cat-detail .mono { font-size: 11px; color: var(--mute); margin-top: 8px; letter-spacing: 0.02em; }

        .cb-switch {
          position: relative;
          width: 40px; height: 22px;
          border-radius: 999px;
          background: var(--edge-strong);
          border: 0; padding: 0;
          cursor: pointer;
          transition: background .2s;
          flex-shrink: 0;
        }
        .cb-switch.on { background: var(--brand); }
        .cb-switch[disabled] { background: var(--brand); opacity: 0.7; cursor: not-allowed; }
        .cb-switch-knob {
          position: absolute;
          left: 2px; top: 2px;
          width: 18px; height: 18px;
          background: white;
          border-radius: 50%;
          box-shadow: 0 1px 3px rgba(0,0,0,.2);
          transition: transform .2s cubic-bezier(.2,.7,.3,1);
        }
        .cb-switch.on .cb-switch-knob { transform: translateX(18px); }
      `}</style>
    </div>
  );
}

window.CookieBanner = CookieBanner;
window.loadConsent = loadConsent;
