/* ============================================================================
 * COOKIE CONSENT BANNER — DSGVO/TDDDG-konform
 * ----------------------------------------------------------------------------
 * 3 Layer:
 *   1. Bottom Bar    — Initial-Anzeige bei erstem Besuch
 *   2. Settings Modal — granulare Kategorie-Toggles + Akkordeon-Details
 *   3. Toast         — Bestätigung nach Speichern (oben, 3s)
 *
 * Persistiert in localStorage als JSON unter `mt_cookie_consent`:
 *   { version: 1, timestamp: 1234567890, categories: { ... } }
 *
 * API:
 *   window.cookieConsent.get('analytics')  →  boolean
 *   window.cookieConsent.openSettings()    →  öffnet Modal
 *   window.cookieConsent.reset()           →  löscht Entscheidung, zeigt Banner erneut
 *   Event "cookie-consent-updated" feuert mit detail = categories
 *
 * Mounted auf <div id="cookie-consent-root"> (wird automatisch erstellt).
 * ========================================================================= */

(function () {
  const { useState, useEffect, useRef } = React;

  const STORAGE_KEY = 'mt_cookie_consent';
  const CONSENT_VERSION = 1;
  const CONSENT_MAX_AGE_DAYS = 365;

  const CATEGORIES = {
    necessary: {
      label: 'Technisch notwendige Cookies',
      always: true,
      description: 'Für den Betrieb der Website unverzichtbar — z. B. Speicherung Ihrer Cookie-Einstellungen, Schutz vor Spam und Missbrauch.',
      legalBasis: '§ 25 Abs. 2 Nr. 2 TDDDG sowie Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse).',
      retention: 'Session bis maximal 12 Monate',
      services: [
        { name: 'Cookie-Consent', purpose: 'Speichert Ihre Cookie-Entscheidung im Browser', duration: '12 Monate' },
        { name: 'Vercel (Hosting)', purpose: 'Bereitstellung der Website, DDoS-Schutz, Server-Logs', duration: 'Bis 14 Tage' },
        { name: 'Anti-Spam (Honeypot + Rate-Limit)', purpose: 'Schutz der Kontaktformulare vor Bot-Spam', duration: 'Bis 1 Stunde' }
      ]
    },
    functional: {
      label: 'Funktionale Cookies',
      description: 'Eingebettete Drittdienste, die zusätzliche Funktionen bieten — etwa die Online-Terminbuchung.',
      legalBasis: 'Art. 6 Abs. 1 lit. a DSGVO i.V.m. § 25 Abs. 1 TDDDG (Einwilligung).',
      retention: 'Variiert je Dienst — siehe Datenschutzerklärung',
      services: [
        { name: 'TidyCal', purpose: 'Online-Terminbuchung (eingebettetes Widget, AppSumo Originals LLC, USA)', duration: 'Buchungsdaten max. 3 Jahre' }
      ]
    },
    analytics: {
      label: 'Analyse-Cookies',
      description: 'Helfen uns zu verstehen, wie die Website genutzt wird, damit wir sie verbessern können. Daten werden anonymisiert oder pseudonymisiert verarbeitet.',
      legalBasis: 'Art. 6 Abs. 1 lit. a DSGVO i.V.m. § 25 Abs. 1 TDDDG (Einwilligung).',
      retention: 'Bis zu 14 Monate',
      services: [
        { name: 'Google Analytics 4', purpose: 'Reichweitenanalyse mit IP-Anonymisierung', duration: '14 Monate', conditional: true }
      ]
    }
  };

  /* ── Persistenz ────────────────────────────────────────────────────── */

  function readConsent() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      if (parsed.version !== CONSENT_VERSION) return null;
      const ageDays = (Date.now() - (parsed.timestamp || 0)) / (1000 * 60 * 60 * 24);
      if (ageDays > CONSENT_MAX_AGE_DAYS) return null;
      return parsed.categories || null;
    } catch (e) { return null; }
  }

  function writeConsent(categories) {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify({
        version: CONSENT_VERSION,
        timestamp: Date.now(),
        categories
      }));
    } catch (e) {}
    window.__cookieConsent = categories;
    window.dispatchEvent(new CustomEvent('cookie-consent-updated', { detail: categories }));
  }

  /* ── Toast ────────────────────────────────────────────────────────── */

  function Toast({ message, onDismiss }) {
    useEffect(() => {
      const t = setTimeout(onDismiss, 3000);
      return () => clearTimeout(t);
    }, [onDismiss]);
    return (
      <div className="cc-toast" role="status">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        <span>{message}</span>
      </div>
    );
  }

  /* ── Toggle-Switch ────────────────────────────────────────────────── */

  function Toggle({ checked, onChange, label, locked }) {
    return (
      <button
        type="button"
        role="switch"
        aria-checked={checked}
        aria-label={label}
        className={`cc-toggle ${checked ? 'cc-toggle-on' : ''} ${locked ? 'cc-toggle-locked' : ''}`}
        onClick={() => !locked && onChange(!checked)}
        disabled={locked}>
        <span className="cc-toggle-knob"/>
      </button>
    );
  }

  /* ── Kategorie-Card im Modal ──────────────────────────────────────── */

  function CategoryRow({ id, cat, value, onChange }) {
    const [open, setOpen] = useState(false);
    return (
      <div className="cc-cat">
        <div className="cc-cat-head">
          <div className="cc-cat-text">
            <h4>{cat.label}</h4>
            <p>{cat.description}</p>
          </div>
          <div className="cc-cat-control">
            {cat.always ? (
              <span className="cc-always">✓ IMMER AKTIV</span>
            ) : (
              <Toggle
                checked={value}
                onChange={(v) => onChange(id, v)}
                label={`${cat.label} aktivieren`}/>
            )}
          </div>
        </div>

        <button
          type="button"
          className={`cc-details-btn ${open ? 'cc-details-open' : ''}`}
          onClick={() => setOpen(!open)}
          aria-expanded={open}>
          {open ? 'Details ausblenden' : 'Details anzeigen'}
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
        </button>

        <div className={`cc-details ${open ? 'cc-details-visible' : ''}`} aria-hidden={!open}>
          <div className="cc-details-inner">
            <dl className="cc-details-meta">
              <dt>Rechtsgrundlage</dt><dd>{cat.legalBasis}</dd>
              <dt>Speicherdauer</dt><dd>{cat.retention}</dd>
            </dl>
            <div className="cc-services">
              <div className="cc-services-label">Eingesetzte Dienste</div>
              <table>
                <thead>
                  <tr><th>Dienst</th><th>Zweck</th><th>Dauer</th></tr>
                </thead>
                <tbody>
                  {cat.services.map((s, i) => (
                    <tr key={i}>
                      <td>{s.name}</td>
                      <td>{s.purpose}</td>
                      <td>{s.duration}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ── Settings-Modal ────────────────────────────────────────────────── */

  function SettingsModal({ initial, onClose, onSave, onAcceptAll, onRejectAll }) {
    const [draft, setDraft] = useState({
      necessary: true,
      functional: initial?.functional || false,
      analytics: initial?.analytics || false
    });
    const setCat = (id, v) => setDraft((d) => ({ ...d, [id]: v }));

    useEffect(() => {
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      document.addEventListener('keydown', onKey);
      document.body.style.overflow = 'hidden';
      return () => {
        document.removeEventListener('keydown', onKey);
        document.body.style.overflow = '';
      };
    }, [onClose]);

    return (
      <div className="cc-overlay" onClick={onClose} role="dialog" aria-modal="true" aria-labelledby="cc-modal-title">
        <div className="cc-modal" onClick={(e) => e.stopPropagation()}>
          <header className="cc-modal-head">
            <h2 id="cc-modal-title">Cookie-Einstellungen</h2>
            <button type="button" className="cc-modal-close" onClick={onClose} aria-label="Schließen">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
            </button>
          </header>

          <div className="cc-modal-body">
            <p className="cc-intro">
              Wir verwenden Cookies und vergleichbare Technologien, um Ihnen unsere Website bestmöglich anzubieten.
              Sie können auswählen, welche Kategorien Sie zulassen möchten. Detaillierte Informationen finden Sie in
              unserer <a href="datenschutz.html" target="_blank" rel="noopener">Datenschutzerklärung</a>.
            </p>

            {Object.entries(CATEGORIES).map(([id, cat]) => (
              <CategoryRow
                key={id}
                id={id}
                cat={cat}
                value={draft[id]}
                onChange={setCat}/>
            ))}
          </div>

          <footer className="cc-modal-foot">
            <button type="button" className="cc-btn cc-btn-neutral" onClick={onRejectAll}>Alle ablehnen</button>
            <button type="button" className="cc-btn cc-btn-neutral" onClick={() => onSave(draft)}>Auswahl speichern</button>
            <button type="button" className="cc-btn cc-btn-neutral" onClick={onAcceptAll}>Alle akzeptieren</button>
          </footer>
        </div>
      </div>
    );
  }

  /* ── Banner (Bottom Bar) ──────────────────────────────────────────── */

  function Banner({ onAcceptAll, onRejectAll, onOpenSettings }) {
    return (
      <div className="cc-bar" role="region" aria-label="Cookie-Hinweis">
        <div className="cc-bar-content">
          <div className="cc-bar-text">
            <h3>🍪 Ihre Privatsphäre ist uns wichtig</h3>
            <p>
              Wir nutzen Cookies und vergleichbare Technologien, um die Website zu betreiben, Inhalte zu personalisieren und
              die Nutzung zu analysieren. Sie können selbst entscheiden, welche Kategorien Sie zulassen.{' '}
              <button type="button" className="cc-bar-link" onClick={onOpenSettings}>Mehr erfahren</button>
            </p>
          </div>
          <div className="cc-bar-actions">
            <button type="button" className="cc-btn cc-btn-ghost cc-btn-sm" onClick={onOpenSettings}>Einstellungen</button>
            <button type="button" className="cc-btn cc-btn-secondary cc-btn-sm" onClick={onRejectAll}>Nur notwendige</button>
            <button type="button" className="cc-btn cc-btn-primary cc-btn-sm" onClick={onAcceptAll}>Alle akzeptieren</button>
          </div>
        </div>
      </div>
    );
  }

  /* ── Root-Component ────────────────────────────────────────────────── */

  function CookieConsent() {
    const initialConsent = readConsent();
    const [consent, setConsent] = useState(initialConsent);
    const [showBar, setShowBar] = useState(!initialConsent);
    const [showSettings, setShowSettings] = useState(false);
    const [showToast, setShowToast] = useState(false);

    useEffect(() => {
      // API publishen
      window.__cookieConsent = consent;
      window.cookieConsent = {
        get: (key) => key === 'necessary' ? true : !!(consent && consent[key]),
        all: () => ({ ...(consent || {}), necessary: true }),
        openSettings: () => setShowSettings(true),
        reset: () => {
          try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}
          setConsent(null);
          setShowBar(true);
        }
      };
    }, [consent]);

    const persist = (next) => {
      writeConsent(next);
      setConsent(next);
      setShowSettings(false);
      setShowBar(false);
      setShowToast(true);
    };

    const acceptAll = () => persist({ necessary: true, functional: true, analytics: true });
    const rejectAll = () => persist({ necessary: true, functional: false, analytics: false });
    const saveCustom = (draft) => persist({ necessary: true, ...draft });

    return (
      <>
        {showBar && !showSettings && (
          <Banner
            onAcceptAll={acceptAll}
            onRejectAll={rejectAll}
            onOpenSettings={() => setShowSettings(true)}/>
        )}
        {showSettings && (
          <SettingsModal
            initial={consent}
            onClose={() => setShowSettings(false)}
            onSave={saveCustom}
            onAcceptAll={acceptAll}
            onRejectAll={rejectAll}/>
        )}
        {showToast && (
          <Toast
            message="Ihre Cookie-Einstellungen wurden gespeichert."
            onDismiss={() => setShowToast(false)}/>
        )}
      </>
    );
  }

  /* ── Mount in eigenen Root, damit es auf JEDER Seite funktioniert ──── */
  function mount() {
    let host = document.getElementById('cookie-consent-root');
    if (!host) {
      host = document.createElement('div');
      host.id = 'cookie-consent-root';
      document.body.appendChild(host);
    }
    ReactDOM.createRoot(host).render(<CookieConsent/>);
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mount);
  } else {
    mount();
  }
})();
