// Cookie consent banner + small "Cookie-Einstellungen"-Modal.
// Persists in localStorage 'aw.cookieConsent' = { necessary, analytics, ads, savedAt }.

const _cookieKey = 'aw.cookieConsent';

const loadCookieConsent = () => {
  try {
    const v = JSON.parse(localStorage.getItem(_cookieKey) || 'null');
    return v;
  } catch { return null; }
};
const saveCookieConsent = (v) => {
  try {
    localStorage.setItem(_cookieKey, JSON.stringify({ ...v, savedAt: new Date().toISOString() }));
    window.dispatchEvent(new CustomEvent('aw:cookie-changed'));
  } catch {}
};

const CookieBanner = () => {
  const [consent, setConsent] = React.useState(() => loadCookieConsent());
  const [showSettings, setShowSettings] = React.useState(false);
  const [analytics, setAnalytics] = React.useState(true);
  const [ads, setAds] = React.useState(true);

  React.useEffect(() => {
    const h = () => setConsent(loadCookieConsent());
    window.addEventListener('aw:cookie-changed', h);
    return () => window.removeEventListener('aw:cookie-changed', h);
  }, []);

  // Expose a way to re-open settings from elsewhere (e.g. footer link).
  React.useEffect(() => {
    const onOpen = () => setShowSettings(true);
    window.addEventListener('aw:cookie-open-settings', onOpen);
    return () => window.removeEventListener('aw:cookie-open-settings', onOpen);
  }, []);

  if (consent && !showSettings) return null;

  const acceptAll = () => {
    saveCookieConsent({ necessary: true, analytics: true, ads: true });
    setShowSettings(false);
  };
  const rejectAll = () => {
    saveCookieConsent({ necessary: true, analytics: false, ads: false });
    setShowSettings(false);
  };
  const saveCustom = () => {
    saveCookieConsent({ necessary: true, analytics, ads });
    setShowSettings(false);
  };

  // Settings modal (full dialog)
  if (showSettings) {
    return (
      <div className="fixed inset-0 z-[80] flex items-center justify-center p-4">
        <div className="absolute inset-0 bg-ink/50 backdrop-blur-sm" onClick={() => setShowSettings(false)}/>
        <div className="relative w-full max-w-lg bg-paper rounded-3xl ring-2 ring-line shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
          <div className="p-6 bg-cream border-b-2 border-line flex items-start gap-3">
            <span className="inline-flex w-12 h-12 rounded-2xl bg-coral text-white items-center justify-center text-2xl shadow-pop">🍪</span>
            <div className="flex-1">
              <div className="font-display text-2xl font-extrabold leading-tight">Cookie-Einstellungen</div>
              <div className="text-[13px] text-inkSoft mt-1">Wähle, welche Cookies du erlauben möchtest.</div>
            </div>
            <button onClick={() => setShowSettings(false)} className="p-2 rounded-full hover:bg-ink/5 -mt-1 -mr-1"><IconClose/></button>
          </div>
          <div className="p-6 overflow-y-auto scroll-soft grid gap-3">
            <CookieRow title="Notwendige Cookies" sub="Werden für die Grundfunktionen der Seite benötigt (Login, Mappen). Können nicht deaktiviert werden."
              checked={true} disabled/>
            <CookieRow title="Statistik (Analytics)" sub="Helfen uns zu verstehen, welche Bilder beliebt sind. Anonymisiert."
              checked={analytics} onChange={setAnalytics}/>
            <CookieRow title="Werbung (Google AdSense)" sub="Personalisierte Werbung. Ohne dies sehen Sie weiterhin nicht-personalisierte Anzeigen."
              checked={ads} onChange={setAds}/>
            <div className="p-3 rounded-xl bg-sky/30 text-[12px] leading-relaxed mt-2">
              Mehr Informationen findest du in der <button className="font-bold underline">Datenschutzerklärung</button>.
              Du kannst deine Auswahl jederzeit im Footer unter „Cookie-Einstellungen" ändern.
            </div>
          </div>
          <div className="p-5 border-t-2 border-line bg-paper grid sm:grid-cols-3 gap-2">
            <Btn variant="soft" size="md" onClick={rejectAll}>Alle ablehnen</Btn>
            <Btn variant="soft" size="md" onClick={saveCustom}>Auswahl speichern</Btn>
            <Btn size="md" onClick={acceptAll}>Alle akzeptieren</Btn>
          </div>
        </div>
      </div>
    );
  }

  // Banner (bottom of viewport)
  return (
    <div className="fixed bottom-0 left-0 right-0 z-[70] p-4 sm:p-6 pointer-events-none">
      <div className="max-w-5xl mx-auto bg-paper rounded-3xl ring-2 ring-line shadow-2xl p-5 sm:p-6 grid md:grid-cols-[auto,1fr,auto] gap-4 items-center pointer-events-auto panel-slide-up">
        <span className="inline-flex w-14 h-14 rounded-2xl bg-coral text-white items-center justify-center text-3xl shadow-pop shrink-0">🍪</span>
        <div className="min-w-0">
          <div className="font-display text-lg font-extrabold leading-tight">Wir verwenden Cookies</div>
          <p className="text-[13px] text-inkSoft mt-1 leading-relaxed">
            Wir nutzen Cookies für die Funktion der Seite, für Statistiken und für Werbung. Du kannst alles akzeptieren oder einzelne Cookies wählen.
          </p>
        </div>
        <div className="flex flex-wrap gap-2 shrink-0">
          <Btn variant="soft" size="md" onClick={() => setShowSettings(true)}>Einstellungen</Btn>
          <Btn variant="soft" size="md" onClick={rejectAll}>Nur notwendige</Btn>
          <Btn size="md" onClick={acceptAll}>Alle akzeptieren</Btn>
        </div>
      </div>
    </div>
  );
};

const CookieRow = ({ title, sub, checked, onChange, disabled }) => (
  <label className={cls("flex items-center justify-between gap-4 px-4 py-3 rounded-xl ring-1 ring-line bg-cream",
    disabled ? 'opacity-90' : 'cursor-pointer hover:ring-ink/30 transition')}>
    <div className="min-w-0">
      <div className="text-sm font-extrabold leading-tight">{title}</div>
      <div className="text-[12px] text-inkSoft mt-0.5">{sub}</div>
    </div>
    <button type="button" role="switch" aria-checked={!!checked} disabled={disabled}
      onClick={() => !disabled && onChange(!checked)}
      className={cls("relative w-12 h-7 rounded-full transition shrink-0",
        checked ? 'bg-coral' : 'bg-ink/15', disabled && 'cursor-not-allowed')}>
      <span className={cls("absolute top-1 left-1 w-5 h-5 bg-white rounded-full shadow transition",
        checked && 'translate-x-5')}/>
    </button>
  </label>
);

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