"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";

const CONSENT_KEY = "toolaro-consent-v1";

type Consent = {
  necessary: true;
  ads: boolean;
  statistics: boolean;
  externalMedia: false;
  updatedAt: string;
};

export function ConsentBanner() {
  const [visible, setVisible] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [ads, setAds] = useState(false);
  const [statistics, setStatistics] = useState(false);

  useEffect(() => {
    setVisible(!localStorage.getItem(CONSENT_KEY));

    const openSettings = () => {
      const stored = localStorage.getItem(CONSENT_KEY);
      if (stored) {
        try {
          const consent = JSON.parse(stored) as Consent;
          setAds(consent.ads);
          setStatistics(consent.statistics);
        } catch {
          setAds(false);
          setStatistics(false);
        }
      }
      setSettingsOpen(true);
      setVisible(true);
    };

    window.addEventListener("toolaro-open-cookie-settings", openSettings);
    return () => window.removeEventListener("toolaro-open-cookie-settings", openSettings);
  }, []);

  const save = (options: { ads: boolean; statistics: boolean }) => {
    const consent: Consent = {
      necessary: true,
      ads: options.ads,
      statistics: options.statistics,
      externalMedia: false,
      updatedAt: new Date().toISOString(),
    };
    localStorage.setItem(CONSENT_KEY, JSON.stringify(consent));
    window.dispatchEvent(new Event("toolaro-consent-updated"));
    setVisible(false);
    setSettingsOpen(false);
  };

  if (!visible) return null;

  return (
    <div className="fixed inset-x-0 bottom-0 z-[100] border-t-2 border-ink-primary bg-surface-base/95 p-4 shadow-[0_-4px_0_rgb(var(--ink-primary))] backdrop-blur">
      <div className="mx-auto flex max-w-5xl flex-col gap-4 md:flex-row md:items-start md:justify-between">
        <div className="max-w-3xl">
          <h2
            className="mb-1 text-[0.7rem] font-bold uppercase tracking-[0.16em] text-ink-secondary"
            style={{ fontFamily: '"Courier New", monospace' }}
          >
            Cookie- und Datenschutzeinstellungen
          </h2>
          <p className="mt-2 text-sm leading-6 text-ink-secondary">
            Du entscheidest, was aktiv ist. Notwendige Speicherung merkt nur deine Auswahl.
            Werbung und Statistik werden erst nach Zustimmung aktiviert.
          </p>

          {settingsOpen && (
            <div className="mt-4 grid gap-2 text-sm">
              <ConsentRow
                label="Notwendig"
                description="Speichert deine Consent-Auswahl im Browser. Immer erforderlich."
                checked
                disabled
              />
              <ConsentRow
                label="Werbung"
                description="Lädt Google AdSense, damit Toolaro kostenlos finanziert werden kann."
                checked={ads}
                onChange={(e) => setAds(e.target.checked)}
              />
              <ConsentRow
                label="Statistik"
                description="Speichert intern Seitenaufruf, Referrer-Host, Sprache, Zeitzone, Gerätetyp und Viewport. Keine Tool-Eingaben."
                checked={statistics}
                onChange={(e) => setStatistics(e.target.checked)}
              />
              <ConsentRow
                label="Externe Medien"
                description="Keine externen Medien aktiv."
                checked={false}
                disabled
                muted
              />
            </div>
          )}
        </div>

        <div className="flex shrink-0 flex-col gap-2 sm:flex-row md:flex-col">
          <Button onClick={() => save({ ads: true, statistics: true })}>Alle akzeptieren</Button>
          <Button variant="outline" onClick={() => save({ ads: false, statistics: false })}>
            Nur notwendige
          </Button>
          {settingsOpen ? (
            <Button variant="outline" onClick={() => save({ ads, statistics })}>
              Auswahl speichern
            </Button>
          ) : (
            <Button variant="outline" onClick={() => setSettingsOpen(true)}>
              Einstellungen
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

function ConsentRow({
  label,
  description,
  checked,
  disabled,
  muted,
  onChange,
}: {
  label: string;
  description: string;
  checked: boolean;
  disabled?: boolean;
  muted?: boolean;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}) {
  return (
    <label
      className={`flex items-start gap-3 border-2 border-ink-primary/30 bg-surface-sunken p-3 ${muted ? "opacity-50" : ""}`}
    >
      <input
        type="checkbox"
        checked={checked}
        disabled={disabled}
        onChange={onChange}
        className="mt-1 border-ink-primary"
      />
      <span>
        <span className="block font-bold text-ink-primary">{label}</span>
        <span className="text-ink-secondary">{description}</span>
      </span>
    </label>
  );
}
