/* global React */
/* =============================================================================
   Cookie consent banner — GDPR / CCPA compliant
   - First visit: banner blocks all non-essential scripts
   - Equal-weight Accept All / Reject All buttons (regulator-safe)
   - Customize panel: 5 categories, all OFF by default except strictly necessary
   - Consent stored in first-party cookie `doblier_cookie_consent`, 12-month expiry
   - Global window.reopenCookieSettings() reopens the banner from the footer link
   - GA4 / Hotjar / HubSpot / Calendly load CONDITIONALLY based on stored consent.
     (No scripts actually wired in this prototype — the gating mechanism is what
     ships; site reads `window.doblierConsent` and uses `consentchange` event.)
   ============================================================================= */

const { useState: useCCState, useEffect: useCCEffect, useCallback: useCCCallback } = React;

const CONSENT_COOKIE = "doblier_cookie_consent";
const CONSENT_VERSION = 1; // bump to force re-prompt site-wide
const CATEGORIES = [
  {
    key: "necessary",
    label: "Strictly necessary",
    locked: true,
    body: "Cloudflare, session, CSRF. Required for the site to load and stay secure.",
    examples: "cf_clearance · doblier_session · csrf_token",
  },
  {
    key: "analytics",
    label: "Analytics",
    body: "Aggregated, anonymized usage data so we know which pages get read. No personal profiles.",
    examples: "_ga · _ga_* · _gid (Google Analytics 4)",
  },
  {
    key: "recording",
    label: "Session recording",
    body: "Anonymized session playback to debug UX problems. All form fields are masked.",
    examples: "_hjSessionUser_* · _hjSession_* (Hotjar)",
  },
  {
    key: "marketing",
    label: "Marketing",
    body: "CRM linkage so a conversation you start with us stays continuous.",
    examples: "__hssc · __hstc · hubspotutk (HubSpot)",
  },
  {
    key: "scheduling",
    label: "Scheduling",
    body: "Calendar embeds (architect demos). Loaded only on contact pages.",
    examples: "calendly_session (Calendly)",
  },
];

/* ---------- cookie helpers ---------- */
function readCookie(name) {
  const m = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
  if (!m) return null;
  try { return JSON.parse(decodeURIComponent(m[1])); } catch { return null; }
}
function writeCookie(name, value, maxAgeSeconds) {
  const v = encodeURIComponent(JSON.stringify(value));
  const secure = location.protocol === "https:" ? "; Secure" : "";
  document.cookie = `${name}=${v}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax${secure}`;
}

function emptyConsent(value = false) {
  return CATEGORIES.reduce((acc, c) => {
    acc[c.key] = c.locked ? true : value;
    return acc;
  }, {});
}
function readConsent() {
  const raw = readCookie(CONSENT_COOKIE);
  if (!raw || raw.version !== CONSENT_VERSION) return null;
  return raw;
}
function saveConsent(prefs) {
  const value = {
    version: CONSENT_VERSION,
    timestamp: new Date().toISOString(),
    ...prefs,
  };
  // 12 months
  writeCookie(CONSENT_COOKIE, value, 60 * 60 * 24 * 365);
  // Expose globally + broadcast — script loaders listen for this.
  window.doblierConsent = value;
  window.dispatchEvent(new CustomEvent("consentchange", { detail: value }));
  return value;
}

/* ---------- entry point: <CookieConsent /> ---------- */
function CookieConsent() {
  const [open, setOpen] = useCCState(false);          // banner / modal visible?
  const [customizing, setCustomizing] = useCCState(false);
  const [prefs, setPrefs] = useCCState(() => emptyConsent(false));
  const [savedNote, setSavedNote] = useCCState(false);

  // On mount: if no valid consent cookie, open banner.
  useCCEffect(() => {
    const existing = readConsent();
    if (existing) {
      window.doblierConsent = existing;
      // backfill prefs state so customize shows the current values when reopened
      const next = emptyConsent(false);
      CATEGORIES.forEach((c) => { next[c.key] = !!existing[c.key]; });
      setPrefs(next);
    } else {
      setOpen(true);
    }
  }, []);

  // Footer "Cookie Settings" link calls this.
  useCCEffect(() => {
    window.reopenCookieSettings = () => {
      const existing = readConsent();
      if (existing) {
        const next = emptyConsent(false);
        CATEGORIES.forEach((c) => { next[c.key] = !!existing[c.key]; });
        setPrefs(next);
      }
      setCustomizing(true);
      setOpen(true);
      setSavedNote(false);
    };
    return () => { delete window.reopenCookieSettings; };
  }, []);

  const close = useCCCallback(() => {
    setOpen(false);
    setCustomizing(false);
  }, []);

  const acceptAll = () => { saveConsent(emptyConsent(true)); setSavedNote(true); setTimeout(close, 500); };
  const rejectAll = () => { saveConsent(emptyConsent(false)); setSavedNote(true); setTimeout(close, 500); };
  const savePrefs = () => { saveConsent(prefs); setSavedNote(true); setTimeout(close, 500); };

  if (!open) return null;

  return (
    <div className="cc-root" role="dialog" aria-modal="false" aria-labelledby="cc-headline">
      <div className={`cc-shell ${customizing ? "wide" : ""}`}>
        {!customizing ? (
          <>
            <div className="cc-eyebrow">// COOKIE PREFERENCES</div>
            <div className="cc-body">
              <div className="cc-text">
                <h3 id="cc-headline">Cookie preferences</h3>
                <p>
                  We use cookies for analytics and site functionality. Nothing fires until you choose.
                  Read our <a href="#/cookies" onClick={close}>Cookie Policy</a> for the full list.
                </p>
              </div>
              <div className="cc-actions">
                <button className="cc-btn cc-btn-ghost" onClick={() => setCustomizing(true)}>Customize</button>
                <button className="cc-btn cc-btn-outline" onClick={rejectAll}>Reject All</button>
                <button className="cc-btn cc-btn-primary" onClick={acceptAll}>Accept All</button>
              </div>
            </div>
            <div className="cc-meta">
              // Stored as <code>doblier_cookie_consent</code> · expires 12 months from acceptance · change any time from footer
            </div>
          </>
        ) : (
          <>
            <div className="cc-row cc-row-head">
              <div>
                <div className="cc-eyebrow">// CUSTOMIZE COOKIES</div>
                <h3 id="cc-headline" style={{ marginTop: 8 }}>Choose what runs.</h3>
                <p className="cc-sub">Each toggle controls one bucket of third-party scripts. Strictly necessary cookies can't be disabled — without them the site won't load.</p>
              </div>
              <button className="cc-close" onClick={close} aria-label="Close cookie settings">×</button>
            </div>

            <div className="cc-cats">
              {CATEGORIES.map((c) => (
                <div className="cc-cat" key={c.key}>
                  <div className="cc-cat-top">
                    <div>
                      <div className="cc-cat-label">{c.label}</div>
                      <div className="cc-cat-body">{c.body}</div>
                    </div>
                    <Toggle
                      checked={!!prefs[c.key]}
                      disabled={c.locked}
                      onChange={(v) => setPrefs({ ...prefs, [c.key]: v })}
                      label={c.label}
                    />
                  </div>
                  <div className="cc-cat-examples">{c.examples}</div>
                </div>
              ))}
            </div>

            <div className="cc-row cc-row-foot">
              <div className="cc-meta" style={{ flex: 1 }}>
                // Stored 12 months · re-open from footer "Cookie Settings"
              </div>
              <div className="cc-actions">
                <button className="cc-btn cc-btn-outline" onClick={rejectAll}>Reject All</button>
                <button className="cc-btn cc-btn-outline" onClick={acceptAll}>Accept All</button>
                <button className="cc-btn cc-btn-primary" onClick={savePrefs}>Save preferences</button>
              </div>
            </div>
          </>
        )}
        {savedNote && (
          <div className="cc-saved">
            <span className="cc-dot" /> Saved. Scripts will respect your choice on this and future visits.
          </div>
        )}
      </div>

      <style>{`
        .cc-root {
          position: fixed;
          left: 0; right: 0; bottom: 0;
          z-index: 200;
          padding: 16px;
          display: flex;
          justify-content: center;
          pointer-events: none;
        }
        .cc-shell {
          pointer-events: auto;
          width: 100%;
          max-width: 1080px;
          background: #0c0c0c;
          border: 1px solid var(--border-bright);
          border-radius: 4px;
          box-shadow: 0 24px 60px -16px rgba(0,0,0,0.7);
          padding: 24px 28px;
          color: var(--text);
          position: relative;
        }
        .cc-shell.wide { max-width: 880px; }
        .cc-eyebrow {
          font-family: var(--font-mono);
          font-size: 11px;
          letter-spacing: 0.08em;
          color: var(--teal);
          text-transform: uppercase;
        }
        .cc-body {
          display: grid;
          grid-template-columns: minmax(0, 1fr) auto;
          gap: 32px;
          align-items: center;
          margin-top: 12px;
        }
        .cc-text h3 { font-size: 20px; font-weight: 500; letter-spacing: -0.01em; margin: 0 0 6px; }
        .cc-text p {
          color: var(--text-dim);
          font-size: 14px;
          line-height: 1.55;
          margin: 0;
          max-width: 64ch;
        }
        .cc-text p a { color: var(--teal); text-decoration: none; border-bottom: 1px solid rgba(0,212,170,0.4); }
        .cc-text p a:hover { border-color: var(--teal); }
        .cc-actions {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
        }
        .cc-btn {
          font-family: var(--font-sans);
          font-size: 13px;
          font-weight: 500;
          padding: 11px 18px;
          border-radius: 2px;
          border: 1px solid transparent;
          cursor: pointer;
          letter-spacing: 0.01em;
          transition: background 0.15s, border-color 0.15s, color 0.15s;
          min-width: 120px;
          text-align: center;
        }
        /* CRITICAL: Reject All MUST be equal visual weight to Accept All.
           Same size, same padding. Only fill differs. */
        .cc-btn-primary {
          background: var(--teal);
          color: #001a14;
          font-weight: 600;
        }
        .cc-btn-primary:hover { background: #00ebbd; }
        .cc-btn-outline {
          background: transparent;
          color: var(--text);
          border-color: var(--border-bright);
          font-weight: 500;
        }
        .cc-btn-outline:hover { border-color: var(--teal); color: var(--teal); }
        .cc-btn-ghost {
          background: transparent;
          color: var(--text-dim);
          border-color: transparent;
          padding: 11px 14px;
          min-width: 0;
          text-decoration: underline;
          text-decoration-color: var(--text-mute);
          text-underline-offset: 4px;
        }
        .cc-btn-ghost:hover { color: var(--text); }
        .cc-meta {
          margin-top: 14px;
          font-family: var(--font-mono);
          font-size: 10px;
          letter-spacing: 0.06em;
          color: var(--text-mute);
          text-transform: uppercase;
        }
        .cc-meta code {
          color: var(--text-dim);
          font-family: var(--font-mono);
          text-transform: none;
          letter-spacing: 0.02em;
        }
        .cc-row { display: flex; gap: 24px; }
        .cc-row-head { justify-content: space-between; align-items: flex-start; }
        .cc-row-head .cc-sub {
          color: var(--text-dim); font-size: 13px; line-height: 1.55; margin: 8px 0 0; max-width: 64ch;
        }
        .cc-close {
          background: transparent;
          border: 1px solid var(--border-bright);
          color: var(--text-dim);
          width: 32px; height: 32px;
          border-radius: 2px;
          cursor: pointer;
          font-size: 18px;
          line-height: 1;
        }
        .cc-close:hover { color: var(--text); border-color: var(--teal); }
        .cc-cats {
          margin: 24px 0;
          display: flex;
          flex-direction: column;
          border-top: 1px solid var(--border);
        }
        .cc-cat {
          padding: 20px 0;
          border-bottom: 1px solid var(--border);
        }
        .cc-cat-top {
          display: flex;
          gap: 24px;
          justify-content: space-between;
          align-items: flex-start;
        }
        .cc-cat-label {
          font-size: 14px;
          font-weight: 500;
          color: var(--text);
          letter-spacing: -0.005em;
        }
        .cc-cat-body {
          font-size: 13px;
          color: var(--text-dim);
          line-height: 1.55;
          margin-top: 6px;
          max-width: 56ch;
        }
        .cc-cat-examples {
          margin-top: 10px;
          font-family: var(--font-mono);
          font-size: 11px;
          color: var(--text-mute);
        }
        .cc-row-foot {
          justify-content: space-between;
          align-items: center;
          flex-wrap: wrap;
        }
        .cc-saved {
          margin-top: 14px;
          padding-top: 14px;
          border-top: 1px solid var(--border);
          display: inline-flex;
          align-items: center;
          gap: 8px;
          font-family: var(--font-mono);
          font-size: 11px;
          color: var(--text-dim);
          letter-spacing: 0.04em;
        }
        .cc-dot { width: 6px; height: 6px; background: var(--teal); border-radius: 50%; display: inline-block; }
        @media (max-width: 760px) {
          .cc-body { grid-template-columns: 1fr; gap: 16px; }
          .cc-actions { width: 100%; }
          .cc-btn { flex: 1; min-width: 0; }
          .cc-row-foot { gap: 14px; }
        }
      `}</style>
    </div>
  );
}

/* ---------- toggle switch ---------- */
function Toggle({ checked, disabled, onChange, label }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      aria-label={`${label} ${checked ? "enabled" : "disabled"}`}
      disabled={disabled}
      onClick={() => !disabled && onChange(!checked)}
      className={`cc-toggle ${checked ? "on" : "off"} ${disabled ? "locked" : ""}`}
    >
      <span className="cc-thumb" />
      <style>{`
        .cc-toggle {
          width: 44px;
          height: 24px;
          border-radius: 24px;
          border: 1px solid var(--border-bright);
          background: rgba(255,255,255,0.04);
          position: relative;
          cursor: pointer;
          padding: 0;
          flex-shrink: 0;
          transition: background 0.15s, border-color 0.15s;
        }
        .cc-toggle .cc-thumb {
          position: absolute;
          left: 2px; top: 50%;
          transform: translateY(-50%);
          width: 18px; height: 18px;
          border-radius: 50%;
          background: var(--text-mute);
          transition: left 0.15s, background 0.15s;
        }
        .cc-toggle.on { background: var(--teal); border-color: var(--teal); }
        .cc-toggle.on .cc-thumb { left: 22px; background: #001a14; }
        .cc-toggle.locked { opacity: 0.55; cursor: not-allowed; }
        .cc-toggle.locked.on { background: var(--teal-dim); }
      `}</style>
    </button>
  );
}

Object.assign(window, { CookieConsent });
