// ============================================================
// Monarch — Bannière de consentement cookies (RGPD / CNIL)
// Autonome : se monte tout seul. Stocke le choix dans localStorage.
//   window.monarchCookiesOpen()  -> rouvre le panneau de réglages
// ============================================================
(function () {
  const { useState, useEffect } = React;

  const C = {
    blanc: "#FFFFFF", albatre: "#FAF9F6", encre: "#1B1D1C",
    ardoise: "#5B7C99", ardoiseF: "#3D5468", sauge: "#5C6F5C", saugeF: "#48584A",
    gris: "#737373", grisC: "#9A9A95", trait: "#E4E1DA"
  };
  const SERIF = "'Fraunces', Georgia, serif";
  const BODY = "'Archivo', system-ui, sans-serif";
  const KEY = "monarch.cookies.v1";

  function readChoice() { try { return JSON.parse(localStorage.getItem(KEY) || "null"); } catch (e) { return null; } }
  function writeChoice(obj) {
    const data = Object.assign({ date: new Date().toISOString() }, obj);
    try { localStorage.setItem(KEY, JSON.stringify(data)); } catch (e) {}
    applyConsent(data);
    window.dispatchEvent(new CustomEvent("monarch-consent", { detail: data }));
  }
  // Point d'ancrage pour activer/désactiver des scripts tiers (analytics…) selon le choix.
  function applyConsent(data) {
    window.MONARCH_CONSENT = data;
    // Exemple : if (data.analytics) { /* charger la mesure d'audience */ }
  }

  function CookieBanner() {
    const [choice, setChoice] = useState(() => readChoice());
    const [settings, setSettings] = useState(false);
    const [analytics, setAnalytics] = useState(true);

    useEffect(() => {
      const c = readChoice();
      if (c) applyConsent(c);
      window.monarchCookiesOpen = () => { const cur = readChoice(); setAnalytics(cur ? !!cur.analytics : true); setSettings(true); setChoice(null); };
    }, []);

    if (choice && !settings) return null;

    const acceptAll = () => { setChoice({ essential: true, analytics: true }); writeChoice({ essential: true, analytics: true }); setSettings(false); };
    const refuseAll = () => { setChoice({ essential: true, analytics: false }); writeChoice({ essential: true, analytics: false }); setSettings(false); };
    const saveCustom = () => { const v = { essential: true, analytics }; setChoice(v); writeChoice(v); setSettings(false); };

    const btnPrimary = { fontFamily: BODY, fontSize: 14, fontWeight: 600, color: "#fff", background: C.sauge, border: "none", borderRadius: 2, padding: "12px 22px", cursor: "pointer" };
    const btnGhost = { fontFamily: BODY, fontSize: 14, fontWeight: 600, color: C.encre, background: "transparent", border: `1px solid ${C.trait}`, borderRadius: 2, padding: "12px 22px", cursor: "pointer" };

    return (
      <div style={{ position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 400, display: "flex", justifyContent: "center", padding: "0 16px 16px" }}>
        <div style={{ background: C.blanc, border: `1px solid ${C.trait}`, borderTop: `3px solid ${C.sauge}`, boxShadow: "0 20px 60px -24px rgba(0,0,0,.35)", maxWidth: 880, width: "100%", padding: "clamp(20px,3vw,28px)" }}>
          <div style={{ display: "flex", gap: 24, alignItems: "flex-start", flexWrap: "wrap", justifyContent: "space-between" }}>
            <div style={{ flex: "1 1 380px", minWidth: 0 }}>
              <div style={{ fontFamily: BODY, fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: C.ardoise, fontWeight: 600 }}>Cookies &amp; confidentialité</div>
              <h3 style={{ fontFamily: SERIF, fontSize: "clamp(18px,2.2vw,22px)", fontWeight: 500, margin: "8px 0 8px", letterSpacing: "-0.01em" }}>Votre vie privée, notre priorité</h3>
              <p style={{ fontFamily: BODY, fontSize: 13.5, color: C.gris, lineHeight: 1.6, margin: 0, maxWidth: "46em" }}>
                Ce site utilise des cookies strictement nécessaires à son fonctionnement, et — avec votre accord — une mesure d'audience anonyme pour améliorer nos contenus. Aucune donnée n'est cédée à des tiers.
              </p>

              {settings &&
                <div style={{ marginTop: 18, borderTop: `1px solid ${C.trait}`, paddingTop: 16, display: "flex", flexDirection: "column", gap: 12 }}>
                  <Row title="Strictement nécessaires" desc="Indispensables au fonctionnement du site (navigation, accès réservé). Toujours actifs." locked checked={true} />
                  <Row title="Mesure d'audience" desc="Statistiques de visite anonymisées pour améliorer le site." checked={analytics} onToggle={() => setAnalytics((a) => !a)} />
                </div>}
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 10, flex: "0 0 auto", minWidth: 200 }}>
              {!settings &&
                <React.Fragment>
                  <button onClick={acceptAll} style={btnPrimary}>Tout accepter</button>
                  <button onClick={refuseAll} style={btnGhost}>Tout refuser</button>
                  <button onClick={() => setSettings(true)} style={{ ...btnGhost, border: "none", padding: "8px", textDecoration: "underline", textUnderlineOffset: 3 }}>Personnaliser</button>
                </React.Fragment>}
              {settings &&
                <React.Fragment>
                  <button onClick={saveCustom} style={btnPrimary}>Enregistrer mes choix</button>
                  <button onClick={acceptAll} style={btnGhost}>Tout accepter</button>
                  <button onClick={refuseAll} style={{ ...btnGhost, border: "none", padding: "8px", textDecoration: "underline", textUnderlineOffset: 3 }}>Tout refuser</button>
                </React.Fragment>}
            </div>
          </div>
        </div>
      </div>);
  }

  function Row({ title, desc, checked, onToggle, locked }) {
    return (
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 18 }}>
        <div>
          <div style={{ fontFamily: BODY, fontSize: 14, fontWeight: 600, color: C.encre }}>{title}</div>
          <div style={{ fontFamily: BODY, fontSize: 12.5, color: C.gris, lineHeight: 1.5, marginTop: 2 }}>{desc}</div>
        </div>
        <button onClick={locked ? undefined : onToggle} disabled={locked} aria-pressed={checked}
          style={{ flex: "0 0 auto", width: 46, height: 26, borderRadius: 999, border: "none", cursor: locked ? "default" : "pointer", position: "relative", background: checked ? C.sauge : C.trait, opacity: locked ? 0.6 : 1, transition: "background .25s" }}>
          <span style={{ position: "absolute", top: 3, left: checked ? 23 : 3, width: 20, height: 20, borderRadius: "50%", background: "#fff", transition: "left .25s" }} />
        </button>
      </div>);
  }

  // montage autonome
  function mount() {
    let host = document.getElementById("monarch-cookie-root");
    if (!host) { host = document.createElement("div"); host.id = "monarch-cookie-root"; document.body.appendChild(host); }
    ReactDOM.createRoot(host).render(<CookieBanner />);
  }
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", mount);
  else mount();

  window.MonarchCookieBanner = CookieBanner;
})();
