// LUXOMES — Cookie Consent + Analytics loader
//
// One file owns everything cookie/analytics-related so we can swap
// providers or amend the categories without touching the rest of the
// app. Strategy:
//
//   1. On first visit, show a banner asking for consent. Until the
//      user makes a choice, NO non-essential script loads (GDPR + TTDSG).
//   2. The user can accept all, reject all, or pick categories.
//   3. Choices are persisted to localStorage. The footer link "Cookies"
//      reopens the dialog any time.
//   4. Granted categories trigger the relevant script loader
//      (gtag for GA4, clarity.ms for Microsoft Clarity).
//
// To activate analytics: drop your IDs into the CONFIG object below.
// As long as both are empty strings, the cookie banner still works but
// nothing is loaded — useful for staging.

const CONFIG = {
  // Google Analytics 4 — Measurement-ID, format: G-XXXXXXXXXX
  // Property: luxomes.com (account: azamat.manghal@luxomes.com)
  GA4_ID: "G-2PJYWXNCNC",
  // Microsoft Clarity — Project-ID, format: 10-char alphanumeric
  // Project: LUXOMES (account: info@luxomes.com)
  CLARITY_ID: "wviwckffay",
};

const STORAGE_KEY = "luxomes-consent-v1";

// Public read API used by the rest of the app if needed
window.LXConsent = {
  get: () => {
    try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "null"); }
    catch (e) { return null; }
  },
  set: (state) => {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); }
    catch (e) {}
  },
  reset: () => {
    try { localStorage.removeItem(STORAGE_KEY); }
    catch (e) {}
  },
  // Allow the footer link to reopen the banner
  open: () => { window.dispatchEvent(new CustomEvent("lx-consent-open")); },
};

function loadGA4(id) {
  if (!id || window.__lxGA4Loaded) return;
  window.__lxGA4Loaded = true;
  const s = document.createElement("script");
  s.async = true;
  s.src = "https://www.googletagmanager.com/gtag/js?id=" + encodeURIComponent(id);
  document.head.appendChild(s);
  window.dataLayer = window.dataLayer || [];
  function gtag(){ window.dataLayer.push(arguments); }
  window.gtag = gtag;
  gtag("js", new Date());
  // anonymize_ip is recommended for DE; cookie flags tighten storage
  gtag("config", id, {
    anonymize_ip: true,
    cookie_flags: "SameSite=None;Secure",
  });
}

function loadClarity(id) {
  if (!id || window.__lxClarityLoaded) return;
  window.__lxClarityLoaded = 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", id);
}

function applyConsent(state) {
  if (state && state.analytics) {
    loadGA4(CONFIG.GA4_ID);
    loadClarity(CONFIG.CLARITY_ID);
  }
  // (Marketing-Pixel würden hier laden, falls jemals aktiviert.)
}

// ─────────────────────────────────────────────────────────────────────
// React UI for the cookie banner / settings dialog
// ─────────────────────────────────────────────────────────────────────
function CookieBanner({ lang }) {
  const [state, setState] = React.useState(() => window.LXConsent.get());
  const [open, setOpen] = React.useState(() => !window.LXConsent.get());
  const [tab, setTab] = React.useState("intro"); // 'intro' | 'detail'
  const [analytics, setAnalytics] = React.useState(state?.analytics ?? false);
  const [marketing, setMarketing] = React.useState(state?.marketing ?? false);

  React.useEffect(() => {
    const onOpen = () => {
      const s = window.LXConsent.get();
      setAnalytics(s?.analytics ?? false);
      setMarketing(s?.marketing ?? false);
      setTab("detail");
      setOpen(true);
    };
    window.addEventListener("lx-consent-open", onOpen);
    return () => window.removeEventListener("lx-consent-open", onOpen);
  }, []);

  // On first mount: if state already saved, apply scripts immediately
  React.useEffect(() => { if (state) applyConsent(state); }, []);

  const T = lang === "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",
    catNecessary: "Notwendig",
    catNecessaryDesc: "Diese Cookies sind technisch erforderlich (Sitzung, Sicherheit, Cookie-Einstellungen). Immer aktiv.",
    catAnalytics: "Statistik",
    catAnalyticsDesc: "Hilft uns zu verstehen, wie Besucher die Seite nutzen (Google Analytics, Microsoft Clarity). Anonymisierte Daten.",
    catMarketing: "Marketing",
    catMarketingDesc: "Aktuell nicht im Einsatz. Wird für künftige Anzeigen-Kampagnen reserviert.",
    privacyLink: "Datenschutzerklärung",
    legal: 'Du kannst Deine Auswahl jederzeit über den Link „Cookies" im Footer ändern.',
    always: "Immer aktiv",
  } : {
    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",
    catNecessary: "Necessary",
    catNecessaryDesc: "Technically required (session, security, cookie preferences). Always on.",
    catAnalytics: "Analytics",
    catAnalyticsDesc: "Helps us understand how visitors use the site (Google Analytics, Microsoft Clarity). Anonymized data.",
    catMarketing: "Marketing",
    catMarketingDesc: "Currently not used. Reserved for future advertising campaigns.",
    privacyLink: "Privacy policy",
    legal: "You can change your selection any time via the “Cookies” link in the footer.",
    always: "Always active",
  };

  const save = (next) => {
    const persist = {
      necessary: true,
      analytics: !!next.analytics,
      marketing: !!next.marketing,
      ts: new Date().toISOString(),
      v: 1,
    };
    window.LXConsent.set(persist);
    setState(persist);
    applyConsent(persist);
    setOpen(false);
  };

  if (!open) return null;

  return (
    <div className="consent-overlay" role="dialog" aria-modal="true" aria-labelledby="consent-title">
      <div className="consent-card">
        <h3 id="consent-title" className="consent-title">{T.title}</h3>
        <p className="consent-intro">{T.intro}</p>

        {tab === "intro" ? (
          <div className="consent-actions">
            <button className="btn btn-primary" onClick={() => save({ analytics: true, marketing: true })}>
              {T.acceptAll}
            </button>
            <button className="btn btn-ghost" onClick={() => save({ analytics: false, marketing: false })}>
              {T.rejectAll}
            </button>
            <button className="btn-link" onClick={() => setTab("detail")}>{T.customize}</button>
          </div>
        ) : (
          <>
            <div className="consent-categories">
              <label className="consent-row">
                <div className="consent-row-text">
                  <div className="consent-row-title">{T.catNecessary} <span className="consent-pill">{T.always}</span></div>
                  <div className="consent-row-desc">{T.catNecessaryDesc}</div>
                </div>
                <input type="checkbox" checked disabled aria-label={T.catNecessary}/>
              </label>
              <label className="consent-row">
                <div className="consent-row-text">
                  <div className="consent-row-title">{T.catAnalytics}</div>
                  <div className="consent-row-desc">{T.catAnalyticsDesc}</div>
                </div>
                <input type="checkbox" checked={analytics} onChange={(e) => setAnalytics(e.target.checked)} aria-label={T.catAnalytics}/>
              </label>
              <label className="consent-row">
                <div className="consent-row-text">
                  <div className="consent-row-title">{T.catMarketing}</div>
                  <div className="consent-row-desc">{T.catMarketingDesc}</div>
                </div>
                <input type="checkbox" checked={marketing} onChange={(e) => setMarketing(e.target.checked)} aria-label={T.catMarketing}/>
              </label>
            </div>
            <div className="consent-actions">
              <button className="btn btn-primary" onClick={() => save({ analytics, marketing })}>{T.save}</button>
              <button className="btn btn-ghost" onClick={() => save({ analytics: true, marketing: true })}>{T.acceptAll}</button>
              <button className="btn-link" onClick={() => save({ analytics: false, marketing: false })}>{T.rejectAll}</button>
            </div>
          </>
        )}
        <p className="consent-legal">
          {T.legal} · <a href="/datenschutz" onClick={(e) => { e.preventDefault(); setOpen(false); if (window.setPage) window.setPage("legal-privacy"); else window.location.href = "/datenschutz"; }}>{T.privacyLink}</a>
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { CookieBanner });
