// LUXOMES — Cookie consent (GA4 + Clarity) and floating contact button.
// Storage key and loader logic unchanged from the previous site, so existing
// visitor choices stay valid. UI follows the 2026 redesign reference.

const CONSENT_KEY = "luxomes-consent-v1";
const LX_GA4_ID = "G-2PJYWXNCNC";
const LX_CLARITY_ID = "wviwckffay";
const LX_HOTLINE = "+4989693378930";

const CONSENT_TX = {
  de: { title: "Cookies & Tracking", intro: "Wir verwenden Cookies und ähnliche Technologien. Notwendige Cookies sind für die Funktion der Website nötig. Andere helfen uns, die Seite zu verbessern. Du entscheidest, was Du erlaubst.", acceptAll: "Alle akzeptieren", rejectAll: "Nur notwendige", customize: "Anpassen", save: "Auswahl speichern", nec: "Notwendig", necD: "Technisch erforderlich (Sitzung, Sicherheit, Cookie-Einstellungen). Immer aktiv.", ana: "Statistik", anaD: "Hilft uns zu verstehen, wie Besucher die Seite nutzen (Google Analytics, Microsoft Clarity). Anonymisierte Daten.", mkt: "Marketing", mktD: "Aktuell nicht im Einsatz. Reserviert für künftige Anzeigen-Kampagnen.", always: "Immer aktiv", privacy: "Datenschutz", call: "Anrufen", wa: "WhatsApp" },
  en: { title: "Cookies & Tracking", intro: "We use cookies and similar technologies. Necessary cookies enable core site functionality. Others help us improve. You decide what to allow.", acceptAll: "Accept all", rejectAll: "Necessary only", customize: "Customize", save: "Save selection", nec: "Necessary", necD: "Technically required (session, security, cookie preferences). Always on.", ana: "Analytics", anaD: "Helps us understand how visitors use the site (Google Analytics, Microsoft Clarity). Anonymized data.", mkt: "Marketing", mktD: "Currently not used. Reserved for future advertising campaigns.", always: "Always on", privacy: "Privacy", call: "Call", wa: "WhatsApp" },
};

function lxLoadGA4() {
  if (window.__lxGA) return; window.__lxGA = true;
  const s = document.createElement("script"); s.async = true;
  s.src = "https://www.googletagmanager.com/gtag/js?id=" + LX_GA4_ID;
  document.head.appendChild(s);
  window.dataLayer = window.dataLayer || [];
  window.gtag = function () { window.dataLayer.push(arguments); };
  gtag("js", new Date());
  gtag("config", LX_GA4_ID, { anonymize_ip: true });
}
function lxLoadClarity() {
  if (window.__lxClarity) return; window.__lxClarity = true;
  (function (c, l, a, r, i, t, y) {
    c[a] = c[a] || function () { (c[a].q = c[a].q || []).push(arguments); };
    t = l.createElement(r); t.async = 1; t.src = "https://www.clarity.ms/tag/" + i;
    y = l.getElementsByTagName(r)[0]; y.parentNode.insertBefore(t, y);
  })(window, document, "clarity", "script", LX_CLARITY_ID);
}
function lxGetConsent() {
  try { return JSON.parse(localStorage.getItem(CONSENT_KEY) || "null"); } catch { return null; }
}
function lxApplyConsent(s) {
  if (s && s.analytics) { lxLoadGA4(); lxLoadClarity(); }
}

function CookieBanner({ lang, setPage }) {
  const t = CONSENT_TX[lang] || CONSENT_TX.de;
  const saved = lxGetConsent();
  const [open, setOpen] = useState(!saved);
  const [detail, setDetail] = useState(false);
  const [ana, setAna] = useState(!!(saved && saved.analytics));
  const [mkt, setMkt] = useState(!!(saved && saved.marketing));

  useEffect(() => { lxApplyConsent(saved); }, []);
  useEffect(() => {
    window.LXConsent = {
      get: lxGetConsent,
      open: () => { setDetail(true); setOpen(true); },
    };
  }, []);

  const save = (a, m) => {
    const s = { necessary: true, analytics: !!a, marketing: !!m, ts: new Date().toISOString() };
    try { localStorage.setItem(CONSENT_KEY, JSON.stringify(s)); } catch (e) {}
    lxApplyConsent(s);
    setAna(!!a); setMkt(!!m); setOpen(false);
  };

  if (!open) return null;
  const row = { display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, padding: "14px 0", borderTop: "1px solid #EEEAE1" };
  const cb = { width: 20, height: 20, accentColor: "#5F7458", flex: "none", marginTop: 2 };
  const btnP = { font: "inherit", cursor: "pointer", border: 0, borderRadius: 999, padding: "12px 18px", fontSize: 13.5, fontWeight: 600, background: "#1E231F", color: "#fff" };
  const btnG = { ...btnP, background: "transparent", color: "#1E231F", border: "1px solid #DDD8CC" };
  const btnL = { ...btnP, background: "transparent", color: "#5F7458", padding: "12px 6px" };

  return (
    <div role="dialog" aria-modal="true" style={{ position: "fixed", inset: 0, zIndex: 900, background: "rgba(30,35,31,.35)", backdropFilter: "blur(6px)", display: "flex", alignItems: "flex-end", justifyContent: "center", padding: 16 }}>
      <div style={{ width: "min(100%,560px)", maxHeight: "calc(100vh - 32px)", overflow: "auto", background: "#fff", borderRadius: 24, padding: 28, boxShadow: "0 40px 90px -30px rgba(30,35,31,.5)", color: "#1E231F" }}>
        <h3 className="serif" style={{ fontSize: 24, margin: "0 0 10px" }}>{t.title}</h3>
        <p style={{ fontSize: 14, lineHeight: 1.6, color: "#4A514B", margin: "0 0 18px" }}>
          {t.intro}{" "}
          <a href="/datenschutz" onClick={e => { e.preventDefault(); setOpen(false); setPage && setPage("legal-privacy"); }}>{t.privacy}</a>
        </p>
        {!detail ? (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <button style={btnP} onClick={() => save(true, true)}>{t.acceptAll}</button>
            <button style={btnG} onClick={() => save(false, false)}>{t.rejectAll}</button>
            <button style={btnL} onClick={() => setDetail(true)}>{t.customize}</button>
          </div>
        ) : (
          <>
            <div style={row}>
              <div><b style={{ fontSize: 14, display: "block", marginBottom: 3 }}>{t.nec} <span style={{ display: "inline-block", fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", background: "#E3E8DC", color: "#5F7458", borderRadius: 999, padding: "3px 8px", marginLeft: 6, fontWeight: 600 }}>{t.always}</span></b><span style={{ fontSize: 12.5, color: "#7A817A", lineHeight: 1.5 }}>{t.necD}</span></div>
              <input type="checkbox" checked disabled style={cb} />
            </div>
            <div style={row}>
              <div><b style={{ fontSize: 14, display: "block", marginBottom: 3 }}>{t.ana}</b><span style={{ fontSize: 12.5, color: "#7A817A", lineHeight: 1.5 }}>{t.anaD}</span></div>
              <input type="checkbox" checked={ana} onChange={e => setAna(e.target.checked)} style={cb} />
            </div>
            <div style={row}>
              <div><b style={{ fontSize: 14, display: "block", marginBottom: 3 }}>{t.mkt}</b><span style={{ fontSize: 12.5, color: "#7A817A", lineHeight: 1.5 }}>{t.mktD}</span></div>
              <input type="checkbox" checked={mkt} onChange={e => setMkt(e.target.checked)} style={cb} />
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
              <button style={btnP} onClick={() => save(ana, mkt)}>{t.save}</button>
              <button style={btnG} onClick={() => save(true, true)}>{t.acceptAll}</button>
              <button style={btnL} onClick={() => save(false, false)}>{t.rejectAll}</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function ContactFab({ lang }) {
  const t = CONSENT_TX[lang] || CONSENT_TX.de;
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const esc = e => { if (e.key === "Escape") setOpen(false); };
    addEventListener("keydown", esc);
    return () => removeEventListener("keydown", esc);
  }, []);
  const opt = { display: "flex", alignItems: "center", gap: 10, background: "#fff", color: "#1E231F", textDecoration: "none", borderRadius: 999, padding: "11px 16px 11px 12px", fontSize: 13.5, fontWeight: 600, boxShadow: "0 16px 40px -12px rgba(30,35,31,.4)", border: "1px solid #E6E1D6", transform: open ? "none" : "translateY(10px)", opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "all .35s cubic-bezier(.2,.7,.2,1)" };
  const ico = { width: 30, height: 30, borderRadius: "50%", background: "#E3E8DC", color: "#5F7458", display: "inline-flex", alignItems: "center", justifyContent: "center", fontStyle: "normal" };
  return (
    <div style={{ position: "fixed", right: 20, bottom: 20, zIndex: 800, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 10 }}>
      <a style={opt} href={"tel:" + LX_HOTLINE}>
        <i style={ico}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.9 2z"/></svg></i>
        {t.call}
      </a>
      <a style={opt} href={"https://wa.me/" + LX_HOTLINE.replace(/\D/g, "")} target="_blank" rel="noopener noreferrer">
        <i style={ico}><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 0 0-8.6 15.1L2 22l5-1.3A10 10 0 1 0 12 2zm0 18.2a8.2 8.2 0 0 1-4.2-1.2l-.3-.2-3 .8.8-2.9-.2-.3A8.2 8.2 0 1 1 12 20.2zm4.5-6.1c-.2-.1-1.5-.7-1.7-.8s-.4-.1-.6.1-.6.8-.8 1-.3.2-.5.1a6.7 6.7 0 0 1-3.3-2.9c-.3-.4.3-.4.8-1.4.1-.2 0-.3 0-.5l-.8-1.8c-.2-.5-.4-.4-.6-.4h-.5a1 1 0 0 0-.7.3 3 3 0 0 0-.9 2.2 5.2 5.2 0 0 0 1.1 2.7 11.8 11.8 0 0 0 4.5 4c1.7.7 2.3.8 3.1.6a2.7 2.7 0 0 0 1.8-1.2 2.2 2.2 0 0 0 .1-1.2c0-.1-.2-.2-.5-.3z"/></svg></i>
        {t.wa}
      </a>
      <button aria-label="Kontakt" onClick={() => setOpen(!open)} style={{ width: 56, height: 56, borderRadius: "50%", border: 0, cursor: "pointer", background: open ? "#1E231F" : "#5F7458", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 20px 40px -12px rgba(95,116,88,.7)", transition: "transform .4s cubic-bezier(.2,.7,.2,1), background .3s", transform: open ? "rotate(45deg)" : "none", padding: 0 }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
      </button>
    </div>
  );
}
