/* ProofSource redesign — Home page. Exports window.Home. */

function timeAgo(iso) {
  const s = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000));
  if (s < 5) return 'just now';
  if (s < 60) return s + 's ago';
  const m = Math.floor(s / 60);
  if (m < 60) return m + 'm ago';
  const h = Math.floor(m / 60);
  if (h < 24) return h + 'h ago';
  return Math.floor(h / 24) + 'd ago';
}

function HeroField() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const N = 32;
    const LINK_DIST = 150;
    const COLORS = ['84,180,136', '91,192,235']; // --earned, --buy
    let width = 0, height = 0, dpr = 1, raf = null;
    let nodes = [];

    function resize() {
      const parent = canvas.parentElement;
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      width = parent.offsetWidth;
      height = parent.offsetHeight;
      canvas.width = width * dpr;
      canvas.height = height * dpr;
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }

    function initNodes() {
      nodes = Array.from({ length: N }, () => ({
        x: Math.random() * width,
        y: Math.random() * height,
        vx: (Math.random() - 0.5) * 0.14,
        vy: (Math.random() - 0.5) * 0.14,
      }));
    }

    function frame() {
      ctx.clearRect(0, 0, width, height);
      for (let i = 0; i < nodes.length; i++) {
        const a = nodes[i];
        if (!reduceMotion) {
          a.x += a.vx; a.y += a.vy;
          if (a.x < 0 || a.x > width) a.vx *= -1;
          if (a.y < 0 || a.y > height) a.vy *= -1;
        }
        for (let j = i + 1; j < nodes.length; j++) {
          const b = nodes[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const dist = Math.sqrt(dx * dx + dy * dy);
          if (dist < LINK_DIST) {
            ctx.strokeStyle = `rgba(${COLORS[(i + j) % 2]},${(1 - dist / LINK_DIST) * 0.32})`;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }
      for (const n of nodes) {
        ctx.fillStyle = 'rgba(126,212,173,.5)';
        ctx.beginPath();
        ctx.arc(n.x, n.y, 1.5, 0, Math.PI * 2);
        ctx.fill();
      }
      if (!reduceMotion) raf = requestAnimationFrame(frame);
    }

    resize();
    initNodes();
    frame();

    function onResize() { resize(); initNodes(); if (reduceMotion) frame(); }
    window.addEventListener('resize', onResize);
    return () => {
      if (raf) cancelAnimationFrame(raf);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  return (
    <canvas ref={canvasRef} aria-hidden="true"
      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.55, pointerEvents: 'none' }} />
  );
}

function LiveTransactions({ go }) {
  const [total, setTotal] = useState(null);
  const [recent, setRecent] = useState([]);
  const [idx, setIdx] = useState(0);
  const [show, setShow] = useState(true);

  function load() {
    Promise.all([window.PS_API.traction(), window.PS_API.receipts()]).then(([t, r]) => {
      if (t) setTotal(t.totalPayoutUsdc);
      if (Array.isArray(r)) setRecent(r.slice(0, 5));
    }).catch(() => {});
  }
  useEffect(() => { load(); }, []);
  useInterval(load, 8000);

  // Rotate the single caption line through recent settlements, crossfading.
  useInterval(() => {
    if (recent.length < 2) return;
    setShow(false);
    setTimeout(() => { setIdx((i) => (i + 1) % recent.length); setShow(true); }, 250);
  }, 4000, recent.length > 1);

  const current = recent[idx % (recent.length || 1)];

  return (
    <div style={{ textAlign: 'right' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 7, marginBottom: 10 }}>
        <span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--earned)', boxShadow: 'var(--glow-earned)', animation: 'tagdot 1.4s infinite' }} />
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--faint)', textTransform: 'uppercase', letterSpacing: '.1em' }}>live · arc · usdc</span>
      </div>

      <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 'clamp(34px,3.2vw,46px)', letterSpacing: '-.02em', color: 'var(--earned2)' }}>
        {total == null ? '—' : usd(total, 6)}
      </div>
      <div style={{ fontSize: 13, color: 'var(--mut)', marginTop: 4 }}>paid to creators, updating live</div>

      <div style={{ marginTop: 18, minHeight: 34, opacity: show ? 1 : 0, transition: 'opacity .25s ease' }}>
        {current ? (
          <div style={{ fontSize: 13, color: 'var(--text)' }}>
            <b>{current.providerName}</b> earned <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--earned2)' }}>+{usd(current.amountUsdc, 6)}</span>
            <span style={{ color: 'var(--faint)' }}> · {timeAgo(current.createdAt)} · </span>
            {current.circleStatus === 'completed' ? (
              <span style={{ color: 'var(--earned2)' }}>✓ settled on Circle</span>
            ) : (
              <span style={{ color: 'var(--faint)' }}>settling…</span>
            )}
            {current.arcAddressUrl && (
              <>
                {' · '}
                <a href={current.arcAddressUrl} target="_blank" rel="noopener"
                  style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--buy)' }}>
                  buyer wallet ↗
                </a>
              </>
            )}
          </div>
        ) : (
          <div style={{ fontSize: 13, color: 'var(--faint)' }}>waiting for the first live settlement…</div>
        )}
      </div>

      <a onClick={() => go('traction')} style={{ display: 'inline-block', marginTop: 14, fontSize: 12, color: 'var(--mut)', cursor: 'pointer' }}>View full traction →</a>
    </div>
  );
}

function Door({ accent, kicker, title, body, cta, onClick }) {
  const [h, setH] = useState(false);
  const c = accent === 'earn' ? 'var(--earned2)' : 'var(--buy)';
  return (
    <div onMouseEnter={() => setH(1)} onMouseLeave={() => setH(0)}
      style={{ position: 'relative', background: 'var(--card-fill)', border: '1px solid ' + (h ? (accent === 'earn' ? 'var(--earned-line)' : '#2c5a70') : 'var(--line)'), borderRadius: 18, padding: 26, overflow: 'hidden', transition: 'border-color .2s, transform .2s', transform: h ? 'translateY(-2px)' : 'none' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(420px 200px at 100% 0%, ' + (accent === 'earn' ? 'rgba(84,180,136,.10)' : 'rgba(91,192,235,.10)') + ', transparent 70%)', opacity: h ? 1 : .5, transition: 'opacity .3s', pointerEvents: 'none' }} />
      <div style={{ position: 'relative' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: c, marginBottom: 14 }}>{kicker}</div>
        <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 25, letterSpacing: '-.035em', margin: '0 0 10px', color: c }}>{title}</h3>
        <p style={{ color: 'var(--mut)', fontSize: 14.5, lineHeight: 1.55, margin: '0 0 20px', maxWidth: 380 }}>{body}</p>
        <Btn variant={accent === 'earn' ? 'earn' : 'primary'} onClick={onClick}>{cta}</Btn>
      </div>
    </div>
  );
}

function IntegrationsRow() {
  const items = ['Circle', 'Arc', 'MCP', 'OpenClaw'];
  return (
    <div style={{ maxWidth: 1360, margin: '0 auto', padding: '2px 26px 28px', display: 'flex', alignItems: 'center', gap: 26, flexWrap: 'wrap' }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--faint)', textTransform: 'uppercase', letterSpacing: '.12em', flexShrink: 0 }}>
        Integrates with
      </span>
      <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
        {items.map((name) => (
          <span key={name} style={{ fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: 600, color: 'var(--mut)' }}>
            {name}
          </span>
        ))}
      </div>
    </div>
  );
}

const TRY_SUGGESTIONS = [
  'What are the key arguments around AI content licensing?',
  'How should music royalties be split by what listeners played?',
  'How does per-image licensing pay photographers instantly?',
  'What is the best sourdough bread recipe?',
];

function TryItLive() {
  const [question, setQuestion] = useState(TRY_SUGGESTIONS[0]);
  const [running, setRunning] = useState(false);
  const [result, setResult] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [revealed, setRevealed] = useState(0);
  const [cooldown, setCooldown] = useState(0);
  const revealTimer = useRef(null);
  const cooldownTimer = useRef(null);

  useEffect(() => () => {
    if (revealTimer.current) clearInterval(revealTimer.current);
    if (cooldownTimer.current) clearInterval(cooldownTimer.current);
  }, []);

  function startCooldown() {
    let t = 12;
    setCooldown(t);
    if (cooldownTimer.current) clearInterval(cooldownTimer.current);
    cooldownTimer.current = setInterval(() => {
      t -= 1;
      setCooldown(t);
      if (t <= 0) clearInterval(cooldownTimer.current);
    }, 1000);
  }

  async function run() {
    const q = question.trim();
    if (running || cooldown > 0 || !q) return;
    setRunning(true);
    setResult(null);
    setErrorMsg(null);
    setRevealed(0);
    try {
      const res = await fetch('/v1/proofsource/demo/research-agent/run', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ workspaceId: 'ws_demo', agentId: 'agent_live_web', question: q.slice(0, 240) }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || 'Request failed');
      setResult(data);
      const stepCount = (data.trace || []).length;
      let i = 0;
      revealTimer.current = setInterval(() => {
        i += 1;
        setRevealed(i);
        if (i >= stepCount) clearInterval(revealTimer.current);
      }, 320);
    } catch (e) {
      setErrorMsg('Could not reach the live agent — try again in a moment.');
    } finally {
      setRunning(false);
      startCooldown();
    }
  }

  const steps = (result?.trace || []).map((t) => t.step);
  const action = result?.decision?.action;
  const badgeTone = action === 'BUY' ? 'buy' : action === 'REUSE' ? 'reuse' : 'skip';
  const doneRevealing = steps.length > 0 && revealed >= steps.length;

  return (
    <section style={{ maxWidth: 1360, margin: '0 auto', padding: '0 26px 60px' }}>
      <SectionHead eyebrow="Try it live" title="Ask a real question. Watch the agent decide." center style={{ marginBottom: 28 }} />
      <div style={{ maxWidth: 860, margin: '0 auto', background: 'var(--card-fill)', border: '1px solid var(--line)', borderRadius: 16, padding: 22 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
          {TRY_SUGGESTIONS.map((q) => {
            const on = question === q;
            return (
              <button key={q} onClick={() => setQuestion(q)}
                style={{ fontFamily: 'var(--font-sans)', fontSize: 12.5, padding: '7px 12px', borderRadius: 7, cursor: 'pointer',
                  border: '1px solid ' + (on ? 'var(--buy-line)' : 'var(--line)'),
                  background: on ? 'var(--buy-fill)' : 'transparent',
                  color: on ? 'var(--buy)' : 'var(--mut)' }}>
                {q.length > 44 ? q.slice(0, 44) + '…' : q}
              </button>
            );
          })}
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <input value={question} onChange={(e) => setQuestion(e.target.value)} maxLength={240}
            placeholder="Ask a research question…"
            style={{ flex: '1 1 300px', fontFamily: 'var(--font-sans)', fontSize: 14, padding: '11px 14px', borderRadius: 9,
              border: '1px solid var(--line)', background: 'var(--panel2)', color: 'var(--text)' }} />
          <Btn variant="earn" onClick={run} disabled={running || cooldown > 0 || !question.trim()}>
            {running ? 'Running…' : cooldown > 0 ? `Wait ${cooldown}s` : 'Ask the agent →'}
          </Btn>
        </div>

        {errorMsg && <div style={{ marginTop: 14, fontSize: 12.5, color: 'var(--block)' }}>{errorMsg}</div>}

        {(running || result) && (
          <div style={{ marginTop: 20, paddingTop: 20, borderTop: '1px solid var(--line-soft)' }}>
            <div style={{ fontSize: 10.5, color: 'var(--faint)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 700, marginBottom: 10 }}>
              Live settlement pipeline
            </div>
            {steps.length > 0 ? (
              <Pipeline steps={steps} reached={revealed} gateStep="verify" />
            ) : (
              <div style={{ fontSize: 12.5, color: 'var(--faint)' }}>Contacting the live agent…</div>
            )}

            {doneRevealing && result?.decision && (
              <div style={{ marginTop: 18, animation: 'pageIn .4s ease' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                  <Badge tone={badgeTone}>{action}</Badge>
                  <span style={{ fontSize: 13, color: 'var(--mut)' }}>{result.decision.reasoning}</span>
                </div>
                {result.sources?.[0] && (
                  <div style={{ marginTop: 12, fontSize: 13 }}>
                    Cited <b>{result.sources[0].providerName}</b>
                    {result.spend?.totalUsdc && Number(result.spend.totalUsdc) > 0 && (
                      <> · paid <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--earned2)' }}>${result.spend.totalUsdc}</span></>
                    )}
                    {result.sources[0].receiptId && (
                      <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--faint)', fontSize: 11.5 }}> · {result.sources[0].receiptId}</span>
                    )}
                  </div>
                )}
                {result.answer && (
                  <p style={{ marginTop: 12, fontSize: 13.5, color: 'var(--text)', lineHeight: 1.6, fontFamily: 'var(--font-serif)' }}>
                    {result.answer.length > 320 ? result.answer.slice(0, 320) + '…' : result.answer}
                  </p>
                )}
              </div>
            )}
          </div>
        )}
      </div>
      <p style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--faint)', marginTop: 14 }}>
        A real call to the live API — a real Arc/Circle settlement when the agent decides to buy.
      </p>
    </section>
  );
}

const HOW = [
  { n: '01', t: 'Creators list work', d: 'Connect a feed, set a sub-cent price, add a wallet — or get a managed one.' },
  { n: '02', t: 'Agents decide', d: 'A budgeted agent scores permitted sources on value-per-cent and picks one to buy.' },
  { n: '03', t: 'Verified settlement', d: 'Payment releases on Arc only after delivery passes seven deterministic checks.' },
  { n: '04', t: 'Proof of earning', d: 'Every citation leaves a tamper-evident receipt and a reusable paid-context record.' },
];

function Home({ go }) {
  return (
    <div className="page">

      {/* 0–5s: WHAT IS THIS */}
      <section style={{ position: 'relative', overflow: 'hidden', maxWidth: 1360, margin: '0 auto', padding: '46px 26px 40px', display: 'grid', gridTemplateColumns: 'minmax(0,.85fr) minmax(0,1.15fr)', gap: 54, alignItems: 'center' }} className="hero-grid">
        <HeroField />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Tag tone="earned" style={{ marginBottom: 22 }}>Live on Arc · USDC · sub-cent citations</Tag>
          <h1 style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 'clamp(40px,6vw,66px)', lineHeight: 1.08, letterSpacing: '-.025em', margin: '0 0 22px', textWrap: 'balance' }}>
            Knowledge that<br /><em style={{ fontStyle: 'normal', color: 'var(--earned2)' }}>settles in real time.</em>
          </h1>
          <p style={{ fontSize: 18, color: 'var(--mut)', lineHeight: 1.65, maxWidth: 500, margin: '0 0 28px' }}>
            Right now, when an AI agent cites your work, you earn nothing. ProofSource is the settlement floor that changes that — the agent pays you a sub-cent amount and seals a tamper-evident receipt, all in one step.
          </p>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Btn variant="earn" size="lg" onClick={() => go('creators')}>Get paid for your work</Btn>
            <Btn variant="outline" size="lg" onClick={() => go('demo')}>Watch the floor live →</Btn>
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <LiveTransactions go={go} />
        </div>
      </section>

      <IntegrationsRow />

      {/* 5–15s: HOW IT WORKS */}
      <section style={{ maxWidth: 1360, margin: '0 auto', padding: '56px 26px 60px', borderTop: '1px solid var(--line-soft)' }}>
        <SectionHead eyebrow="How it works" title="From a creator's feed to a provable, paid citation." center style={{ marginBottom: 36 }} />
        <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 18 }} className="how-grid">
          <div style={{ position: 'absolute', left: '12%', right: '12%', top: 19, height: 2, background: 'linear-gradient(90deg,var(--earned),var(--buy),var(--skip))', opacity: .55 }} className="how-rail" />
          {HOW.map((s) => (
            <div key={s.n} style={{ position: 'relative', textAlign: 'center', paddingTop: 44 }}>
              <span style={{ position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)', width: 40, height: 40, borderRadius: 99, display: 'grid', placeItems: 'center', background: 'var(--ink)', border: '1px solid var(--earned-line)', color: 'var(--earned2)', fontFamily: 'var(--font-mono)', fontSize: 12, boxShadow: '0 0 0 6px var(--canvas)' }}>{s.n}</span>
              <h4 style={{ fontFamily: 'var(--font-serif)', fontSize: 20, letterSpacing: '-.015em', margin: '0 0 8px' }}>{s.t}</h4>
              <p style={{ color: 'var(--mut)', fontSize: 14, lineHeight: 1.55, margin: '0 auto', maxWidth: 230 }}>{s.d}</p>
            </div>
          ))}
        </div>
      </section>

      <TryItLive />

      {/* 15–30s: WHICH SIDE ARE YOU ON */}
      <section style={{ maxWidth: 1360, margin: '0 auto', padding: '0 26px 56px' }}>
        <SectionHead eyebrow="Two sides of the floor" title="Pick your side." center style={{ marginBottom: 26 }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="doors-grid">
          <Door accent="earn" kicker="Creators · writers · publishers" title="Get paid every time AI cites you." body="List your articles, set a price per citation, and earn whenever an agent grounds an answer in your work. We can set up a wallet for you — no crypto knowledge needed." cta="Start earning" onClick={() => go('creators')} />
          <Door accent="buy" kicker="Operators · research teams" title="Your agent pays sources, by the rules." body="Give your agent a budget and a policy, and let it pay per use — transparently, within limits you set, with a receipt for every citation it makes." cta="Run a paying agent" onClick={() => go('operators')} />
        </div>
      </section>

      {/* 30s+: ACT */}
      <section style={{ maxWidth: 1360, margin: '0 auto', padding: '0 26px 88px' }}>
        <div style={{ borderRadius: 22, background: 'linear-gradient(135deg,var(--cta-bg-1) 0%,var(--cta-bg-2) 100%)', border: '1px solid var(--cta-border)', padding: 'clamp(44px,6vw,72px) clamp(28px,5vw,64px)', textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse 60% 80% at 50% 110%, rgba(84,180,136,.09), transparent 70%)', pointerEvents: 'none' }} />
          <div style={{ position: 'relative' }}>
            <h2 style={{ fontFamily: 'var(--font-serif)', fontSize: 'clamp(34px,5vw,58px)', letterSpacing: '-.04em', margin: '0 0 14px', lineHeight: 1.08 }}>
              One API.<br /><em style={{ fontStyle: 'normal', color: 'var(--earned2)' }}>Every citation paid.</em>
            </h2>
            <p style={{ color: 'var(--mut)', fontSize: 16, maxWidth: 420, margin: '0 auto 32px', lineHeight: 1.55 }}>
              Wires into any LLM pipeline in minutes. Creators list once and earn every time an agent cites their work.
            </p>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <Btn variant="earn" size="lg" onClick={() => go('creators')}>Start earning</Btn>
              <Btn variant="primary" size="lg" onClick={() => go('operators')}>Run a paying agent</Btn>
            </div>
          </div>
        </div>
      </section>

    </div>
  );
}

window.Home = Home;
window.LiveTransactions = LiveTransactions;
