// ATOM Center — Cookie / RGPD consent banner
const COOKIE_KEY = "atom-cookie-consent-v1";

const readConsent = () => {
  try {
    const v = localStorage.getItem(COOKIE_KEY);
    return v ? JSON.parse(v) : null;
  } catch { return null; }
};

const writeConsent = (obj) => {
  try {
    localStorage.setItem(COOKIE_KEY, JSON.stringify({
      ...obj,
      _ts: new Date().toISOString(),
      _v: 1,
    }));
  } catch {}
};

const STR = {
  fr: {
    title: "Cookies & confidentialité",
    body: "ATOM Center utilise des cookies pour assurer le bon fonctionnement du site, mesurer son audience et personnaliser votre expérience. Vous pouvez accepter, refuser ou paramétrer vos préférences à tout moment, conformément au RGPD.",
    seeMore: "En savoir plus",
    accept: "Tout accepter",
    refuse: "Tout refuser",
    customize: "Paramétrer",
    modalTitle: "Préférences de cookies",
    modalBody: "Choisissez les catégories que vous souhaitez activer. Les cookies essentiels sont nécessaires au fonctionnement du site et ne peuvent être désactivés.",
    catEss: "Cookies essentiels",
    catEssDesc: "Nécessaires au fonctionnement du site (préférences de langue, sécurité, accessibilité).",
    catEssReq: "Toujours actifs",
    catAna: "Mesure d'audience",
    catAnaDesc: "Nous aident à comprendre comment le site est utilisé pour l'améliorer (analytics anonymisés).",
    catMkt: "Marketing & contenus",
    catMktDesc: "Permettent de personnaliser les contenus que nous vous proposons et de mesurer nos campagnes.",
    save: "Enregistrer mes choix",
    acceptAll: "Tout accepter",
    refuseAll: "Tout refuser",
    cancel: "Fermer",
  },
  en: {
    title: "Cookies & privacy",
    body: "ATOM Center uses cookies to ensure the site works properly, measure audience and personalize your experience. You can accept, refuse or customize your preferences at any time, in line with GDPR.",
    seeMore: "Learn more",
    accept: "Accept all",
    refuse: "Refuse all",
    customize: "Customize",
    modalTitle: "Cookie preferences",
    modalBody: "Pick the categories you want to enable. Essential cookies are required and cannot be disabled.",
    catEss: "Essential cookies",
    catEssDesc: "Required for the site to work (language preference, security, accessibility).",
    catEssReq: "Always active",
    catAna: "Analytics",
    catAnaDesc: "Help us understand how the site is used so we can improve it (anonymized analytics).",
    catMkt: "Marketing & content",
    catMktDesc: "Personalize content and measure our campaigns.",
    save: "Save my choices",
    acceptAll: "Accept all",
    refuseAll: "Refuse all",
    cancel: "Close",
  },
};

const CookieBanner = ({ lang }) => {
  const [consent, setConsent] = useState(() => readConsent());
  const [modalOpen, setModalOpen] = useState(false);
  const [draft, setDraft] = useState({ analytics: true, marketing: false });
  const s = STR[lang] || STR.fr;

  // Re-emit decision so the rest of the app can react if needed
  useEffect(() => {
    if (consent) {
      window.dispatchEvent(new CustomEvent("atom:consent-changed", { detail: consent }));
    }
  }, [consent]);

  // Allow re-opening the panel from a footer link via custom event
  useEffect(() => {
    const onOpen = () => {
      const cur = readConsent();
      setDraft({
        analytics: cur?.analytics ?? true,
        marketing: cur?.marketing ?? false,
      });
      setModalOpen(true);
    };
    window.addEventListener("atom:open-cookie-prefs", onOpen);
    return () => window.removeEventListener("atom:open-cookie-prefs", onOpen);
  }, []);

  const acceptAll = () => {
    const next = { essential: true, analytics: true, marketing: true };
    writeConsent(next);
    setConsent(next);
    setModalOpen(false);
  };

  const refuseAll = () => {
    const next = { essential: true, analytics: false, marketing: false };
    writeConsent(next);
    setConsent(next);
    setModalOpen(false);
  };

  const saveCustom = () => {
    const next = { essential: true, analytics: !!draft.analytics, marketing: !!draft.marketing };
    writeConsent(next);
    setConsent(next);
    setModalOpen(false);
  };

  // Don't show banner once user has chosen, but still allow modal re-open
  const showBanner = !consent;

  return (
    <>
      {showBanner && (
        <div className="cookie-banner" role="dialog" aria-live="polite" aria-label={s.title}>
          <div>
            <h4>{s.title}</h4>
            <p>
              {s.body}{" "}
              <a href="#" onClick={(e) => { e.preventDefault(); setModalOpen(true); }}>
                {s.seeMore}
              </a>
            </p>
          </div>
          <div className="cookie-actions">
            <button className="btn btn-ghost btn-sm" onClick={refuseAll}>{s.refuse}</button>
            <button className="btn btn-ghost btn-sm" onClick={() => {
              const cur = readConsent();
              setDraft({
                analytics: cur?.analytics ?? true,
                marketing: cur?.marketing ?? false,
              });
              setModalOpen(true);
            }}>{s.customize}</button>
            <button className="btn btn-primary btn-sm" onClick={acceptAll}>{s.accept}</button>
          </div>
        </div>
      )}

      {modalOpen && (
        <div className="cookie-modal-backdrop" onClick={() => setModalOpen(false)}>
          <div className="cookie-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
            <h3>{s.modalTitle}</h3>
            <p>{s.modalBody}</p>

            <div className="cookie-cat">
              <div className="cookie-cat-text">
                <h5>{s.catEss}</h5>
                <p>{s.catEssDesc}</p>
              </div>
              <span className="cookie-required">{s.catEssReq}</span>
              <div className="cookie-switch on locked" aria-disabled="true"></div>
            </div>

            <div className="cookie-cat">
              <div className="cookie-cat-text">
                <h5>{s.catAna}</h5>
                <p>{s.catAnaDesc}</p>
              </div>
              <div
                className={"cookie-switch " + (draft.analytics ? "on" : "")}
                role="switch"
                aria-checked={draft.analytics}
                tabIndex={0}
                onClick={() => setDraft(d => ({ ...d, analytics: !d.analytics }))}
                onKeyDown={(e) => { if (e.key === " " || e.key === "Enter") { e.preventDefault(); setDraft(d => ({ ...d, analytics: !d.analytics })); } }}
              ></div>
            </div>

            <div className="cookie-cat">
              <div className="cookie-cat-text">
                <h5>{s.catMkt}</h5>
                <p>{s.catMktDesc}</p>
              </div>
              <div
                className={"cookie-switch " + (draft.marketing ? "on" : "")}
                role="switch"
                aria-checked={draft.marketing}
                tabIndex={0}
                onClick={() => setDraft(d => ({ ...d, marketing: !d.marketing }))}
                onKeyDown={(e) => { if (e.key === " " || e.key === "Enter") { e.preventDefault(); setDraft(d => ({ ...d, marketing: !d.marketing })); } }}
              ></div>
            </div>

            <div className="cookie-modal-actions">
              <button className="btn btn-ghost btn-sm" onClick={refuseAll}>{s.refuseAll}</button>
              <button className="btn btn-ghost btn-sm" onClick={acceptAll}>{s.acceptAll}</button>
              <button className="btn btn-primary btn-sm" onClick={saveCustom}>{s.save}</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

window.CookieBanner = CookieBanner;
