/* global React */
/* =============================================================================
   Tecnolife — Cookie consent banner (GDPR / Provv. Garante 10/06/2021)
   -----------------------------------------------------------------------------
   - 3 categorie: necessary (sempre attivo), analytics, marketing.
   - Persistenza: localStorage.tl-cookie-consent  (vedi tipo Consent sotto).
   - TTL configurabile da window.FCE_CONFIG.cookieConsentTtlDays (default 365).
   - Re-prompt automatico quando la versione policy in FCE_CONFIG cambia
     (cookiePolicyVersion) o quando il consenso è scaduto.
   - POST best-effort verso /api/cookies/consent (errore silenzioso, non blocca UX).
   - API esposta:
       window.openCookiePreferences()   → riapre il pannello da link footer / cookie-policy
       window.getCookieConsent()        → ritorna l'oggetto Consent corrente o null
   ============================================================================= */
const { useState: useCkState, useEffect: useCkEffect } = React;

const TL_COOKIE_KEY = "tl-cookie-consent";

function readConsent() {
  try {
    const raw = window.localStorage.getItem(TL_COOKIE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") return null;
    return parsed;
  } catch (e) {
    return null;
  }
}

function writeConsent(consent) {
  try {
    window.localStorage.setItem(TL_COOKIE_KEY, JSON.stringify(consent));
  } catch (e) {
    /* storage non disponibile (private mode/quota) — il banner riapparirà al prossimo load */
  }
}

function isConsentValid(consent, cfg) {
  if (!consent || !consent.timestamp) return false;
  if (cfg && consent.policyVersion !== cfg.cookiePolicyVersion) return false;
  const ttlMs = (cfg && cfg.cookieConsentTtlDays ? cfg.cookieConsentTtlDays : 365) * 24 * 60 * 60 * 1000;
  return Date.now() - consent.timestamp < ttlMs;
}

async function postConsent(consent, cfg) {
  if (!cfg || !cfg.apiBase || !cfg.siteId) return;
  try {
    await fetch(cfg.apiBase + "/api/cookies/consent", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        siteId: cfg.siteId,
        categories: consent.categories,
        policyVersion: consent.policyVersion,
        timestamp: consent.timestamp,
      }),
    });
  } catch (e) {
    /* best-effort: non blocchiamo l'utente se il backend non risponde */
  }
}

window.CookieBanner = function CookieBanner({ lang }) {
  const cfg = (typeof window !== "undefined" && window.FCE_CONFIG) || null;
  const [visible, setVisible] = useCkState(false);
  const [showCustomize, setShowCustomize] = useCkState(false);
  const [analytics, setAnalytics] = useCkState(false);
  const [marketing, setMarketing] = useCkState(false);

  // Carica stato iniziale ed espone le API globali per riapertura.
  useCkEffect(() => {
    const open = (existing) => {
      if (existing && Array.isArray(existing.categories)) {
        setAnalytics(existing.categories.indexOf("analytics") !== -1);
        setMarketing(existing.categories.indexOf("marketing") !== -1);
      }
      setShowCustomize(true);
      setVisible(true);
    };

    if (typeof window !== "undefined") {
      window.openCookiePreferences = function () {
        const existing = readConsent();
        open(existing);
      };
      window.getCookieConsent = function () {
        return readConsent();
      };
    }

    const existing = readConsent();
    if (!isConsentValid(existing, cfg)) {
      setVisible(true);
      setShowCustomize(false);
    }

    return () => {
      if (typeof window !== "undefined") {
        try { delete window.openCookiePreferences; } catch (e) { /* noop */ }
        try { delete window.getCookieConsent; } catch (e) { /* noop */ }
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const t = lang === "en" ? {
    title: "We respect your privacy",
    body: "We use technical cookies (always on) and, with your consent, analytics and marketing cookies to improve the site experience and measure traffic.",
    acceptAll: "Accept all",
    rejectOptional: "Reject optional",
    customize: "Customize",
    save: "Save preferences",
    close: "Close",
    catNecLbl: "Strictly necessary",
    catNecDesc: "Required for the site to function. Cannot be disabled.",
    catAnaLbl: "Analytics",
    catAnaDesc: "Aggregated, anonymous usage statistics to improve content and performance.",
    catMktLbl: "Marketing",
    catMktDesc: "Personalized communications and measurement of advertising campaigns.",
    privacyLink: "Privacy Policy",
    cookieLink: "Cookie Policy",
    ariaTitle: "Cookie consent",
  } : {
    title: "Rispettiamo la tua privacy",
    body: "Usiamo cookie tecnici (sempre attivi) e, previo consenso, cookie di analytics e marketing per migliorare l'esperienza del sito e misurare il traffico.",
    acceptAll: "Accetta tutto",
    rejectOptional: "Rifiuta opzionali",
    customize: "Personalizza",
    save: "Salva preferenze",
    close: "Chiudi",
    catNecLbl: "Strettamente necessari",
    catNecDesc: "Indispensabili per il funzionamento del sito. Non disattivabili.",
    catAnaLbl: "Analytics",
    catAnaDesc: "Statistiche di utilizzo aggregate e anonime per migliorare contenuti e prestazioni.",
    catMktLbl: "Marketing",
    catMktDesc: "Comunicazioni personalizzate e misurazione delle campagne pubblicitarie.",
    privacyLink: "Privacy Policy",
    cookieLink: "Cookie Policy",
    ariaTitle: "Consenso cookie",
  };

  function commit(categories) {
    const consent = {
      categories: categories,
      policyVersion: cfg ? cfg.cookiePolicyVersion : "unknown",
      timestamp: Date.now(),
    };
    writeConsent(consent);
    setVisible(false);
    setShowCustomize(false);
    postConsent(consent, cfg);
  }

  function handleAcceptAll() {
    commit(["necessary", "analytics", "marketing"]);
  }
  function handleRejectOptional() {
    commit(["necessary"]);
  }
  function handleCustomize() {
    setShowCustomize(true);
  }
  function handleSaveCustom() {
    const cats = ["necessary"];
    if (analytics) cats.push("analytics");
    if (marketing) cats.push("marketing");
    commit(cats);
  }

  if (!visible) return null;

  /* ----- Layout: bottom sheet dello stesso linguaggio del sito ----- */
  return (
    <div
      role="dialog"
      aria-modal="false"
      aria-label={t.ariaTitle}
      style={{
        position: "fixed",
        zIndex: 100,
        left: "clamp(12px, 2vw, 24px)",
        right: "clamp(12px, 2vw, 24px)",
        bottom: "clamp(12px, 2vw, 24px)",
        display: "flex",
        justifyContent: "center",
        pointerEvents: "none",
      }}
    >
      <div style={{
        pointerEvents: "auto",
        width: "min(880px, 100%)",
        background: "linear-gradient(135deg, rgba(8,12,26,0.96) 0%, rgba(2,40,163,0.96) 100%)",
        color: "#fff",
        border: "1px solid rgba(126,227,255,0.18)",
        borderRadius: 20,
        boxShadow: "0 32px 80px rgba(2,40,163,.45), 0 8px 24px rgba(2,40,163,.20)",
        padding: showCustomize ? "26px 26px 22px" : "22px 24px",
        backdropFilter: "blur(14px)",
        WebkitBackdropFilter: "blur(14px)",
        overflow: "hidden",
        position: "relative",
      }}>
        <svg style={{ position: "absolute", inset: 0, opacity: 0.07, pointerEvents: "none" }}>
          <defs>
            <pattern id="cookgrid" width="40" height="40" patternUnits="userSpaceOnUse">
              <path d="M40 0H0V40" fill="none" stroke="#7EE3FF" strokeWidth="0.5" />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#cookgrid)" />
        </svg>

        {!showCustomize ? (
          <div className="cb-row" style={{ display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap", position: "relative" }}>
            <div style={{ flex: "1 1 320px", minWidth: 240 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--tl-cyan-soft)", marginBottom: 6 }}>
                {t.ariaTitle}
              </div>
              <div style={{ fontSize: 16, fontWeight: 700, color: "#fff", letterSpacing: "-0.01em", marginBottom: 4 }}>
                {t.title}
              </div>
              <p style={{ fontSize: 13, lineHeight: 1.55, color: "rgba(255,255,255,.78)", margin: 0 }}>
                {t.body}{" "}
                <a href="privacy.html" style={{ color: "#7EE3FF", textDecoration: "underline" }}>{t.privacyLink}</a>
                {" · "}
                <a href="cookie-policy.html" style={{ color: "#7EE3FF", textDecoration: "underline" }}>{t.cookieLink}</a>
              </p>
            </div>
            <div className="cb-actions" style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-end" }}>
              <button onClick={handleCustomize} style={btnGhost}>{t.customize}</button>
              <button onClick={handleRejectOptional} style={btnGlass}>{t.rejectOptional}</button>
              <button onClick={handleAcceptAll} style={btnPrimary}>{t.acceptAll}</button>
            </div>
          </div>
        ) : (
          <div style={{ position: "relative" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12, marginBottom: 14 }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--tl-cyan-soft)", marginBottom: 6 }}>
                  {t.customize}
                </div>
                <div style={{ fontSize: 16, fontWeight: 700, color: "#fff", letterSpacing: "-0.01em" }}>
                  {t.title}
                </div>
              </div>
              <button onClick={() => setShowCustomize(false)} aria-label={t.close} style={btnIconClose}>×</button>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 16 }}>
              <CategoryRow
                label={t.catNecLbl}
                desc={t.catNecDesc}
                checked={true}
                disabled={true}
                onChange={() => {}}
              />
              <CategoryRow
                label={t.catAnaLbl}
                desc={t.catAnaDesc}
                checked={analytics}
                onChange={setAnalytics}
              />
              <CategoryRow
                label={t.catMktLbl}
                desc={t.catMktDesc}
                checked={marketing}
                onChange={setMarketing}
              />
            </div>

            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-end" }}>
              <button onClick={handleRejectOptional} style={btnGlass}>{t.rejectOptional}</button>
              <button onClick={handleAcceptAll} style={btnGlass}>{t.acceptAll}</button>
              <button onClick={handleSaveCustom} style={btnPrimary}>{t.save}</button>
            </div>
          </div>
        )}

        <style>{`
          @media (max-width: 640px) {
            .cb-row { flex-direction: column; align-items: stretch; }
            .cb-actions { justify-content: stretch; }
            .cb-actions button { flex: 1 1 auto; }
          }
        `}</style>
      </div>
    </div>
  );
};

function CategoryRow({ label, desc, checked, onChange, disabled = false }) {
  return (
    <div style={{
      display: "flex", alignItems: "flex-start", gap: 14,
      padding: "12px 14px",
      borderRadius: 12,
      background: "rgba(255,255,255,.04)",
      border: "1px solid rgba(255,255,255,.08)",
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "#fff", marginBottom: 2 }}>{label}</div>
        <div style={{ fontSize: 12, color: "rgba(255,255,255,.65)", lineHeight: 1.45 }}>{desc}</div>
      </div>
      <Toggle checked={checked} disabled={disabled} onChange={onChange} />
    </div>
  );
}

function Toggle({ checked, onChange, disabled }) {
  const w = 38, h = 22, pad = 2;
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      disabled={disabled}
      onClick={() => !disabled && onChange(!checked)}
      style={{
        width: w, height: h, borderRadius: 999, border: 0, padding: 0,
        position: "relative", flexShrink: 0,
        background: checked ? "linear-gradient(135deg,#0B57E0,#28D1FE)" : "rgba(255,255,255,.20)",
        opacity: disabled ? 0.5 : 1,
        cursor: disabled ? "not-allowed" : "pointer",
        transition: "background 220ms cubic-bezier(.22,1,.36,1)",
      }}
    >
      <span style={{
        position: "absolute", top: pad, left: checked ? w - h + pad : pad,
        width: h - pad * 2, height: h - pad * 2,
        borderRadius: "50%",
        background: "#fff",
        boxShadow: "0 2px 6px rgba(0,0,0,.25)",
        transition: "left 220ms cubic-bezier(.22,1,.36,1)",
      }} />
    </button>
  );
}

const btnPrimary = {
  fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600,
  padding: "10px 18px", borderRadius: 10, border: 0, cursor: "pointer",
  background: "linear-gradient(135deg,#0B57E0,#1E8BFF 60%,#28D1FE)",
  color: "#fff",
  boxShadow: "0 4px 14px rgba(11,87,224,.40)",
  transition: "transform 140ms",
};
const btnGlass = {
  fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600,
  padding: "10px 16px", borderRadius: 10,
  border: "1px solid rgba(255,255,255,.22)",
  background: "rgba(255,255,255,.10)",
  color: "#fff", cursor: "pointer",
  backdropFilter: "blur(8px)",
};
const btnGhost = {
  fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 500,
  padding: "10px 12px", borderRadius: 10,
  border: 0, background: "transparent",
  color: "rgba(255,255,255,.78)", cursor: "pointer",
  textDecoration: "underline",
};
const btnIconClose = {
  width: 32, height: 32, borderRadius: 8,
  border: "1px solid rgba(255,255,255,.14)",
  background: "rgba(255,255,255,.06)",
  color: "#fff", fontSize: 18, lineHeight: 1, cursor: "pointer",
};
