// COOKIE CONSENT BANNER
// Pairs with the default-deny Consent Mode snippet in each page's <head>
// (see the inline script above the GTM tag). This component only records the
// user's choice and pushes the update; the blocking itself is done by Google
// Consent Mode inside GTM.
//
// Storage: localStorage key `outrun-cookie-consent`, shape
//   { analytics: bool, marketing: bool, ts: ISO8601, v: 1 }
// Bump CONSENT_VERSION to re-ask everyone (e.g. if a new vendor is added).

const CONSENT_KEY = 'outrun-cookie-consent';
const CONSENT_VERSION = 1;

function readConsent() {
  try {
    const raw = localStorage.getItem(CONSENT_KEY);
    if (!raw) return null;
    const v = JSON.parse(raw);
    return v && v.v === CONSENT_VERSION ? v : null;
  } catch (e) { return null; }
}

function pushConsent({ analytics, marketing }) {
  const state = {
    analytics_storage: analytics ? 'granted' : 'denied',
    ad_storage: marketing ? 'granted' : 'denied',
    ad_user_data: marketing ? 'granted' : 'denied',
    ad_personalization: marketing ? 'granted' : 'denied',
  };
  if (typeof window.gtag === 'function') {
    window.gtag('consent', 'update', state);
  }
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({ event: 'outrun_consent_update', ...state });
}

function writeConsent({ analytics, marketing }) {
  try {
    localStorage.setItem(CONSENT_KEY, JSON.stringify({
      analytics, marketing, ts: new Date().toISOString(), v: CONSENT_VERSION,
    }));
  } catch (e) { /* private mode - choice applies to this session only */ }
  pushConsent({ analytics, marketing });
}

// Footer "Cookie settings" link calls this.
window.openCookieSettings = function () {
  window.dispatchEvent(new CustomEvent('outrun:open-cookie-settings'));
};

function CcButton({ kind, onClick, children }) {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  const [hover, setHover] = React.useState(false);
  const solid = kind === 'solid';
  const base = solid ? ED.green : ED.ink;
  return (
    <button
      type="button"
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        ...edText.med, fontSize: 13, letterSpacing: '-0.005em',
        padding: '8px 16px', borderRadius: 2, cursor: 'pointer',
        border: `1.5px solid ${base}`,
        background: solid ? (hover ? 'transparent' : base) : (hover ? base : 'transparent'),
        color: solid ? (hover ? base : '#FFFFFF') : (hover ? '#FFFFFF' : base),
        transition: 'background 140ms ease, color 140ms ease',
        whiteSpace: 'nowrap', fontFamily: 'inherit',
      }}
    >{children}</button>
  );
}

function CcToggle({ label, note, checked, onChange, locked }) {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '11px 0', borderTop: `1px solid ${ED.rule}` }}>
      <button
        type="button"
        role="switch"
        aria-checked={checked}
        aria-label={label}
        disabled={locked}
        onClick={() => !locked && onChange(!checked)}
        style={{
          flex: '0 0 auto', width: 32, height: 19, borderRadius: 999, marginTop: 1,
          border: `1.5px solid ${checked ? ED.ink : ED.rule}`,
          background: checked ? ED.ink : 'transparent',
          cursor: locked ? 'default' : 'pointer', opacity: locked ? 0.45 : 1,
          padding: 0, position: 'relative', transition: 'background 140ms ease, border-color 140ms ease',
        }}
      >
        <span style={{
          position: 'absolute', top: 2, left: checked ? 15 : 2,
          width: 11, height: 11, borderRadius: '50%',
          background: checked ? '#FFFFFF' : ED.ink2,
          transition: 'left 140ms ease',
        }} />
      </button>
      <div>
        <div style={{ ...edText.med, fontSize: 13, color: ED.ink }}>
          {label}{locked && <span style={{ ...edText.sans, fontSize: 11.5, color: ED.ink2, marginLeft: 7 }}>Always on</span>}
        </div>
        <div style={{ ...edText.sans, fontSize: 12, lineHeight: 1.45, color: ED.ink2, marginTop: 2 }}>{note}</div>
      </div>
    </div>
  );
}

function CookieConsent() {
  const ED = React.useContext(EdCtx);
  const edText = ED.text;
  const isMobile = useIsMobile();
  const [open, setOpen] = React.useState(false);
  const [detail, setDetail] = React.useState(false);
  const [analytics, setAnalytics] = React.useState(true);
  const [marketing, setMarketing] = React.useState(false);

  React.useEffect(() => {
    const saved = readConsent();
    if (saved) {
      pushConsent(saved);            // re-assert on every page load
    } else {
      const t = setTimeout(() => setOpen(true), 600);
      return () => clearTimeout(t);
    }
  }, []);

  React.useEffect(() => {
    const reopen = () => {
      const saved = readConsent();
      if (saved) { setAnalytics(saved.analytics); setMarketing(saved.marketing); }
      setDetail(false); setOpen(true);
    };
    window.addEventListener('outrun:open-cookie-settings', reopen);
    return () => window.removeEventListener('outrun:open-cookie-settings', reopen);
  }, []);

  if (!open) return null;

  const decide = (a, m) => { writeConsent({ analytics: a, marketing: m }); setOpen(false); setDetail(false); };

  return (
    <div role="dialog" aria-label="Cookie preferences" style={{
      position: 'fixed', zIndex: 9000,
      ...(isMobile
        ? { left: 12, right: 12, bottom: 12 }
        : { right: 24, bottom: 24, width: '25%', minWidth: 320, maxWidth: 420 }),
      background: ED.bg, border: `1px solid ${ED.rule}`,
      boxShadow: '0 10px 34px rgba(55,71,79,0.13)',
      padding: isMobile ? '18px 18px 20px' : '22px 24px 24px',
    }}>
      <div>
        {!detail ? (
          <div>
            <div style={{ ...edText.med, fontSize: 14, color: ED.ink, marginBottom: 7 }}>
              Cookies
            </div>
            <p style={{ ...edText.sans, fontSize: 13.5, lineHeight: 1.55, color: ED.ink2, margin: '0 0 16px' }}>
              We use essential cookies to make the site work, and analytics to understand how it&rsquo;s used.{' '}
              <a href="/cookie-policy" style={{ color: ED.ink2, textDecoration: 'underline', textUnderlineOffset: 2 }}>Cookie Policy</a>.
            </p>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
              <CcButton kind="solid" onClick={() => decide(true, true)}>Accept</CcButton>
              <CcButton onClick={() => decide(false, false)}>Reject</CcButton>
              <button type="button" onClick={() => setDetail(true)} style={{ ...edText.sans, fontSize: 13, color: ED.ink2, background: 'none', border: 'none', padding: '6px 4px', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2, marginLeft: 2, fontFamily: 'inherit' }}>Choose</button>
            </div>
          </div>
        ) : (
          <div>
            <div style={{ ...edText.med, fontSize: 14, color: ED.ink, marginBottom: 4 }}>
              Cookie preferences
            </div>
            <p style={{ ...edText.sans, fontSize: 13, lineHeight: 1.5, color: ED.ink2, margin: '0 0 6px' }}>
              Detail in our{' '}
              <a href="/cookie-policy" style={{ color: ED.ink2, textDecoration: 'underline', textUnderlineOffset: 2 }}>Cookie Policy</a>.
            </p>
            <div>
              <CcToggle locked checked label="Strictly necessary" note="Required for the site to work. Cannot be switched off." onChange={() => {}} />
              <CcToggle checked={analytics} onChange={setAnalytics} label="Analytics" note="Google Analytics. Until you choose, it runs without storing cookies on your device." />
              <CcToggle checked={marketing} onChange={setMarketing} label="Marketing" note="LinkedIn Insight Tag. Off until you turn it on." />
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 16, paddingTop: 14, borderTop: `1px solid ${ED.rule}` }}>
              <CcButton kind="solid" onClick={() => decide(analytics, marketing)}>Save</CcButton>
              <CcButton onClick={() => decide(false, false)}>Reject all</CcButton>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CookieConsent, readConsent, openCookieSettings: window.openCookieSettings });
