/* ============================================================
   COOKIES BANNER — RGPD (UE) + LGPD (Brésil)
   Affiche une bannière discrète en bas de l'écran tant que
   l'utilisateur n'a pas fait de choix. Persiste dans
   localStorage sous la clé "omega.cookies".
   ============================================================ */

const COOKIE_KEY = "omega.cookies.v1";

function readCookieChoice() {
  try {
    const raw = localStorage.getItem(COOKIE_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch (_) {
    return null;
  }
}

function writeCookieChoice(choice) {
  try {
    localStorage.setItem(COOKIE_KEY, JSON.stringify({
      ...choice,
      timestamp: Date.now(),
      version: 1,
    }));
  } catch (_) {}
}

window.getCookieConsent = readCookieChoice;
window.hasCookieConsent = (cat) => {
  const c = readCookieChoice();
  if (!c) return false;
  if (cat === "essential") return true; // always allowed
  return !!c[cat];
};

function CookiesBanner() {
  const [t] = window.useT();
  const [visible, setVisible] = React.useState(() => readCookieChoice() === null);
  const [shown, setShown] = React.useState(false);
  const [showDetails, setShowDetails] = React.useState(false);
  const [analytics, setAnalytics] = React.useState(false);
  const [marketing, setMarketing] = React.useState(false);

  React.useEffect(() => {
    if (visible) {
      const id = requestAnimationFrame(() => setShown(true));
      return () => cancelAnimationFrame(id);
    } else {
      setShown(false);
    }
  }, [visible]);

  // Allow reopening from external link (e.g., footer "Cookies" link)
  React.useEffect(() => {
    const handler = () => {
      const existing = readCookieChoice();
      if (existing) {
        setAnalytics(!!existing.analytics);
        setMarketing(!!existing.marketing);
      }
      setShowDetails(true);
      setVisible(true);
    };
    window.__omegaOpenCookies = handler;
    window.addEventListener("omega:cookies:open", handler);
    return () => {
      delete window.__omegaOpenCookies;
      window.removeEventListener("omega:cookies:open", handler);
    };
  }, []);

  if (!visible) return null;

  const acceptAll = () => {
    writeCookieChoice({ essential: true, analytics: true, marketing: true });
    setVisible(false);
  };
  const essentialOnly = () => {
    writeCookieChoice({ essential: true, analytics: false, marketing: false });
    setVisible(false);
  };
  const saveChoices = () => {
    writeCookieChoice({ essential: true, analytics, marketing });
    setVisible(false);
  };

  return (
    <div className={"cookies-banner" + (shown ? " is-shown" : "") + (showDetails ? " is-details" : "")}>
      <div className="cookies-inner">
        {!showDetails ? (
          <>
            <div className="cookies-text">
              <div className="cookies-title">{t("cookies.title")}</div>
              <p className="cookies-body">
                {t("cookies.body")}
                {" "}
                <a
                  className="cookies-link"
                  href="#privacy"
                  onClick={(e) => {
                    e.preventDefault();
                    window.__omegaGo && window.__omegaGo("policies", "privacy");
                  }}
                >
                  {t("cookies.policyLink")}
                </a>
              </p>
            </div>
            <div className="cookies-actions">
              <button className="cookies-btn cookies-btn-ghost" onClick={() => setShowDetails(true)}>
                {t("cookies.btn.customize")}
              </button>
              <button className="cookies-btn cookies-btn-ghost" onClick={essentialOnly}>
                {t("cookies.btn.essential")}
              </button>
              <button className="cookies-btn cookies-btn-primary" onClick={acceptAll}>
                {t("cookies.btn.accept")}
              </button>
            </div>
          </>
        ) : (
          <>
            <div className="cookies-text">
              <div className="cookies-title">{t("cookies.detailsTitle")}</div>
              <p className="cookies-body">{t("cookies.detailsIntro")}</p>
            </div>
            <div className="cookies-categories">
              <div className="cookies-cat">
                <div className="cookies-cat-row">
                  <div>
                    <div className="cookies-cat-name">{t("cookies.cat.essential")}</div>
                    <div className="cookies-cat-desc">{t("cookies.cat.essentialDesc")}</div>
                  </div>
                  <div className="cookies-cat-state cookies-cat-state-locked">
                    {t("cookies.always")}
                  </div>
                </div>
              </div>

              <div className="cookies-cat">
                <div className="cookies-cat-row">
                  <div>
                    <div className="cookies-cat-name">{t("cookies.cat.analytics")}</div>
                    <div className="cookies-cat-desc">{t("cookies.cat.analyticsDesc")}</div>
                  </div>
                  <label className="cookies-switch">
                    <input type="checkbox" checked={analytics} onChange={(e) => setAnalytics(e.target.checked)} />
                    <span className="cookies-switch-slot"><span className="cookies-switch-knob" /></span>
                  </label>
                </div>
              </div>

              <div className="cookies-cat">
                <div className="cookies-cat-row">
                  <div>
                    <div className="cookies-cat-name">{t("cookies.cat.marketing")}</div>
                    <div className="cookies-cat-desc">{t("cookies.cat.marketingDesc")}</div>
                  </div>
                  <label className="cookies-switch">
                    <input type="checkbox" checked={marketing} onChange={(e) => setMarketing(e.target.checked)} />
                    <span className="cookies-switch-slot"><span className="cookies-switch-knob" /></span>
                  </label>
                </div>
              </div>
            </div>
            <div className="cookies-actions">
              <button className="cookies-btn cookies-btn-ghost" onClick={essentialOnly}>
                {t("cookies.btn.essential")}
              </button>
              <button className="cookies-btn cookies-btn-primary" onClick={saveChoices}>
                {t("cookies.btn.save")}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

window.CookiesBanner = CookiesBanner;
