// Afford-X · ALM agent — unique brand mark, state machine, floating chat.
const { useState, useRef, useEffect, useCallback, createContext, useContext } = React;

/* ============================================================
   The ALM mark — an Afford-X spark.
   A 4-point star rotated to read as the brand "X", with a green
   gradient core and an orbiting micro-spark (red accent nod to
   the Afford-X "X"). Distinct from any third-party logo.
   ============================================================ */
const STAR = 'M12 1.6C12.7 6.9 17.1 11.3 22.4 12C17.1 12.7 12.7 17.1 12 22.4C11.3 17.1 6.9 12.7 1.6 12C6.9 11.3 11.3 6.9 12 1.6Z';

function AlmMark({ size = 26, state = 'idle', tone = 'green', id = 'm' }) {
  const gid = `almg-${id}`;
  const core = tone === 'white' ? '#fff' : `url(#${gid})`;
  const sat = tone === 'white' ? 'rgba(255,255,255,0.9)' : 'var(--afx-red-bright)';
  return (
    <span className={`alm-mark alm-state-${state}`} aria-hidden="true">
      <svg width={size} height={size} viewBox="0 0 24 24">
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="#74C07F" />
            <stop offset="0.55" stopColor="var(--afx-green-500)" />
            <stop offset="1" stopColor="var(--afx-green-700)" />
          </linearGradient>
        </defs>
        <g className="alm-core" style={{ transform: 'rotate(45deg)', transformOrigin: '12px 12px' }}>
          <path d={STAR} fill={core} />
        </g>
        <g className="alm-orbit">
          <path d={STAR} fill={sat} transform="translate(20.5 4) scale(0.26)" />
        </g>
      </svg>
    </span>
  );
}

/* ============================================================
   Agent state machine (shared via context)
   phase: idle | engaged | listening | thinking | answering
   ============================================================ */
const GREETING = "Hi — I'm ALM, the Affordability Language Model behind Afford-X. Ask me anything about exclusion filters, segments, or how we make intent better.";
const SUGGESTIONS = [
  'What is the Exclusion Filter?',
  'How does ALM score affordability?',
  'Which industries do you serve?',
];

const SYS_PROMPT = `You are ALM, the Affordability Language Model — the AI agent that powers Afford-X, a martech platform.
Afford-X scores audiences on real purchasing power (not just intent) and offers a first-in-market one-click exclusion filter that removes window-shoppers before a campaign launches.
Key facts you can draw on: nearly 1 billion U.S. MAIDs and HEMs across 100+ data segments (income, credit, purchase behavior, intent); a Dollar Scoring Framework; GDPR/CCPA/LGPD compliant, consented/pseudonymized signals; verticals served include auto, luxury, financial services and e-commerce; tagline "We Make Intent Better."
Voice: confident, modern, benefit-led B2B. Speak to the visitor as "you", refer to Afford-X as "we". Keep replies under 70 words, no emoji, no markdown headers. Be concrete and helpful.`;

const AgentCtx = createContext(null);
const useAgent = () => useContext(AgentCtx);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function AgentProvider({ children }) {
  const [open, setOpen] = useState(false);
  const [phase, setPhase] = useState('idle');
  const [messages, setMessages] = useState([{ role: 'assistant', content: GREETING }]);
  const [draft, setDraft] = useState('');
  const busyRef = useRef(false);

  const openWidget = useCallback(() => {
    setOpen(true);
    setPhase((p) => (p === 'idle' ? 'engaged' : p));
  }, []);
  const closeWidget = useCallback(() => {
    setOpen(false);
    if (!busyRef.current) setPhase('idle');
  }, []);

  // listening reacts to visitor typing
  const onDraft = useCallback((v) => {
    setDraft(v);
    if (busyRef.current) return;
    setPhase(v.trim() ? 'listening' : 'engaged');
  }, []);

  const ask = useCallback(async (qRaw) => {
    const q = (qRaw == null ? draft : qRaw).trim();
    if (!q || busyRef.current) return;
    busyRef.current = true;
    setDraft('');
    setMessages((m) => [...m, { role: 'user', content: q }]);
    setPhase('thinking');

    // build short conversation context
    const history = messages.filter((m) => m.role === 'user' || m.role === 'assistant').slice(-6)
      .map((m) => `${m.role === 'user' ? 'Visitor' : 'ALM'}: ${m.content}`).join('\n');
    const prompt = `${SYS_PROMPT}\n\n${history ? 'Conversation so far:\n' + history + '\n\n' : ''}Visitor: ${q}\nALM:`;

    let reply = '';
    try {
      if (window.claude && window.claude.complete) {
        reply = await window.claude.complete(prompt);
      } else {
        throw new Error('no-api');
      }
    } catch (e) {
      reply = "We narrow your intent audience down to people with real purchasing power — our one-click Exclusion Filter removes window-shoppers before launch, so every ad dollar works harder. (Live answers activate when this page is shared.)";
      await sleep(900);
    }
    reply = (reply || '').trim();

    // stream the reply word-by-word for the "answering" state
    setPhase('answering');
    setMessages((m) => [...m, { role: 'assistant', content: '' }]);
    const parts = reply.split(/(\s+)/);
    let acc = '';
    for (const w of parts) {
      acc += w;
      setMessages((m) => { const c = m.slice(); c[c.length - 1] = { role: 'assistant', content: acc }; return c; });
      await sleep(24);
    }
    busyRef.current = false;
    setPhase(open ? 'engaged' : 'idle');
  }, [draft, messages, open]);

  const value = { open, phase, messages, draft, openWidget, closeWidget, onDraft, ask, busy: () => busyRef.current };
  return <AgentCtx.Provider value={value}>{children}</AgentCtx.Provider>;
}

/* ============================================================
   Header indicator — "Ask ALM" pill that reflects live state
   ============================================================ */
const LABELS = {
  idle: 'Ask ALM',
  engaged: 'ALM is here',
  listening: 'Listening…',
  thinking: 'Thinking…',
  answering: 'Answering…',
};
const DOT_COLOR = {
  idle: 'var(--afx-gray-400)',
  engaged: 'var(--afx-green-500)',
  listening: 'var(--afx-green-500)',
  thinking: 'var(--afx-yellow)',
  answering: 'var(--afx-green-500)',
};

function HeaderAgent() {
  const { phase, open, openWidget, closeWidget } = useAgent();
  const active = phase !== 'idle';
  return (
    <button
      onClick={open ? closeWidget : openWidget}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 9, cursor: 'pointer',
        height: 40, padding: '0 14px 0 10px', borderRadius: 999,
        border: `1.5px solid ${active ? 'var(--afx-green-500)' : 'var(--afx-gray-200)'}`,
        background: active ? 'var(--afx-green-50)' : '#fff',
        fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14,
        color: 'var(--afx-ink)', transition: 'border-color 0.18s ease, background 0.18s ease',
      }}
    >
      <AlmMark size={22} state={phase} id="hdr" />
      <span style={{ minWidth: 78, textAlign: 'left' }}>{LABELS[phase]}</span>
      <span className={active ? 'alm-dot' : ''} style={{ width: 8, height: 8, borderRadius: '50%', background: DOT_COLOR[phase], color: DOT_COLOR[phase], display: 'inline-block' }} />
    </button>
  );
}

/* ============================================================
   Floating widget — bottom-right bubble + chat panel
   ============================================================ */
function Bubble() {
  const { open, phase, openWidget } = useAgent();
  if (open) return null;
  const busy = phase === 'thinking' || phase === 'answering';
  return (
    <button
      onClick={openWidget}
      aria-label="Open ALM assistant"
      style={{
        position: 'fixed', right: 26, bottom: 26, zIndex: 60,
        width: 62, height: 62, borderRadius: '50%', cursor: 'pointer', border: 'none',
        background: 'linear-gradient(135deg, var(--afx-green-400), var(--afx-green-600))',
        boxShadow: '0 10px 28px rgba(42,87,52,0.34)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}
    >
      {!busy && <span className="alm-bubble-ring" />}
      <AlmMark size={32} state={phase} tone="white" id="bub" />
    </button>
  );
}

function SubLine({ phase }) {
  if (phase === 'thinking') return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      Thinking <span className="alm-think-dots"><span></span><span></span><span></span></span>
    </span>
  );
  if (phase === 'answering') return <span>Answering…</span>;
  if (phase === 'listening') return <span>Listening…</span>;
  return <span>Online · replies in seconds</span>;
}

function Panel() {
  const { open, phase, messages, draft, closeWidget, onDraft, ask, busy } = useAgent();
  const scrollRef = useRef(null);
  const inputRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, phase, open]);
  useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); }, [open]);
  if (!open) return null;
  const isBusy = busy();

  return (
    <div className="alm-panel" style={{
      position: 'fixed', right: 26, bottom: 26, zIndex: 60,
      width: 380, maxWidth: 'calc(100vw - 32px)', height: 560, maxHeight: 'calc(100vh - 52px)',
      background: '#fff', borderRadius: 18, overflow: 'hidden',
      border: '1px solid var(--afx-gray-200)', boxShadow: '0 24px 60px rgba(5,7,8,0.22)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: 'linear-gradient(135deg, #0c2414, #061a0e)', color: '#fff' }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <AlmMark size={26} state={phase} tone="white" id="pnl" />
        </div>
        <div style={{ flex: 1, lineHeight: 1.2 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>ALM</div>
          <div style={{ fontSize: 12, opacity: 0.85 }}><SubLine phase={phase} /></div>
        </div>
        <button onClick={closeWidget} aria-label="Close" style={{ background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fff', width: 30, height: 30, borderRadius: 8, cursor: 'pointer', fontSize: 18, lineHeight: 1 }}>×</button>
      </div>

      {/* messages */}
      <div ref={scrollRef} className="alm-scroll" style={{ flex: 1, overflowY: 'auto', padding: '18px 16px', background: 'var(--afx-gray-50)', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {messages.map((m, i) => (
          <div key={i} className="alm-msg" style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
            <div style={{
              maxWidth: '82%', padding: '10px 13px', fontSize: 14, lineHeight: 1.5,
              fontFamily: 'var(--font-body)',
              borderRadius: m.role === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
              background: m.role === 'user' ? 'var(--afx-green-500)' : '#fff',
              color: m.role === 'user' ? '#fff' : 'var(--afx-gray-700)',
              border: m.role === 'user' ? 'none' : '1px solid var(--afx-gray-200)',
              boxShadow: m.role === 'user' ? 'none' : '0 1px 2px rgba(5,7,8,0.04)',
            }}>{m.content || '\u200b'}</div>
          </div>
        ))}
        {phase === 'thinking' && (
          <div className="alm-msg" style={{ display: 'flex', justifyContent: 'flex-start' }}>
            <div style={{ padding: '12px 14px', background: '#fff', border: '1px solid var(--afx-gray-200)', borderRadius: '14px 14px 14px 4px', display: 'flex', alignItems: 'center', gap: 4 }}>
              <span className="alm-think-dots"><span></span><span></span><span></span></span>
            </div>
          </div>
        )}
        {messages.length <= 1 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 4 }}>
            {SUGGESTIONS.map((s) => (
              <button key={s} className="alm-chip" onClick={() => ask(s)} style={{
                padding: '7px 12px', borderRadius: 999, fontSize: 13, fontFamily: 'var(--font-body)',
                background: '#fff', border: '1px solid var(--afx-gray-300)', color: 'var(--afx-green-700)', cursor: 'pointer',
              }}>{s}</button>
            ))}
          </div>
        )}
      </div>

      {/* input */}
      <form onSubmit={(e) => { e.preventDefault(); ask(); }} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 12, borderTop: '1px solid var(--afx-gray-200)', background: '#fff' }}>
        <input
          ref={inputRef}
          value={draft}
          onChange={(e) => onDraft(e.target.value)}
          placeholder={isBusy ? 'ALM is responding…' : 'Ask about Afford-X…'}
          disabled={isBusy}
          style={{
            flex: 1, height: 42, padding: '0 14px', borderRadius: 999, fontSize: 14, fontFamily: 'var(--font-body)',
            border: '1.5px solid var(--afx-gray-200)', outline: 'none', color: 'var(--afx-ink)', background: 'var(--afx-gray-50)',
          }}
          onFocus={(e) => (e.target.style.borderColor = 'var(--afx-green-500)')}
          onBlur={(e) => (e.target.style.borderColor = 'var(--afx-gray-200)')}
        />
        <button type="submit" disabled={isBusy || !draft.trim()} aria-label="Send" style={{
          width: 42, height: 42, borderRadius: '50%', border: 'none', flexShrink: 0,
          cursor: isBusy || !draft.trim() ? 'default' : 'pointer',
          background: !draft.trim() || isBusy ? 'var(--afx-gray-200)' : 'var(--afx-green-500)',
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'background 0.15s ease',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
        </button>
      </form>
    </div>
  );
}

function AgentWidget() {
  return <><Bubble /><Panel /></>;
}

Object.assign(window, { AgentProvider, useAgent, HeaderAgent, AgentWidget, AlmMark });
// Afford-X · Free Evaluation flow — email capture dialog + browser-extension explainer.
const { Button, Badge, Input, Dialog } = window.AffordXDesignSystem_998110;
const EvalCtx = React.createContext(null);
const useEval = () => React.useContext(EvalCtx);
const EVAL_KEY = 'afx_eval_email';
const EXT_DEMO = '/extension';

function detectBrowser() {
  const ua = (navigator.userAgent || '').toLowerCase();
  if (ua.includes('firefox')) return { name: 'Firefox', store: 'Firefox Add-ons' };
  if (ua.includes('edg/')) return { name: 'Edge', store: 'Chrome Web Store' };
  if (ua.includes('chrome') || ua.includes('chromium')) return { name: 'Chrome', store: 'Chrome Web Store' };
  if (ua.includes('safari')) return { name: 'Safari', store: 'Extensions' };
  return { name: 'your browser', store: 'extension store' };
}

// little browser glyph for the install button
function BrowserGlyph({ name }) {
  return (
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      {name === 'Firefox'
        ? <path d="M12 3c4 1 5 4 5 7a5 5 0 1 1-9-3" />
        : <><circle cx="12" cy="12" r="3.2" /><line x1="12" y1="3" x2="12" y2="8.8" /><line x1="20" y1="16" x2="14.8" y2="13.5" /><line x1="4" y1="16" x2="9.2" y2="13.5" /></>}
    </svg>
  );
}

function EvalProvider({ children }) {
  const [open, setOpen] = React.useState(false);
  const [stage, setStage] = React.useState('email');
  const [email, setEmail] = React.useState('');
  const [err, setErr] = React.useState('');

  const openEval = React.useCallback(() => {
    const saved = localStorage.getItem(EVAL_KEY) || '';
    setEmail(saved);
    setErr('');
    setStage(saved ? 'done' : 'email');
    setOpen(true);
  }, []);
  const close = React.useCallback(() => setOpen(false), []);

  const submit = React.useCallback(() => {
    const v = email.trim();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v)) { setErr('Enter a valid work email.'); return; }
    localStorage.setItem(EVAL_KEY, v);
    setErr('');
    setStage('done');
  }, [email]);

  return (
    <EvalCtx.Provider value={{ openEval, close, open, stage, email, setEmail, submit, err }}>
      {children}
    </EvalCtx.Provider>
  );
}

function EvalDialog() {
  const ev = useEval();
  if (!ev || !ev.open) return null;
  const b = detectBrowser();

  if (ev.stage === 'email') {
    return (
      <Dialog open title="Start your Free Evaluation" onClose={ev.close} width={460}
        footer={<>
          <Button variant="ghost" onClick={ev.close}>Cancel</Button>
          <Button variant="primary" onClick={ev.submit}>Continue</Button>
        </>}>
        <p style={{ margin: '0 0 16px' }}>Enter your work email to begin. You’ll use the <strong>same email</strong> to verify inside the browser extension.</p>
        <form onSubmit={(e) => { e.preventDefault(); ev.submit(); }}>
          <Input label="Work email" type="email" placeholder="you@company.com" value={ev.email}
            error={ev.err || undefined}
            onChange={(e) => ev.setEmail(e.target.value)} autoFocus
            leading={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="m3 7 9 6 9-6" /></svg>} />
        </form>
        <p style={{ fontSize: 12.5, color: 'var(--afx-gray-500)', margin: '14px 0 0' }}>No campaign data leaves your browser during evaluation. GDPR / CCPA / LGPD compliant.</p>
      </Dialog>
    );
  }

  // done → install extension
  return (
    <Dialog open title="You’re in. Add the extension." onClose={ev.close} width={480}
      footer={<>
        <Button variant="ghost" onClick={ev.close}>Maybe later</Button>
        <Button variant="primary" iconLeft={<BrowserGlyph name={b.name} />} onClick={() => { window.location.href = EXT_DEMO; }}>Add to {b.name}</Button>
      </>}>
      <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', marginBottom: 6 }}>
        <span style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--afx-green-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <window.AlmMark size={26} state="engaged" id="dlg" />
        </span>
        <div>
          <p style={{ margin: '0 0 8px' }}>We’ll verify <strong style={{ color: 'var(--afx-ink)' }}>{ev.email}</strong> inside the Afford-X ALM extension.</p>
          <p style={{ margin: 0, fontSize: 14, color: 'var(--afx-gray-600)' }}>Install it from the {b.store}, open your ad platform, and ALM will guide you from there.</p>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 16 }}>
        {['Meta', 'Google Display Network', 'DV360'].map((p) => <Badge key={p} tone="neutral">{p}</Badge>)}
      </div>
    </Dialog>
  );
}

// ---- Landing-page section explaining the extension ----
function MiniExtMock() {
  return (
    <div style={{ position: 'relative', background: 'var(--afx-gray-50)', border: '1px solid var(--afx-gray-200)', borderRadius: 16, padding: 18, overflow: 'hidden' }}>
      {/* fake browser toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ display: 'flex', gap: 5 }}>
          {['#FF5F57', '#FEBC2E', '#28C840'].map((c) => <span key={c} style={{ width: 10, height: 10, borderRadius: '50%', background: c }} />)}
        </span>
        <div style={{ flex: 1, height: 26, borderRadius: 7, background: '#fff', border: '1px solid var(--afx-gray-200)', display: 'flex', alignItems: 'center', padding: '0 10px', fontSize: 11.5, color: 'var(--afx-gray-500)', fontFamily: 'var(--font-mono)' }}>app.adsmanager.com/campaigns</div>
        <span style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--afx-green-500)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <window.AlmMark size={16} state="engaged" tone="white" id="mini" />
        </span>
      </div>
      {/* page body with overlaid ALM cue */}
      <div style={{ position: 'relative', height: 168, borderRadius: 10, background: '#fff', border: '1px solid var(--afx-gray-200)', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: '56px 1fr', opacity: 0.5 }}>
          <div style={{ background: 'var(--afx-black)' }} />
          <div style={{ padding: 12 }}>
            <div style={{ height: 10, width: '40%', background: 'var(--afx-gray-200)', borderRadius: 4, marginBottom: 10 }} />
            <div style={{ display: 'flex', gap: 8 }}>{[0, 1, 2].map((i) => <div key={i} style={{ flex: 1, height: 38, background: 'var(--afx-gray-100)', borderRadius: 6 }} />)}</div>
            <div style={{ marginTop: 10, height: 46, background: 'var(--afx-gray-100)', borderRadius: 6 }} />
          </div>
        </div>
        {/* ALM coachmark */}
        <div style={{ position: 'absolute', left: 14, top: 54, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="alm-dot" style={{ width: 18, height: 18, borderRadius: '50%', border: '2px solid var(--afx-green-500)', color: 'var(--afx-green-500)', background: 'rgba(84,169,102,0.15)' }} />
          <span style={{ background: 'var(--afx-green-600)', color: '#fff', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, padding: '4px 9px', borderRadius: 999, boxShadow: 'var(--shadow-sm)' }}>Click here →</span>
        </div>
        {/* ALM chat peek */}
        <div style={{ position: 'absolute', right: 12, bottom: 12, width: 132, background: '#fff', border: '1px solid var(--afx-gray-200)', borderRadius: 10, boxShadow: 'var(--shadow-md)', padding: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <window.AlmMark size={14} state="answering" id="peek" />
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 11, color: 'var(--afx-ink)' }}>ALM</span>
          </div>
          <div style={{ height: 6, width: '90%', background: 'var(--afx-green-100)', borderRadius: 3, marginBottom: 4 }} />
          <div style={{ height: 6, width: '60%', background: 'var(--afx-gray-100)', borderRadius: 3 }} />
        </div>
      </div>
    </div>
  );
}

function ExtensionSection() {
  const ev = useEval();
  const b = detectBrowser();
  const steps = [
    ['Install the extension', `Add Afford-X ALM from the ${b.store} — one click, no setup.`],
    ['Open your ad platform', 'Head to Meta, Google Display Network or DV360. ALM draws cues showing where to go.'],
    ['Watch ALM simulate', 'Once it reads your live performance, a dashboard overlays your platform in real time.'],
  ];
  return (
    <section id="extension" style={{ background: 'var(--afx-gray-50)', borderTop: '1px solid var(--afx-gray-200)', borderBottom: '1px solid var(--afx-gray-200)' }}>
      <div style={{ maxWidth: 1120, margin: '0 auto', padding: '72px 28px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center' }}>
        <div>
          <span className="afx-eyebrow">Browser Extension</span>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 34, letterSpacing: '-0.02em', color: 'var(--afx-ink)', margin: '14px 0 14px' }}>Evaluate ALM on your live campaigns</h2>
          <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--afx-gray-600)', margin: '0 0 24px' }}>
            With the Afford-X ALM browser extension you can evaluate — and see the real effectiveness of our solution — directly on the campaigns you’re already running. No data leaves your browser.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 28 }}>
            {steps.map(([t, d], i) => (
              <div key={t} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                <span style={{ width: 28, height: 28, borderRadius: '50%', flexShrink: 0, background: 'var(--afx-green-500)', color: '#fff', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</span>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 16, color: 'var(--afx-ink)' }}>{t}</div>
                  <div style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--afx-gray-600)' }}>{d}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <Button variant="primary" size="lg" iconLeft={<BrowserGlyph name={b.name} />} onClick={ev.openEval}>Add to {b.name} — free</Button>
            <a href={EXT_DEMO} style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 15, color: 'var(--afx-green-700)', textDecoration: 'none' }}>See how it works →</a>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 18, alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: 'var(--afx-gray-500)' }}>Works with</span>
            {['Meta', 'Google Display Network', 'DV360'].map((p) => <Badge key={p} tone="neutral">{p}</Badge>)}
          </div>
        </div>
        <MiniExtMock />
      </div>
    </section>
  );
}

Object.assign(window, { EvalProvider, useEval, EvalDialog, ExtensionSection, detectBrowser });
// Afford-X marketing site — homepage + ALM agent integration.
const { Button, Badge, FeatureCard, Steps, Card } = window.AffordXDesignSystem_998110;
const { AgentProvider, HeaderAgent, AgentWidget, EvalProvider, useEval, EvalDialog, ExtensionSection } = window;
const A = 'assets/';

function SiteHeader() {
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 30, background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)', borderBottom: '1px solid var(--afx-gray-200)' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 28px', height: 72, display: 'flex', alignItems: 'center', gap: 32 }}>
        <img src={A + 'logo.png'} alt="Afford-X" style={{ height: 30 }} />
        <nav style={{ display: 'flex', gap: 28, marginLeft: 12 }}>
          {[['Product Highlights', '#'], ['How Afford-X Works', '#'], ['Blog', '/blog'], ['Pricing', '/pricing']].map(([l, href]) => (
            <a key={l} href={href} style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: 'var(--afx-gray-600)', textDecoration: 'none' }}>{l}</a>
          ))}
        </nav>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 12, alignItems: 'center' }}>
          <HeaderAgent />
          <Button variant="primary" size="sm">Contact us</Button>
        </div>
      </div>
    </header>
  );
}

function Hero() {
  return (
    <section style={{ position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -120, right: -80, width: 520, height: 520, background: 'radial-gradient(circle, rgba(84,169,102,0.16), transparent 70%)', pointerEvents: 'none' }} />
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '72px 28px 64px', display: 'grid', gridTemplateColumns: '1.05fr 0.95fr', gap: 48, alignItems: 'center' }}>
        <div>
          <span className="afx-eyebrow">Affordability Intelligence</span>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 60, lineHeight: 1.04, letterSpacing: '-0.03em', color: 'var(--afx-ink)', margin: '16px 0 0' }}>
            We Make Intent Better<span style={{ color: 'var(--afx-red-bright)' }}>.</span>
          </h1>
          <p style={{ fontSize: 19, lineHeight: 1.6, color: 'var(--afx-gray-600)', maxWidth: 520, margin: '20px 0 32px' }}>
            Tap into real buying power with the <strong style={{ color: 'var(--afx-ink)' }}>Affordability Language Model (ALM)</strong> — our AI agent that filters out what can’t convert, so every advertising dollar works harder.
          </p>
          <div style={{ display: 'flex', gap: 14 }}>
            <Button variant="primary" size="lg" onClick={useEval().openEval}>Free Evaluation</Button>
            <Button variant="secondary" size="lg" onClick={() => document.getElementById('extension').scrollIntoView({ behavior: 'smooth' })}>How it works</Button>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <img src={A + 'visual-web-3.png'} alt="Afford-X data science" style={{ width: '100%', maxWidth: 460 }} />
        </div>
      </div>
    </section>
  );
}

function Pillars() {
  return (
    <section style={{ maxWidth: 1200, margin: '0 auto', padding: '24px 28px 72px' }}>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 36, letterSpacing: '-0.02em', color: 'var(--afx-ink)', textAlign: 'center', margin: '0 0 8px' }}>
        Afford-X lets you <span className="afx-grad-green">Exclude. Target. Convert.</span>
      </h2>
      <p style={{ textAlign: 'center', color: 'var(--afx-gray-500)', maxWidth: 560, margin: '0 auto 40px', fontSize: 16 }}>Real purchasing power at the center of every campaign.</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 20 }}>
        <FeatureCard icon={<SvgIcon d={ICN.filter} />} eyebrow="First in market" title="Exclusion Filter">One click narrows your intent audience to people financially ready to act — before the campaign begins.</FeatureCard>
        <FeatureCard icon={<SvgIcon d={ICN.layers} />} title="Data Science Simplified">Deep analysis of 100+ behavioral, income and credit segments — we take on the heavy lifting.</FeatureCard>
        <FeatureCard icon={<SvgIcon d={ICN.sparkles} />} title="AI-First Advertising">ALM adapts to your industry with dynamically-updated feeds and real-world signals.</FeatureCard>
      </div>
    </section>
  );
}

function FeatureRow({ img, eyebrow, title, lead, body, flip }) {
  const text = (
    <div style={{ flex: 1 }}>
      <span className="afx-eyebrow">{eyebrow}</span>
      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 30, letterSpacing: '-0.02em', color: 'var(--afx-ink)', margin: '12px 0 16px' }}>{title}</h3>
      <p style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--afx-gray-600)', margin: '0 0 14px' }}>{lead}</p>
      <p style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 16, color: 'var(--afx-green-700)', margin: 0 }}>{body}</p>
    </div>
  );
  const pic = <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}><img src={A + img} alt={title} style={{ width: '100%', maxWidth: 440, borderRadius: 'var(--radius-lg)' }} /></div>;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 56, padding: '40px 0' }}>
      {flip ? <>{pic}{text}</> : <>{text}{pic}</>}
    </div>
  );
}

function Highlights() {
  return (
    <section style={{ background: 'var(--afx-gray-50)', borderTop: '1px solid var(--afx-gray-200)', borderBottom: '1px solid var(--afx-gray-200)' }}>
      <div style={{ maxWidth: 1120, margin: '0 auto', padding: '64px 28px' }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 32, letterSpacing: '-0.02em', color: 'var(--afx-ink)', textAlign: 'center', margin: '0 0 8px' }}>Product Highlights</h2>
        <FeatureRow img="affordable.webp" eyebrow="Make intent better" title="Real purchasing power, scored" lead="ALM builds on intent signals by integrating privacy-compliant financial signals with behavioral insights and purchase history." body="Simpler segments, greater precision." />
        <FeatureRow img="filter.webp" flip eyebrow="First-in-market" title="The Exclusion Filter" lead="Afford-X pre-screens your intent audience — removing unconvertible interest and raising the share of people with real purchasing power." body="Sharper targeting, higher efficiency." />
        <FeatureRow img="visual-web-4.png" eyebrow="AI-first" title="Built for your industry" lead="From auto to luxury to financial services, ALM refines your audience with the freshest affordability, intent and behavioral signals." body="Instant start, smarter optimization." />
      </div>
    </section>
  );
}

function HowItWorks() {
  return (
    <section style={{ maxWidth: 1120, margin: '0 auto', padding: '72px 28px' }}>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 32, letterSpacing: '-0.02em', color: 'var(--afx-ink)', textAlign: 'center', margin: '0 0 40px' }}>How Afford-X Works</h2>
      <Card variant="default" padding={0} style={{ overflow: 'hidden', marginBottom: 48 }}>
        <img src={A + 'dashboard.png'} alt="Afford-X dashboard" style={{ width: '100%', display: 'block' }} />
      </Card>
      <Steps current={4} steps={[
        { title: 'Share your campaign details', desc: 'Our AI agent analyzes the inputs and recommends the best-fit Afford-X segment.' },
        { title: 'Select an Afford-X segment', desc: 'Go with the AI recommendation or pick the one that fits your goals.' },
        { title: 'Launch with precision', desc: 'Connect your ad account, activate the segment, and let Afford-X refine your audience.' },
      ]} />
    </section>
  );
}

function CtaBand() {
  return (
    <section style={{ background: 'var(--afx-green-500)' }}>
      <div style={{ maxWidth: 1000, margin: '0 auto', padding: '64px 28px', textAlign: 'center', color: '#fff' }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 40, letterSpacing: '-0.02em', margin: '0 0 12px', color: '#fff' }}>Affordability Makes Intent Better</h2>
        <p style={{ fontSize: 18, opacity: 0.95, margin: '0 0 28px' }}>Your efficiency accelerator — because real buyers drive real results.</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          <Button variant="danger" size="lg" onClick={useEval().openEval}>Free Evaluation</Button>
          <Button variant="secondary" size="lg" style={{ background: 'rgba(255,255,255,0.12)', borderColor: '#fff', color: '#fff' }}>Contact us</Button>
        </div>
      </div>
    </section>
  );
}

function SiteFooter() {
  return (
    <footer style={{ background: 'var(--afx-black)', color: 'var(--afx-gray-400)' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '48px 28px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
        <div style={{ background: '#fff', borderRadius: 'var(--radius-md)', padding: '12px 18px' }}><img src={A + 'logo.png'} alt="Afford-X" style={{ height: 26, display: 'block' }} /></div>
        <div style={{ display: 'flex', gap: 24, fontFamily: 'var(--font-display)', fontSize: 14 }}>
          {['Product Highlights', 'How Afford-X Works', 'Terms & Conditions', 'Privacy Policy'].map((l) => <a key={l} href="#" style={{ color: 'var(--afx-gray-400)', textDecoration: 'none' }}>{l}</a>)}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 13 }}>Find us on</span>
          <span style={{ width: 34, height: 34, borderRadius: 'var(--radius-sm)', background: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <img src={A + 'linkedin.svg'} alt="LinkedIn" style={{ width: 18, height: 18 }} />
          </span>
        </div>
      </div>
    </footer>
  );
}

const ICN = {
  filter: '<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>',
  layers: '<polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/>',
  sparkles: '<path d="M12 3l1.9 5.8L20 11l-6.1 2.2L12 19l-1.9-5.8L4 11l6.1-2.2z"/>',
};
function SvgIcon({ d }) {
  return <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: d }} />;
}

function SiteHome() {
  return (
    <AgentProvider>
      <EvalProvider>
      <div style={{ background: '#fff' }}>
        <SiteHeader /><Hero /><Pillars /><Highlights /><HowItWorks /><ExtensionSection /><CtaBand /><SiteFooter />
      </div>
      <AgentWidget />
      <EvalDialog />
      </EvalProvider>
    </AgentProvider>
  );
}

Object.assign(window, { SiteHome });

// auto-render
document.body.innerHTML = '<div id="afx-root"></div>';
ReactDOM.createRoot(document.getElementById('afx-root')).render(<window.SiteHome />);
