// components/cookie-banner.jsx
// CookieBanner - Block B2.
// Strict opt-in for analytics. localStorage key "fanish_cookie_consent" persists choice.
// Banner appears with 1.5s delay on first visit (no recorded consent).
// Esc dismisses. Tap targets >= 44px. role="dialog" + aria-labelledby.

(function () {
  var CONSENT_KEY = "fanish_cookie_consent";

  function readConsent() {
    try {
      var raw = localStorage.getItem(CONSENT_KEY);
      return raw ? JSON.parse(raw) : null;
    } catch (e) { return null; }
  }

  function writeConsent(value) {
    try {
      localStorage.setItem(CONSENT_KEY, JSON.stringify(value));
    } catch (e) { /* noop */ }
    window.dispatchEvent(new CustomEvent("fanish:consent-updated", { detail: value }));
  }

  function CookieBanner() {
    var C = window.COPY;
    var IconCloseEl = window.IconClose;
    var stateVisible = React.useState(false);
    var visible = stateVisible[0]; var setVisible = stateVisible[1];
    var stateManage = React.useState(false);
    var manageOpen = stateManage[0]; var setManageOpen = stateManage[1];
    var stateAnalytics = React.useState(false);
    var analyticsOn = stateAnalytics[0]; var setAnalyticsOn = stateAnalytics[1];

    React.useEffect(function () {
      var existing = readConsent();
      if (existing) return;
      var t = setTimeout(function () { setVisible(true); }, 1500);
      return function () { clearTimeout(t); };
    }, []);

    var handle = function (decision) {
      var consent;
      if (decision === "accept") consent = { essential: true, analytics: true, ts: Date.now() };
      else if (decision === "decline") consent = { essential: true, analytics: false, ts: Date.now() };
      else if (decision === "save") consent = { essential: true, analytics: analyticsOn, ts: Date.now() };
      writeConsent(consent);
      setVisible(false);
      setManageOpen(false);
    };

    React.useEffect(function () {
      if (!visible && !manageOpen) return;
      var onKey = function (e) {
        if (e.key === "Escape") {
          if (manageOpen) setManageOpen(false);
          else handle("decline");
        }
      };
      window.addEventListener("keydown", onKey);
      return function () { window.removeEventListener("keydown", onKey); };
    }, [visible, manageOpen]);

    if (!visible) return null;

    return (
      <div className="cookie-banner-wrap">
        <div className="cookie-banner" role="dialog" aria-labelledby="cookie-heading" aria-describedby="cookie-copy">
          <div className="cookie-banner-inner">
            <p id="cookie-copy" className="cookie-copy">
              <span id="cookie-heading" className="cookie-heading">Cookies.</span>{" "}
              {C.privacy.bannerCopy}
            </p>
            <div className="cookie-actions">
              <button type="button" className="cookie-btn cookie-btn-secondary" onClick={function () { handle("decline"); }}>{C.privacy.decline}</button>
              <button type="button" className="cookie-btn cookie-btn-secondary" onClick={function () { setManageOpen(true); }}>{C.privacy.manage}</button>
              <button type="button" className="cookie-btn cookie-btn-primary" onClick={function () { handle("accept"); }}>{C.privacy.accept}</button>
            </div>
          </div>
        </div>

        {manageOpen && (
          <div className="modal-backdrop" onClick={function (e) { if (e.target === e.currentTarget) setManageOpen(false); }}>
            <div className="modal-card cookie-manage" role="dialog" aria-modal="true" aria-labelledby="cookie-manage-h">
              <button type="button" className="modal-x" onClick={function () { setManageOpen(false); }} aria-label="Close">
                <IconCloseEl />
              </button>
              <h2 id="cookie-manage-h" className="modal-headline">{C.privacy.manageHeading}</h2>
              <p className="modal-body">{C.privacy.manageBody}</p>

              <div className="cookie-row">
                <div className="cookie-row-text">
                  <p className="cookie-row-label">{C.privacy.essentialLabel}</p>
                  <p className="cookie-row-hint">{C.privacy.essentialHint}</p>
                </div>
                <div className="cookie-toggle disabled" aria-disabled="true">
                  <span className="cookie-toggle-track on"><span className="cookie-toggle-knob" /></span>
                </div>
              </div>

              <div className="cookie-row">
                <div className="cookie-row-text">
                  <p className="cookie-row-label">{C.privacy.analyticsLabel}</p>
                  <p className="cookie-row-hint">{C.privacy.analyticsHint}</p>
                </div>
                <button type="button" className="cookie-toggle" role="switch" aria-checked={analyticsOn} onClick={function () { setAnalyticsOn(function (v) { return !v; }); }}>
                  <span className={"cookie-toggle-track" + (analyticsOn ? " on" : "")}>
                    <span className="cookie-toggle-knob" />
                  </span>
                </button>
              </div>

              <button type="button" className="dl-btn cookie-save" onClick={function () { handle("save"); }}>{C.privacy.save}</button>
            </div>
          </div>
        )}
      </div>
    );
  }

  window.CookieBanner = CookieBanner;
})();
