// Cookie consent banner + consent manager.
//
// Mirrors the subtle bottom bar on renewalfunds.com (notice + Accept / Decline /
// Privacy policy), but implemented as a real opt-in consent gate:
//
//   • No non-essential / analytics cookies are set until the visitor clicks Accept.
//   • The choice persists across pages via a first-party cookie (180 days) with a
//     localStorage mirror, so the bar shows only until a choice is made.
//   • Declining (or no choice) means only strictly-necessary cookies are used.
//   • Visitors can change their mind any time via window.rcvOpenCookieSettings()
//     (wired to the "Cookie settings" link in the footer).
//   • On Accept, loadAnalytics() runs once — drop your GA4 / analytics snippet
//     there and it will only ever fire with consent.
//
// NOTE: This is a working consent mechanism, not legal advice. Categories,
// wording, and whether implied vs. express consent is sufficient should be
// confirmed with counsel for PIPEDA, BC PIPA, Quebec Law 25, and GDPR.

const CONSENT_KEY = "rcv_cookie_consent"; // value: "accepted" | "declined"
const CONSENT_MAX_AGE = 60 * 60 * 24 * 180; // 180 days, in seconds

function readConsent() {
  const m = document.cookie.match(/(?:^|;\s*)rcv_cookie_consent=(accepted|declined)/);
  if (m) return m[1];
  try { return localStorage.getItem(CONSENT_KEY); } catch (e) { return null; }
}

function writeConsent(value) {
  document.cookie = CONSENT_KEY + "=" + value + ";path=/;max-age=" + CONSENT_MAX_AGE + ";SameSite=Lax";
  try { localStorage.setItem(CONSENT_KEY, value); } catch (e) {}
}

let analyticsLoaded = false;
function loadAnalytics() {
  if (analyticsLoaded) return;
  analyticsLoaded = true;
  // --- Drop analytics here. It only runs after the visitor clicks Accept. ---
  // Example (Google Analytics 4):
  //   const id = "G-XXXXXXXXXX";
  //   const s = document.createElement("script");
  //   s.async = true;
  //   s.src = "https://www.googletagmanager.com/gtag/js?id=" + id;
  //   document.head.appendChild(s);
  //   window.dataLayer = window.dataLayer || [];
  //   window.gtag = function () { window.dataLayer.push(arguments); };
  //   window.gtag("js", new Date());
  //   window.gtag("config", id, { anonymize_ip: true });
  // -------------------------------------------------------------------------
}

function CookieConsent() {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const choice = readConsent();
    if (!choice) setVisible(true);
    else if (choice === "accepted") loadAnalytics();
    // Let the footer "Cookie settings" link re-open the banner.
    window.rcvOpenCookieSettings = () => setVisible(true);
    return () => { delete window.rcvOpenCookieSettings; };
  }, []);

  function choose(value) {
    writeConsent(value);
    if (value === "accepted") loadAnalytics();
    window.dispatchEvent(new CustomEvent("rcv-consent", { detail: value }));
    setVisible(false);
  }

  if (!visible) return null;

  const ghost = {
    background: "transparent",
    color: "rgba(255,255,255,0.7)",
    border: "1px solid rgba(255,255,255,0.28)",
    padding: "8px 16px", borderRadius: 2, cursor: "pointer",
    font: "500 13px 'Plus Jakarta Sans', sans-serif", letterSpacing: "-0.01em",
  };

  return (
    <div
      role="dialog"
      aria-label="Cookie notice"
      style={{
        position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 1000,
        background: "#213A2C", color: "#FFFFFF",
        borderTop: "1px solid rgba(255,255,255,0.12)",
        padding: "16px 24px",
      }}
    >
      <div style={{
        maxWidth: 1280, margin: "0 auto",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 24, flexWrap: "wrap",
      }}>
        <p style={{ margin: 0, fontSize: 13, lineHeight: 1.5, color: "rgba(255,255,255,0.75)", maxWidth: 720, letterSpacing: "0.01em" }}>
          We use cookies to operate this site and, with your consent, to understand how it is used. You can accept or decline non-essential cookies, or read our{" "}
          <a href="privacy.html" style={{ color: "#CDF6B0", textDecoration: "none" }}>privacy policy</a>.
        </p>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button onClick={() => choose("declined")} style={ghost}>Decline</button>
          <button
            onClick={() => choose("accepted")}
            style={{
              background: "#CDF6B0", color: "#213A2C", border: 0,
              padding: "9px 20px", borderRadius: 2, cursor: "pointer",
              font: "600 13px 'Plus Jakarta Sans', sans-serif", letterSpacing: "-0.01em",
            }}
          >Accept</button>
        </div>
      </div>
    </div>
  );
}

window.CookieConsent = CookieConsent;
