/* eslint-disable */
// Demo logic — sequenced agent run
const { useState, useEffect, useRef, useCallback } = React;

// Demonstration run — fees flow into a tokenized-equity treasury
const DEMO_RUN = {
  vibe: "the fees buy real stocks",
  narrative: "Tokenized-equity treasury — trading fees recycled into S&P holdings",
  name: "VAULT",
  ticker: "VAULT",
  tagline: "The fees buy real stocks.",
  domain: "vault.fund",
  chain: "Solana",
  venue: "Printr",
};

const SUGGESTIONS = [
  "the fees buy real stocks",
  "open-weight models",
  "autonomous companies",
  "embodied agents",
];

// Generate the agent's log lines for a given run
function buildScript(run) {
  return [
    { lvl: "info", body: <><span className="key">agent</span> <span className="muted">·</span> neuron/v0.4.2 initialized</> },
    { lvl: "info", body: <><span className="key">vibe</span> <span className="muted">=</span> <span className="val">"{run.vibe}"</span></> },
    { lvl: "info", body: <>scanning narratives <span className="muted">// momentum · social · onchain</span></> },
    { lvl: "ok",   body: <>narrative: <span className="val">{run.narrative}</span></> },
    { lvl: "info", body: <>generating candidates <span className="muted">·</span> 1,284 names</> },
    { lvl: "ok",   body: <>brand: <span className="val">${run.ticker}</span> <span className="muted">·</span> <span className="key">{run.tagline}</span></> },
    { lvl: "info", body: <>checking domain availability</> },
    { lvl: "ok",   body: <>domain: <span className="val">{run.domain}</span> <span className="muted">· purchased</span></> },
    { lvl: "info", body: <>generating site <span className="muted">·</span> deploying to edge</> },
    { lvl: "ok",   body: <>site live <span className="muted">→</span> https://{run.domain}</> },
    { lvl: "info", body: <>configuring fee router <span className="muted">·</span> 1.5% → treasury</> },
    { lvl: "ok",   body: <>treasury: <span className="val">tokenized S&amp;P basket</span> <span className="muted">via Printr</span></> },
    { lvl: "info", body: <>uploading metadata to IPFS</> },
    { lvl: "ok",   body: <>token deployed <span className="val">${run.ticker}</span> <span className="muted">·</span> 412ms</> },
    { lvl: "ok",   body: <span style={{ color: 'var(--cy-2)' }}>handoff complete <span className="muted">·</span> 00:01:38 elapsed</span> },
  ];
}

// pseudo-timestamps
function ts(i) {
  const m = Math.floor(i / 6).toString().padStart(2, "0");
  const s = ((i * 7) % 60).toString().padStart(2, "0");
  return `00:${m}:${s}`;
}

function LiveDemo() {
  const [input, setInput] = useState("");
  const [phase, setPhase] = useState("idle"); // idle, running, done
  const [run, setRun] = useState(null);
  const [lines, setLines] = useState([]);
  const [stage, setStage] = useState(0); // for artifacts: 0 none, 1 narrative, 2 brand, 3 site, 4 token
  const termRef = useRef(null);
  const tRef = useRef([]);
  const wrapRef = useRef(null);
  const autoStartedRef = useRef(false);

  const stop = useCallback(() => {
    tRef.current.forEach((t) => clearTimeout(t));
    tRef.current = [];
  }, []);

  const start = useCallback((vibeOverride) => {
    stop();
    const vibe = (vibeOverride ?? input).trim();
    if (!vibe) return;
    const matched = { ...DEMO_RUN, vibe };
    setRun(matched);
    setLines([]);
    setStage(0);
    setPhase("running");

    const script = buildScript(matched);

    // append lines on a schedule, advance stages at known indices
    const stageMap = { 3: 1, 5: 2, 9: 3, 12: 4 };
    let acc = 350;
    script.forEach((ln, i) => {
      const delay = acc;
      acc += 520 + (ln.lvl === "ok" ? 280 : 0);
      const t = setTimeout(() => {
        setLines((cur) => [...cur, { ...ln, i }]);
        if (stageMap[i]) setStage(stageMap[i]);
        // autoscroll
        requestAnimationFrame(() => {
          if (termRef.current) termRef.current.scrollTop = termRef.current.scrollHeight;
        });
        if (i === script.length - 1) setPhase("done");
      }, delay);
      tRef.current.push(t);
    });
  }, [input, stop]);

  const reset = () => {
    stop();
    setLines([]);
    setStage(0);
    setRun(null);
    setPhase("idle");
    setInput("");
  };

  useEffect(() => stop, [stop]);

  // auto-start when scrolled into view
  useEffect(() => {
    if (!wrapRef.current || !('IntersectionObserver' in window)) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !autoStartedRef.current) {
          autoStartedRef.current = true;
          const pick = DEMO_RUN.vibe;
          setInput(pick);
          start(pick);
          io.disconnect();
        }
      });
    }, { threshold: 0.35 });
    io.observe(wrapRef.current);
    return () => io.disconnect();
  }, [start]);

  return (
    <div className="demo-grid" ref={wrapRef}>
      <div>
        <div className="run-header">
          <div className="run-header-meta">
            <div className="rh-label">Run input</div>
            <div className="rh-status">
              {phase === 'running' && <><span className="spinner"/><span>Agent working</span></>}
              {phase === 'done' && <><span className="check"/><span>Run complete</span></>}
              {phase === 'idle' && <><span className="dot-idle"/><span>Standby</span></>}
            </div>
          </div>
          <div className="run-header-vibe">
            <span className="rh-glyph">$</span>
            <span className="rh-text">{(run?.vibe || DEMO_RUN.vibe)}</span>
          </div>
          <div className="run-progress-line">
            <div style={{width: `${(stage / 4) * 100}%`}}/>
          </div>
        </div>

        <div className="terminal" style={{ marginTop: 18 }}>
          <div className="term-bar">
            <div className="lights"><span /><span /><span /></div>
            <div className="title mono">neuron — /run/{run ? run.ticker.toLowerCase() : 'live'}</div>
            <div className="stat mono">
              {phase === 'running' && <><span className="spinner" style={{marginRight: 6}}/>RUNNING</>}
              {phase === 'done' && <span style={{color: 'var(--cy-2)'}}>● COMPLETE</span>}
              {phase === 'idle' && <span style={{color: 'var(--fg-faint)'}}>○ STANDBY</span>}
            </div>
          </div>
          <div className="term-body" ref={termRef} style={{maxHeight: 420, overflow: 'auto'}}>
            {lines.length === 0 && (
              <div className="term-line">
                <span className="gutter">›</span>
                <span className="body muted">
                  agent idle<span className="cursor" />
                </span>
              </div>
            )}
            {lines.map((ln, idx) => (
              <div className="term-line" key={idx}>
                <span className="gutter">{ts(ln.i)}</span>
                <span className={`lvl-${ln.lvl}`}>
                  {ln.lvl === 'ok' ? '✓' : ln.lvl === 'warn' ? '!' : ln.lvl === 'err' ? '×' : '›'}
                </span>
                <span className="body">{ln.body}</span>
              </div>
            ))}
            {phase === 'running' && (
              <div className="term-line">
                <span className="gutter">›</span>
                <span className="body"><span className="cursor" /></span>
              </div>
            )}
          </div>
        </div>
      </div>

      <PipelinePanel run={run} stage={stage} phase={phase} />
    </div>
  );
}

function PipelinePanel({ run, stage, phase }) {
  const steps = [
    {
      n: '01',
      label: 'Narrative',
      idx: 1,
      detail: stage >= 1 && run ? run.narrative : 'awaiting input',
    },
    {
      n: '02',
      label: 'Brand',
      idx: 2,
      detail: stage >= 2 && run ? `$${run.ticker} · ${run.name}` : '—',
      sub: stage >= 2 && run ? run.tagline : null,
    },
    {
      n: '03',
      label: 'Website',
      idx: 3,
      detail: stage >= 3 && run ? run.domain : '—',
      sub: stage >= 3 ? 'react · edge · live' : null,
    },
    {
      n: '04',
      label: 'Token',
      idx: 4,
      detail: stage >= 4 && run ? `${run.venue} · 1.5% → S&P` : '—',
      sub: stage >= 4 ? '1,000,000,000 supply · minted' : null,
    },
  ];

  return (
    <aside className="pipeline">
      <div className="pipeline-head">
        <div className="ph-eyebrow">Pipeline</div>
        <div className="ph-status">
          {phase === 'idle' && <><span className="dot-idle"/>standby</>}
          {phase === 'running' && <><span className="spinner"/>working</>}
          {phase === 'done' && <><span className="check"/>complete</>}
        </div>
      </div>
      <div className="pipeline-track">
        {steps.map((s, i) => {
          const state = stage === s.idx ? 'active' : stage > s.idx ? 'done' : 'idle';
          return (
            <div className={`step-row state-${state}`} key={s.n}>
              <div className="step-rail">
                <div className="step-node">
                  {state === 'done' && (
                    <svg className="check-svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="20 6 9 17 4 12"/>
                    </svg>
                  )}
                  {state === 'active' && <span className="spinner"/>}
                  {state === 'idle' && <span className="num">{s.n}</span>}
                </div>
                {i < steps.length - 1 && <div className="step-line"/>}
              </div>
              <div className="step-content">
                <div className="step-top">
                  <span className="step-label">{s.label}</span>
                  <span className="step-meta">{state === 'done' ? 'done' : state === 'active' ? 'in progress' : 'queued'}</span>
                </div>
                <div className="step-detail">{s.detail}</div>
                {s.sub && <div className="step-sub">{s.sub}</div>}
              </div>
            </div>
          );
        })}
      </div>
      {phase === 'done' && run && (
        <div className="pipeline-foot">
          <div className="pf-row"><span>handoff</span><span className="pf-time">00:01:38</span></div>
          <div className="pf-row pf-result">
            <span>${run.ticker} live on Solana</span>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12"/>
            </svg>
          </div>
        </div>
      )}
    </aside>
  );
}

function Artifact({ label, state, rows, preview }) {
  return (
    <div className={`artifact ${state === 'active' ? 'active' : state === 'done' ? 'done' : ''}`}>
      <div className="head">
        <span className="label-wrap"><span className="dot"/>{label}</span>
        <span>
          {state === 'active' && <span className="spinner" />}
          {state === 'done' && <span className="check" />}
        </span>
      </div>
      <div className="body">
        {rows.map(([k, v], i) => (
          <div className="row" key={i}>
            <span className="k">{k}</span>
            <span style={{ textAlign: 'right', maxWidth: '65%', color: 'var(--fg)' }}>{v}</span>
          </div>
        ))}
        {preview}
      </div>
    </div>
  );
}

function SitePreview({ run }) {
  if (!run) return null;
  return (
    <div style={{
      marginTop: 10,
      border: '1px solid var(--hairline-2)',
      borderRadius: 6,
      padding: '14px 14px 16px',
      background: 'var(--bg)',
      fontFamily: 'var(--mono)',
    }}>
      <div style={{display: 'flex', gap: 4, marginBottom: 10, alignItems: 'center'}}>
        <span style={{width: 5, height: 5, borderRadius: '50%', background: 'rgba(255,255,255,0.12)'}} />
        <span style={{width: 5, height: 5, borderRadius: '50%', background: 'rgba(255,255,255,0.12)'}} />
        <span style={{width: 5, height: 5, borderRadius: '50%', background: 'rgba(255,255,255,0.12)'}} />
        <span style={{marginLeft: 'auto', fontSize: 9, color: 'var(--fg-faint)'}}>https://{run.domain}</span>
      </div>
      <div style={{ fontSize: 16, color: 'var(--fg)', letterSpacing: '-0.01em', marginBottom: 4 }}>
        ${run.ticker}
      </div>
      <div style={{ fontSize: 10, color: 'var(--fg-mute)', marginBottom: 8 }}>{run.tagline}</div>
      <div style={{ height: 1, width: '60%', background: 'var(--hairline-3)' }}/>
    </div>
  );
}

window.LiveDemo = LiveDemo;
