// Multi-leg builder wizard (4 steps)
const { useState: useStateB } = React;

function Builder({ initial, onClose, onPlace }) {
  const VD = window.VD;
  const { Icon, ICONS, AssetGlyph } = window.VDIcons;
  const { PayoffDiagram, ProbBar } = window.VDChart;

  const [step, setStep] = useStateB(initial?.strategy ? 1 : 0);
  const [stratId, setStratId] = useStateB(initial?.strategy || 'long');
  const [sym, setSym] = useStateB(initial?.sym || 'BTC');
  const [expiryKey, setExpiryKey] = useStateB('fri');
  const [legs, setLegs] = useStateB([]);
  const [placing, setPlacing] = useStateB(false);
  const [success, setSuccess] = useStateB(false);

  const strat = VD.VD_STRATEGIES.find(s => s.id === stratId);
  const asset = VD.VD_ASSETS.find(a => a.sym === sym);
  const chain = VD.vdBuildChain(sym, expiryKey);

  const next = () => setStep(Math.min(4, step + 1));
  const prev = () => setStep(Math.max(0, step - 1));

  const toggleStrike = (row, side) => {
    const idx = legs.findIndex(l => l.strike === row.strike && l.side === side);
    if (idx >= 0) { setLegs(legs.filter((_, i) => i !== idx)); return; }
    const price = side === 'YES' ? row.yAsk : row.nAsk;
    setLegs([...legs, { strike: row.strike, side, price, qty: 10 }]);
  };

  const place = () => {
    setPlacing(true);
    setTimeout(() => { setSuccess(true); setTimeout(onPlace, 900); }, 380);
  };

  return (
    <div className="vd-backdrop" onClick={onClose}>
      <div className="vd-card-rise" onClick={(e) => e.stopPropagation()} style={{
        width: 720, maxHeight: '88vh', overflow: 'hidden',
        background: 'var(--bg-elev)', border: '1px solid var(--line)', borderRadius: 'var(--r-xl)',
        display: 'flex', flexDirection: 'column'
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 20px', borderBottom: '1px solid var(--line-subtle)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="cap-sm" style={{ color: 'var(--mint)' }}>Builder</span>
            <span style={{ fontWeight: 600, fontSize: 14 }}>{strat.name}</span>
            <span className="chip">{strat.tag}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <Steps step={step} />
            <button className="btn-ghost btn" style={{ width: 32, height: 32, padding: 0 }} onClick={onClose}>{ICONS.close}</button>
          </div>
        </div>

        <div style={{ overflow: 'auto', padding: 20, flex: 1, position: 'relative' }}>
          {step === 0 && (
            <Pane title="Pick a strategy" sub="What outcome shape are you building toward?">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                {VD.VD_STRATEGIES.map(s => (
                  <button key={s.id} onClick={() => setStratId(s.id)} className="lift" style={{
                    textAlign: 'left', padding: 14, borderRadius: 10,
                    background: stratId === s.id ? 'var(--bg-elev-3)' : 'var(--bg-elev-2)',
                    border: `1px solid ${stratId === s.id ? 'rgba(151,252,228,0.4)' : 'var(--line-subtle)'}`
                  }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{s.name}</div>
                    <div className="cap-sm" style={{ marginTop: 4, color: 'var(--text-3)' }}>{s.tag}</div>
                  </button>
                ))}
              </div>
            </Pane>
          )}

          {step === 1 && (
            <Pane title="Pick an asset" sub="What underlying are you trading the outcome of?">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                {VD.VD_ASSETS.map(a => (
                  <button key={a.sym} onClick={() => setSym(a.sym)} className="lift" style={{
                    display: 'flex', gap: 12, alignItems: 'center', padding: 14, borderRadius: 10,
                    background: sym === a.sym ? 'var(--bg-elev-3)' : 'var(--bg-elev-2)',
                    border: `1px solid ${sym === a.sym ? 'rgba(151,252,228,0.4)' : 'var(--line-subtle)'}`
                  }}>
                    <AssetGlyph sym={a.sym} size={32} />
                    <div style={{ textAlign: 'left' }}>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{a.sym}</div>
                      <div className="num" style={{ color: 'var(--text-3)', fontSize: 11 }}>${a.spot.toLocaleString()}</div>
                    </div>
                  </button>
                ))}
              </div>
            </Pane>
          )}

          {step === 2 && (
            <Pane title="Pick an expiry" sub="When does this resolve?">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                {VD.VD_EXPIRIES.map(e => (
                  <button key={e.key} onClick={() => setExpiryKey(e.key)} className="lift" style={{
                    display: 'flex', flexDirection: 'column', gap: 4, padding: 14, borderRadius: 10, alignItems: 'flex-start',
                    background: expiryKey === e.key ? 'var(--bg-elev-3)' : 'var(--bg-elev-2)',
                    border: `1px solid ${expiryKey === e.key ? 'rgba(151,252,228,0.4)' : 'var(--line-subtle)'}`
                  }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{e.label}</div>
                    <div className="cap-sm" style={{ color: 'var(--text-3)' }}>{e.sub}</div>
                  </button>
                ))}
              </div>
            </Pane>
          )}

          {step === 3 && (
            <Pane title={`Pick strike${strat.legs > 1 ? 's' : ''}`} sub={strat.legs > 1 ? `Two legs needed for ${strat.name}.` : 'Single leg.'}>
              <div style={{ background: 'var(--bg-elev-2)', borderRadius: 10, border: '1px solid var(--line-subtle)', overflow: 'hidden' }}>
                <div className="cap" style={{ display: 'grid', gridTemplateColumns: '120px 1fr 80px 80px 80px', padding: '10px 14px', borderBottom: '1px solid var(--line-subtle)', gap: 8 }}>
                  <div>Strike</div><div>Implied probability</div><div style={{textAlign:'center'}}>YES</div><div style={{textAlign:'center'}}>NO</div><div style={{textAlign:'right'}}>Vol</div>
                </div>
                {chain.map(r => {
                  const yPicked = legs.some(l => l.strike === r.strike && l.side === 'YES');
                  const nPicked = legs.some(l => l.strike === r.strike && l.side === 'NO');
                  return (
                    <div key={r.strike} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 80px 80px 80px', padding: '8px 14px', alignItems: 'center', gap: 8, borderBottom: '1px solid var(--line-subtle)', background: r.atm ? 'rgba(151,252,228,0.04)' : 'transparent' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span className="num" style={{ fontSize: 13, fontWeight: 600 }}>{r.strike >= 1000 ? r.strike.toLocaleString() : r.strike}</span>
                        {r.atm && <span style={{ color: 'var(--mint)', fontSize: 8 }}>● spot</span>}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <ProbBar pct={r.probYes} w={120} />
                        <span className="num" style={{ fontSize: 11, color: 'var(--text-3)' }}>{Math.round(r.probYes * 100)}%</span>
                      </div>
                      <button onClick={() => toggleStrike(r, 'YES')} style={{
                        height: 28, borderRadius: 6, fontSize: 12, fontWeight: 600,
                        background: yPicked ? 'var(--mint-bg20)' : 'var(--bg-elev-3)',
                        border: `1px solid ${yPicked ? 'rgba(151,252,228,0.4)' : 'var(--line-subtle)'}`,
                        color: yPicked ? 'var(--mint)' : 'var(--text-2)',
                        fontFamily: 'Geist Mono, monospace',
                      }}>{r.yAsk}¢</button>
                      <button onClick={() => toggleStrike(r, 'NO')} style={{
                        height: 28, borderRadius: 6, fontSize: 12, fontWeight: 600,
                        background: nPicked ? 'var(--coral-bg20)' : 'var(--bg-elev-3)',
                        border: `1px solid ${nPicked ? 'rgba(237,112,136,0.4)' : 'var(--line-subtle)'}`,
                        color: nPicked ? 'var(--coral)' : 'var(--text-2)',
                        fontFamily: 'Geist Mono, monospace',
                      }}>{r.nAsk}¢</button>
                      <div className="num" style={{ textAlign: 'right', color: 'var(--text-3)', fontSize: 11 }}>{(r.vol/1000).toFixed(1)}K</div>
                    </div>
                  );
                })}
              </div>
              {legs.length > 0 && (
                <div style={{ marginTop: 12, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {legs.map((l, i) => (
                    <span key={i} className="chip is-active" style={{ height: 30 }}>
                      {l.side} {l.strike >= 1000 ? l.strike.toLocaleString() : l.strike} @ {l.price}¢
                      <button onClick={() => setLegs(legs.filter((_, j) => j !== i))} style={{ marginLeft: 4, color: 'var(--text-3)', display:'inline-flex' }}>{ICONS.close}</button>
                    </span>
                  ))}
                </div>
              )}
            </Pane>
          )}

          {step === 4 && (
            <Pane title="Review" sub="Confirm the strategy before placing.">
              <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 16 }}>
                <div style={{ background: 'var(--bg-elev-2)', borderRadius: 10, border: '1px solid var(--line-subtle)', padding: 14 }}>
                  <div className="cap-sm" style={{ marginBottom: 8 }}>Payoff at expiry</div>
                  {legs.length > 0
                    ? <PayoffDiagram legs={legs} spot={asset.spot} width={400} height={210} />
                    : <div style={{ color: 'var(--text-3)', fontSize: 12, padding: 24, textAlign:'center' }}>Pick at least one leg</div>}
                </div>
                <div style={{ display: 'grid', gap: 10 }}>
                  <Stat k="Strategy"   v={strat.name} />
                  <Stat k="Asset"      v={`${sym} · $${asset.spot.toLocaleString()}`} />
                  <Stat k="Expiry"     v={VD.VD_EXPIRIES.find(e => e.key === expiryKey).label} />
                  <Stat k="Legs"       v={legs.length} />
                  <Stat k="Total cost" v={`$${legs.reduce((s, l) => s + (l.price/100) * l.qty, 0).toFixed(2)}`} />
                  <Stat k="Max gain"   v={`+$${legs.length ? Math.max(...sampleP(legs, asset.spot)).toFixed(2) : '—'}`} c="var(--mint)" />
                  <Stat k="Max loss"   v={`-$${legs.length ? Math.abs(Math.min(...sampleP(legs, asset.spot))).toFixed(2) : '—'}`} c="var(--coral)" />
                </div>
              </div>
            </Pane>
          )}

          {success && (
            <div style={{ position: 'absolute', inset: 0, background: 'rgba(11,20,22,0.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 14, animation: 'vd-fade 200ms var(--ease)' }}>
              <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--mint-bg20)', border: '1px solid var(--mint)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--mint)', animation: 'vd-rise 320ms var(--spring)' }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5 10 17.5 19 7" /></svg>
              </div>
              <div style={{ fontWeight: 600 }}>Strategy placed</div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '14px 20px', borderTop: '1px solid var(--line-subtle)', background: 'var(--bg-elev)' }}>
          <button onClick={prev} disabled={step === 0} className="btn" style={{ opacity: step === 0 ? 0.4 : 1 }}>{ICONS.back} Back</button>
          {step < 4
            ? <button onClick={next} disabled={step === 3 && legs.length === 0} className="btn btn-primary">Next {ICONS.next}</button>
            : <button onClick={place} disabled={legs.length === 0 || placing} className="btn btn-primary btn-lg">{placing ? 'Placing…' : 'Place strategy'}</button>}
        </div>
      </div>
    </div>
  );
}

function sampleP(legs, spot) {
  const lo = Math.min(...legs.map(l => l.strike), spot) * 0.92;
  const hi = Math.max(...legs.map(l => l.strike), spot) * 1.08;
  const out = [];
  for (let i = 0; i < 60; i++) {
    const p = lo + (hi - lo) * i / 59;
    out.push(legs.reduce((acc, l) => {
      const won = l.side === 'YES' ? p > l.strike : p <= l.strike;
      return acc + ((won ? 1 : 0) - l.price/100) * l.qty;
    }, 0));
  }
  return out;
}

function Steps({ step }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      {[0,1,2,3,4].map(i => (
        <div key={i} style={{
          width: i === step ? 22 : 6, height: 6, borderRadius: 999,
          background: i <= step ? 'var(--mint)' : 'var(--line)',
          transition: 'width 320ms var(--ease), background 320ms var(--ease)'
        }} />
      ))}
    </div>
  );
}

function Pane({ title, sub, children }) {
  return (
    <div style={{ animation: 'vd-fade 200ms var(--ease)' }}>
      <div style={{ marginBottom: 16 }}>
        <h2 className="h2" style={{ marginBottom: 4 }}>{title}</h2>
        <div style={{ color: 'var(--text-3)', fontSize: 12 }}>{sub}</div>
      </div>
      {children}
    </div>
  );
}

function Stat({ k, v, c }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 12px', background: 'var(--bg-elev-2)', borderRadius: 8, border: '1px solid var(--line-subtle)' }}>
      <span style={{ color: 'var(--text-3)', fontSize: 12 }}>{k}</span>
      <span className="num" style={{ color: c || 'var(--text)', fontSize: 13, fontWeight: 600 }}>{v}</span>
    </div>
  );
}

window.VDBuilder = { Builder };
