// CookieBanner.jsx — UK GDPR / PECR-compliant cookie consent.
//
// Principles baked in here:
//  • Non-essential cookies (analytics, preference) are OFF until the user opts
//    in — nothing is set on first load.
//  • "Reject" is as easy and prominent as "Accept" (equal-weight buttons).
//  • Granular control: the user can toggle Analytics / Preference separately.
//  • The choice is remembered so we don't nag, and can be re-opened any time
//    (footer / cookies page can call window.mmCookieConsent.open()).
//  • Other code reads consent via window.mmCookieConsent.has('analytics') and
//    can listen for the 'mm-consent-change' event before loading any tracker.
//
// This mirrors what the Cookies Policy (/cookies) promises. Essential cookies
// are always on; everything else waits for a click here.

const _CC_KEY = "mm-cookie-consent-v1";

// Read the stored decision (or null if the visitor hasn't chosen yet).
const _CC_read = () => {
  try {
    const raw = window.localStorage.getItem(_CC_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch (e) {
    return null;
  }
};

const _CC_write = (choice) => {
  const record = { v: 1, ts: new Date().toISOString(), ...choice };
  try { window.localStorage.setItem(_CC_KEY, JSON.stringify(record)); } catch (e) {}
  // Let any future analytics loader react without a page reload.
  try { window.dispatchEvent(new CustomEvent("mm-consent-change", { detail: record })); } catch (e) {}
  return record;
};

// Public helper surface for the rest of the site + future trackers.
window.mmCookieConsent = {
  get: _CC_read,
  has: (category) => {
    const c = _CC_read();
    return !!(c && c[category]);
  },
  // Re-open the banner (used by "Manage cookies" links). Set via the component.
  open: () => {},
};

const CookieConsent = () => {
  const [choice, setChoice] = React.useState(() => _CC_read());
  const [open, setOpen] = React.useState(() => _CC_read() === null);
  const [showPrefs, setShowPrefs] = React.useState(false);
  // Granular toggles — default OFF (no consent assumed).
  const [analytics, setAnalytics] = React.useState(false);
  const [preferences, setPreferences] = React.useState(false);

  // Expose a re-open handle so footer / cookies page can let people change
  // their mind. Seed the toggles from any prior decision when re-opening.
  React.useEffect(() => {
    window.mmCookieConsent.open = () => {
      const prior = _CC_read();
      setAnalytics(!!(prior && prior.analytics));
      setPreferences(!!(prior && prior.preferences));
      setShowPrefs(false);
      setOpen(true);
    };
    return () => { window.mmCookieConsent.open = () => {}; };
  }, []);

  if (!open) return null;

  const decide = (next) => {
    const record = _CC_write({ essential: true, analytics: next.analytics, preferences: next.preferences });
    setChoice(record);
    setOpen(false);
  };

  const acceptAll   = () => decide({ analytics: true,  preferences: true });
  const rejectAll   = () => decide({ analytics: false, preferences: false });
  const saveChosen  = () => decide({ analytics, preferences });

  return (
    <div className="mm-cookie" role="dialog" aria-modal="false" aria-label="Cookie consent"
      aria-describedby="mm-cookie-desc">
      <div className="mm-cookie__inner">
        <div className="mm-cookie__body">
          <span className="mm-mono mm-cookie__tag">COOKIES</span>
          <p id="mm-cookie-desc" className="mm-cookie__text">
            We use essential cookies to make the site work. With your consent we'd also
            use optional analytics and preference cookies to improve it. You can accept,
            reject, or choose. See our <a href="/cookies">Cookies Policy</a>.
          </p>

          {showPrefs && (
            <div className="mm-cookie__prefs">
              <label className="mm-cookie__pref mm-cookie__pref--locked">
                <input type="checkbox" checked disabled />
                <span>
                  <strong>Essential</strong> — required for the site to function. Always on.
                </span>
              </label>
              <label className="mm-cookie__pref">
                <input type="checkbox" checked={analytics}
                  onChange={(e) => setAnalytics(e.target.checked)} />
                <span>
                  <strong>Analytics</strong> — anonymous, aggregate usage so we can fix what breaks.
                </span>
              </label>
              <label className="mm-cookie__pref">
                <input type="checkbox" checked={preferences}
                  onChange={(e) => setPreferences(e.target.checked)} />
                <span>
                  <strong>Preference</strong> — remember choices like dismissed notices.
                </span>
              </label>
            </div>
          )}
        </div>

        <div className="mm-cookie__actions">
          {/* Reject is given the same weight as Accept — no dark patterns. */}
          <button type="button" className="mm-cookie__btn mm-cookie__btn--ghost" onClick={rejectAll}>
            Reject non-essential
          </button>
          {showPrefs ? (
            <button type="button" className="mm-cookie__btn mm-cookie__btn--ghost" onClick={saveChosen}>
              Save choices
            </button>
          ) : (
            <button type="button" className="mm-cookie__btn mm-cookie__btn--ghost"
              onClick={() => setShowPrefs(true)} aria-expanded={showPrefs}>
              Preferences
            </button>
          )}
          <button type="button" className="mm-cookie__btn mm-cookie__btn--primary" onClick={acceptAll}>
            Accept all
          </button>
        </div>
      </div>
    </div>
  );
};

window.CookieConsent = CookieConsent;
