/* Verdict in Action — interactive scenario stepper */

const { useState, useEffect, useRef } = React;

const SCENARIO = {
  customer: "Margaret Chen, age 67",
  rep: "Daniel R., wealth advisor",
  asked: "Can I add my daughter as a beneficiary on my inherited Roth IRA — and still take the same RMDs I'm taking now?",
  channel: "Inbound · 3:14 PM ET",
};

const STEPS = [
  { id: 0, t: "00.0s", label: "Question received" },
  { id: 1, t: "00.4s", label: "Reading corpus" },
  { id: 2, t: "02.1s", label: "Citing sources" },
  { id: 3, t: "04.7s", label: "Decision rendered" },
  { id: 4, t: "—",     label: "Audit log written" },
];

function StepReceived() {
  return (
    <div style={{display:'flex', flexDirection:'column', gap:18}}>
      <div className="kicker">Inbound · {SCENARIO.channel}</div>
      <div style={{display:'grid', gridTemplateColumns:'140px 1fr', gap:14, fontSize:14, color:'var(--ink-soft)'}}>
        <div style={{color:'var(--ink-mute)'}}>Customer</div><div>{SCENARIO.customer}</div>
        <div style={{color:'var(--ink-mute)'}}>Advisor</div><div>{SCENARIO.rep}</div>
        <div style={{color:'var(--ink-mute)'}}>Account type</div><div>Inherited Roth IRA · DOD 2023-08-12</div>
      </div>
      <div style={{borderTop:'1px solid var(--rule)', paddingTop:18, marginTop:6}}>
        <div className="kicker" style={{marginBottom:10}}>Customer asked</div>
        <div style={{fontFamily:'var(--serif)', fontSize:'clamp(22px, 2.6vw, 30px)', lineHeight:1.25}}>
          "{SCENARIO.asked}"
        </div>
      </div>
      <div style={{display:'flex', gap:10, marginTop:8}}>
        <span className="tag">Routing matrix loaded</span>
        <span className="tag">Account context attached</span>
      </div>
    </div>
  );
}

function StepReading() {
  const corpus = [
    { name: "Compliance Manual §4.3 — Beneficiary designations", state: "match" },
    { name: "FINRA Rule 4512 — Customer account information", state: "match" },
    { name: "IRS Pub. 590-B — Distributions from IRAs", state: "match" },
    { name: "SECURE Act 2.0 — Inherited account rules", state: "scan" },
    { name: "Firm SOP — Form ADV-2B notarization workflow", state: "match" },
    { name: "Compliance Manual §11 — Discretionary advice", state: "skip" },
  ];
  return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      <div className="kicker">Hybrid retrieval · 142,318 passages indexed</div>
      <div style={{display:'flex', flexDirection:'column', gap:6, marginTop:8}}>
        {corpus.map((c, i) => (
          <div key={i} style={{
            display:'grid', gridTemplateColumns:'1fr 90px',
            padding:'12px 14px',
            border:'1px solid var(--rule)',
            background: c.state === 'match' ? 'rgba(107,31,44,0.06)' : 'transparent',
            fontSize:14,
            alignItems:'center'
          }}>
            <div style={{color: c.state==='skip' ? 'var(--ink-fade)' : 'var(--ink)'}}>{c.name}</div>
            <div style={{
              fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.12em', textTransform:'uppercase',
              textAlign:'right',
              color: c.state==='match' ? '#c98a96' : c.state==='scan' ? 'var(--ink-soft)' : 'var(--ink-fade)'
            }}>
              {c.state === 'match' ? '● cited' : c.state === 'scan' ? '○ scanned' : '— skipped'}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function StepCiting() {
  const cites = [
    { ref: "Compliance Manual §4.3", quote: "Beneficiary additions on inherited retirement accounts require Form ADV-2B with notarized signature.", page: "p. 47" },
    { ref: "FINRA Rule 4512(a)(1)", quote: "For each account, the member must maintain the name of the beneficiary, if applicable, and update on customer request.", page: "Reg." },
    { ref: "IRS Pub. 590-B (2024)", quote: "An inherited Roth IRA cannot be combined with the beneficiary's own Roth IRA. RMD schedule is set at the original owner's death.", page: "Ch. 1" },
  ];
  return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      <div className="kicker">3 sources · highest-relevance passages</div>
      {cites.map((c, i) => (
        <div key={i} style={{borderLeft:'2px solid var(--accent)', padding:'12px 0 12px 18px'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:12}}>
            <div style={{fontFamily:'var(--mono)', fontSize:12, color:'var(--ink-soft)', letterSpacing:'0.04em'}}>{c.ref}</div>
            <div style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-mute)'}}>{c.page}</div>
          </div>
          <div style={{fontFamily:'var(--serif)', fontStyle:'italic', fontSize:17, marginTop:8, color:'var(--ink)', lineHeight:1.4}}>
            "{c.quote}"
          </div>
        </div>
      ))}
    </div>
  );
}

function StepDecision() {
  return (
    <div style={{display:'flex', flexDirection:'column', gap:18}}>
      <div style={{display:'flex', alignItems:'center', gap:12}}>
        <span style={{
          fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.14em', textTransform:'uppercase',
          padding:'5px 10px', background:'var(--accent)', color:'var(--ink)'
        }}>Handle here</span>
        <span className="kicker">Confidence 0.94 · Cited 3/3</span>
      </div>
      <div style={{fontFamily:'var(--serif)', fontSize:'clamp(22px, 2.4vw, 28px)', lineHeight:1.3}}>
        Yes — Margaret can add her daughter. Use the script. Then send Form ADV-2B for notarization.
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr', gap:14, marginTop:6}}>
        <div style={{border:'1px solid var(--rule)', padding:18}}>
          <div className="kicker" style={{marginBottom:10}}>Say this</div>
          <div style={{fontFamily:'var(--serif)', fontStyle:'italic', fontSize:16, color:'var(--ink)', lineHeight:1.5}}>
            "Yes, Margaret — adding your daughter as a beneficiary on the inherited Roth is straightforward. I'll send Form ADV-2B to your portal. It needs a notarized signature, but your bank or our local office can handle that. Your RMD schedule won't change — those are still set from your husband's date of death."
          </div>
        </div>
        <div style={{border:'1px solid var(--rule)', padding:18, background:'#0d0d0d'}}>
          <div className="kicker" style={{marginBottom:10, color:'#c98a96'}}>Do not say</div>
          <ul style={{margin:0, paddingLeft:18, color:'var(--ink-soft)', fontSize:14, lineHeight:1.7}}>
            <li>"You can roll this into your own Roth." — <span style={{color:'var(--ink-mute)'}}>Inherited Roths can't be combined.</span></li>
            <li>"Your RMDs will reset." — <span style={{color:'var(--ink-mute)'}}>The schedule is fixed at original owner's DOD.</span></li>
            <li>"You don't need anything notarized." — <span style={{color:'var(--ink-mute)'}}>§4.3 requires notarization.</span></li>
          </ul>
        </div>
        <div style={{border:'1px solid var(--rule)', padding:18}}>
          <div className="kicker" style={{marginBottom:10}}>Steps</div>
          <ol style={{margin:0, paddingLeft:20, color:'var(--ink-soft)', fontSize:14, lineHeight:1.8}}>
            <li>Verify Margaret's identity using the standard 4512 challenge.</li>
            <li>Send <span style={{color:'var(--ink)'}}>Form ADV-2B</span> to her client portal.</li>
            <li>Schedule a follow-up in 7 days if the form hasn't been returned notarized.</li>
            <li>Log the conversation under <span style={{color:'var(--ink)'}}>account #IRA-447-219</span>.</li>
          </ol>
        </div>
      </div>
    </div>
  );
}

function StepAudit() {
  return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      <div className="kicker">Decision log · written to compliance archive</div>
      <pre style={{
        fontFamily:'var(--mono)', fontSize:12, color:'var(--ink-soft)',
        background:'#0a0a0a', border:'1px solid var(--rule)', padding:18, margin:0,
        whiteSpace:'pre-wrap', lineHeight:1.7
      }}>{`{
  "id":            "vd-2026-04-30-A4F71",
  "advisor":       "drosenberg@firm.com",
  "customer_id":   "IRA-447-219",
  "asked_at":      "2026-04-30T15:14:08-04:00",
  "decided_at":    "2026-04-30T15:14:13-04:00",
  "elapsed_ms":    4731,
  "decision":      "HANDLE_HERE",
  "confidence":    0.94,
  "citations":     [
    "compliance-manual:§4.3#p47",
    "finra:rule-4512(a)(1)",
    "irs:pub-590B:2024:ch1"
  ],
  "form_dispatched": "ADV-2B",
  "follow_up":     "T+7d",
  "advisor_action_taken": "true",
  "regulatory_relevance": ["FINRA","SEC","IRC-408A"]
}`}</pre>
      <div style={{display:'flex', gap:10, flexWrap:'wrap'}}>
        <span className="tag">WORM-stored</span>
        <span className="tag">Replayable for exam</span>
        <span className="tag">PII-redacted export ready</span>
      </div>
    </div>
  );
}

function VerdictDemo() {
  const [step, setStep] = useState(0);
  const [autoplay, setAutoplay] = useState(false);
  const timer = useRef(null);

  useEffect(() => {
    if (!autoplay) return;
    timer.current = setTimeout(() => {
      setStep(s => s < STEPS.length - 1 ? s + 1 : (setAutoplay(false), s));
    }, 1900);
    return () => clearTimeout(timer.current);
  }, [step, autoplay]);

  const view = [<StepReceived />, <StepReading />, <StepCiting />, <StepDecision />, <StepAudit />][step];
  const pct = ((step) / (STEPS.length - 1)) * 100;

  return (
    <div className="console-shell">
      <div className="console-bar">
        <div className="left">
          <div className="lights"><span/><span/><span/></div>
          <span>verdict console · v0.4.2</span>
        </div>
        <div className="right"><span className="live">● live</span> &nbsp;corpus: firm-wealth-2026 · 2,184 docs</div>
      </div>
      <div className="console-body">
        <aside className="console-side">
          <div className="label">Decision timeline</div>
          <ol className="timeline">
            {STEPS.map((s, i) => (
              <li key={s.id}
                  className={i === step ? 'active' : i < step ? 'done' : ''}
                  onClick={() => { setAutoplay(false); setStep(i); }}>
                <span className="step-dot">{i < step ? '✓' : i + 1}</span>
                <span style={{display:'flex', flexDirection:'column', gap:2}}>
                  <span>{s.label}</span>
                  <span style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--ink-mute)'}}>{s.t}</span>
                </span>
              </li>
            ))}
          </ol>

          <div style={{marginTop:32, paddingTop:20, borderTop:'1px solid var(--rule)'}}>
            <div className="label">Total time</div>
            <div style={{fontFamily:'var(--serif)', fontSize:36, marginTop:6}}>
              {step >= 3 ? '4.7s' : step === 2 ? '2.1s' : step === 1 ? '0.4s' : '—'}
            </div>
            <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--ink-mute)', letterSpacing:'.1em', textTransform:'uppercase', marginTop:4}}>
              question → cited decision
            </div>
          </div>
        </aside>

        <div className="console-main">
          <div key={step} style={{animation:'fadein .35s ease'}}>
            {view}
          </div>
          <div className="console-controls">
            <button className="icon-btn" onClick={() => { setAutoplay(false); setStep(s => Math.max(0, s-1)); }} disabled={step === 0} aria-label="Previous">←</button>
            <div className="progress"><span style={{width: pct + '%'}}/></div>
            <button className="icon-btn" onClick={() => { setAutoplay(false); setStep(s => Math.min(STEPS.length-1, s+1)); }} disabled={step === STEPS.length-1} aria-label="Next">→</button>
            <button className="icon-btn" onClick={() => { if (step === STEPS.length - 1) setStep(0); setAutoplay(a => !a); }} aria-label={autoplay ? 'Pause' : 'Play'}>{autoplay ? '❚❚' : '▶'}</button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes fadein { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
      `}</style>
    </div>
  );
}

const mount = document.getElementById('verdict-demo');
if (mount) ReactDOM.createRoot(mount).render(<VerdictDemo />);
