const { useState, useEffect, useCallback } = React;

const CC_STORAGE_KEY = "cyrion_consent_v1";
const CC_VERSION = 1;

const CC_CATEGORIES = [
  { key: "necessary", label: "Strictly Necessary", desc: "Required for login, security, and core site functionality. Cannot be disabled.", locked: true },
  { key: "analytics", label: "Analytics", desc: "Helps us understand usage (page views, feature adoption) so we can improve the Service.", locked: false },
  { key: "marketing", label: "Marketing", desc: "Used to measure campaign performance and personalize outreach. Off by default.", locked: false }
];

function ccReadConsent() {
  try {
    const raw = localStorage.getItem(CC_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    return parsed && parsed.version === CC_VERSION ? parsed : null;
  } catch (e) { return null; }
}

function ccWriteConsent(choices) {
  const record = { version: CC_VERSION, choices, ts: new Date().toISOString() };
  try { localStorage.setItem(CC_STORAGE_KEY, JSON.stringify(record)); } catch (e) {}
  window.dispatchEvent(new CustomEvent("cyrion:consent-updated", { detail: record }));
  return record;
}

function ccDefaultChoices(allOn) {
  const c = {};
  CC_CATEGORIES.forEach((cat) => { c[cat.key] = cat.locked ? true : !!allOn; });
  return c;
}

// Read consent synchronously so gated effects (analytics/marketing SDKs) can check
// window.CyrionConsent.get() before mounting anything that fires network calls.
window.CyrionConsent = window.CyrionConsent || {
  get: ccReadConsent,
  categories: CC_CATEGORIES
};

function CookieSwitch({ cat, on, onToggle }) {
  return (
    <div
      role="switch"
      aria-checked={on}
      aria-disabled={cat.locked}
      onClick={() => !cat.locked && onToggle(cat.key)}
      style={{
        position: 'relative', width: 40, height: 22, flexShrink: 0,
        background: on ? 'var(--accent)' : 'var(--bg-lift)',
        border: `1px solid ${on ? 'var(--accent)' : 'var(--line-2)'}`,
        cursor: cat.locked ? 'not-allowed' : 'pointer',
        opacity: cat.locked ? 0.55 : 1, transition: 'background 160ms'
      }}
    >
      <div style={{ position: 'absolute', top: 2, left: on ? 19 : 2, width: 16, height: 16, background: on ? 'var(--bg)' : 'var(--ink)', transition: 'left 160ms' }} />
    </div>
  );
}

function CookiePreferencesModal({ initial, onClose, onSave }) {
  const [choices, setChoices] = useState(initial);
  const toggle = (key) => setChoices((c) => ({ ...c, [key]: !c[key] }));

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: 'fixed', inset: 0, background: 'rgba(7,8,10,0.72)', zIndex: 210, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}
    >
      <div role="dialog" aria-modal="true" aria-label="Cookie preferences" style={{ width: '100%', maxWidth: 560, maxHeight: '86vh', overflowY: 'auto', background: 'var(--panel)', border: '1px solid var(--line)', padding: 28 }}>
        <h2 style={{ fontSize: 19, fontWeight: 500, color: 'var(--ink)', margin: '0 0 8px', letterSpacing: '-0.01em' }}>Cookie preferences</h2>
        <p style={{ fontSize: 13, color: 'var(--ink-mute)', lineHeight: 1.6, margin: '0 0 22px' }}>
          Choose which categories of cookies we may use on this site. Strictly necessary cookies are always on because the Service cannot function without them.
        </p>
        {CC_CATEGORIES.map((cat) => (
          <div key={cat.key} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, padding: '16px 0', borderTop: '1px solid var(--line)' }}>
            <div>
              <div style={{ fontSize: 13.5, color: 'var(--ink)', fontWeight: 500, marginBottom: 4 }}>
                {cat.label}{cat.locked && <span style={{ color: 'var(--ink-dim)', fontWeight: 400, fontSize: 11 }}> (always on)</span>}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-dim)', lineHeight: 1.55, maxWidth: 380 }}>{cat.desc}</div>
            </div>
            <CookieSwitch cat={cat} on={choices[cat.key]} onToggle={toggle} />
          </div>
        ))}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 24, flexWrap: 'wrap' }}>
          <button className="btn" onClick={() => onSave(ccDefaultChoices(false))}>Reject non-essential</button>
          <button className="btn" onClick={() => onSave(choices)}>Save preferences</button>
          <button className="btn btn-primary" onClick={() => onSave(ccDefaultChoices(true))}>Accept all</button>
        </div>
      </div>
    </div>
  );
}

function CookieConsentBanner() {
  const [consent, setConsent] = useState(() => ccReadConsent());
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    window.CyrionConsent.openPreferences = () => setShowModal(true);
  }, []);

  const handleChoice = useCallback((choices) => {
    const record = ccWriteConsent(choices);
    setConsent(record);
    setShowModal(false);
  }, []);

  if (!consent && !showModal) {
    return (
      <div style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 200 }}>
        <div className="page" style={{
          maxWidth: 1440, margin: '0 auto', padding: '18px var(--gutter)', background: 'var(--panel)',
          borderTop: '1px solid var(--line)', boxShadow: '0 -24px 48px rgba(0,0,0,0.35)',
          display: 'flex', gap: 24, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap'
        }}>
          <div style={{ flex: 1, minWidth: 260, fontSize: 13, lineHeight: 1.6, color: 'var(--ink-mute)' }}>
            We use cookies for essential site functionality, and — only with your consent — analytics and marketing. See our <Link_cc to="/privacy#cookies" style={{ color: 'var(--accent)', borderBottom: '1px solid rgba(0,224,198,0.14)' }}>Privacy Policy</Link_cc> for details.
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
            <button className="btn" onClick={() => setShowModal(true)}>Manage preferences</button>
            <button className="btn" onClick={() => handleChoice(ccDefaultChoices(false))}>Reject non-essential</button>
            <button className="btn btn-primary" onClick={() => handleChoice(ccDefaultChoices(true))}>Accept all</button>
          </div>
        </div>
        {showModal && (
          <CookiePreferencesModal initial={ccDefaultChoices(false)} onClose={() => setShowModal(false)} onSave={handleChoice} />
        )}
      </div>
    );
  }

  return showModal ? (
    <CookiePreferencesModal initial={consent ? consent.choices : ccDefaultChoices(false)} onClose={() => setShowModal(false)} onSave={handleChoice} />
  ) : null;
}

const { Link: Link_cc } = ReactRouterDOM;

Object.assign(window, { CookieConsentBanner });
