/* ============================================================
   CADENCE — Trade Panel (3 UX variants: simple | pro | quick)
   window.TradePanel
   ============================================================ */
(function () {
  const { useState, useMemo } = React;
  const I = window.Icon;
  const F = window.CAD.fmt;
  const FEE = 0.009; // 0.9% platform fee

  function useOrder(price, balance, owned, side) {
    const [shares, setShares] = useState(50);
    const cost = +(shares * price).toFixed(2);
    const fee = +(cost * FEE).toFixed(2);
    const total = side === 'buy' ? cost + fee : cost - fee;
    const maxBuy = Math.floor(balance / (price * (1 + FEE)));
    const maxSell = owned;
    const max = side === 'buy' ? maxBuy : maxSell;
    return { shares, setShares, cost, fee, total, max };
  }

  function SummaryRows({ shares, price, fee, total, side, song }) {
    const newOwnPct = (((song.sharesSold + (side === 'buy' ? shares : -shares)) / song.totalShares) * 100);
    return (
      <div style={{ marginTop: 14 }}>
        <div className="summary-row"><span className="k">Shares</span><span className="v">{shares.toLocaleString()}</span></div>
        <div className="summary-row"><span className="k">Price / share</span><span className="v">{F.money(price, 2)}</span></div>
        <div className="summary-row"><span className="k">Platform fee (0.9%)</span><span className="v">{F.money(fee, 2)}</span></div>
        <div className="summary-row total"><span className="k">{side === 'buy' ? 'Total cost' : 'You receive'}</span><span className="v" style={{ color: side === 'buy' ? 'var(--text)' : 'var(--green)' }}>{F.money(total, 2)}</span></div>
        <div className="summary-row" style={{ paddingTop: 10 }}>
          <span className="k">Est. annual yield</span>
          <span className="v pos">≈ {F.money(shares * price * song.yield / 100, 2)}</span>
        </div>
      </div>
    );
  }

  // ---------- SIMPLE ----------
  function SimplePanel({ price, balance, owned, song, onTrade }) {
    const [side, setSide] = useState('buy');
    const o = useOrder(price, balance, owned, side);
    const insufficient = side === 'buy' ? o.total > balance : o.shares > owned;
    const pcts = [0.25, 0.5, 0.75, 1];
    return (
      <div>
        <div className="bs-tabs">
          <button className={'buy' + (side === 'buy' ? ' on' : '')} onClick={() => setSide('buy')}>Buy</button>
          <button className={'sell' + (side === 'sell' ? ' on' : '')} onClick={() => setSide('sell')}>Sell</button>
        </div>

        <div className="field mt16">
          <label>Shares to {side}</label>
          <div className="input">
            <button className="qbtn" style={{ border: 0, background: 'transparent', padding: '0 6px 0 0' }} onClick={() => o.setShares(Math.max(1, o.shares - 10))}><I.minus style={{ width: 16 }} /></button>
            <input type="number" value={o.shares} min="1"
              onChange={(e) => o.setShares(Math.max(0, Math.min(o.max, parseInt(e.target.value || '0'))))} />
            <button className="qbtn" style={{ border: 0, background: 'transparent', padding: '0 0 0 6px' }} onClick={() => o.setShares(Math.min(o.max, o.shares + 10))}><I.plus style={{ width: 16 }} /></button>
          </div>
        </div>

        <div className="stepper" style={{ marginTop: 10, gridTemplateColumns: 'repeat(4,1fr)' }}>
          {pcts.map((p) => (
            <button key={p} className="qbtn" onClick={() => o.setShares(Math.max(1, Math.floor(o.max * p)))}>{p === 1 ? 'Max' : p * 100 + '%'}</button>
          ))}
        </div>

        <SummaryRows shares={o.shares} price={price} fee={o.fee} total={o.total} side={side} song={song} />

        <button className={'btn btn-block btn-lg mt16 ' + (side === 'buy' ? 'btn-buy' : 'btn-sell')}
          disabled={insufficient || o.shares < 1}
          onClick={() => onTrade({ side, shares: o.shares, price, total: o.total })}>
          {insufficient ? (side === 'buy' ? 'Insufficient balance' : 'Not enough shares') : `${side === 'buy' ? 'Buy' : 'Sell'} ${o.shares} shares`}
        </button>
        <div className="row between mt12" style={{ fontSize: 12 }}>
          <span className="muted">Buying power</span><span className="num dim">{F.money(balance, 2)}</span>
        </div>
      </div>
    );
  }

  // ---------- PRO (order ticket) ----------
  function ProPanel({ price, balance, owned, song, onTrade }) {
    const [side, setSide] = useState('buy');
    const [ordType, setOrdType] = useState('market');
    const o = useOrder(price, balance, owned, side);
    const pct = o.max > 0 ? Math.min(100, Math.round((o.shares / o.max) * 100)) : 0;
    const insufficient = side === 'buy' ? o.total > balance : o.shares > owned;
    // synthetic order book
    const book = useMemo(() => {
      const asks = [], bids = [];
      for (let i = 1; i <= 4; i++) { asks.push({ p: +(price + i * 0.04).toFixed(2), q: 40 + i * 55 }); bids.push({ p: +(price - i * 0.04).toFixed(2), q: 60 + i * 40 }); }
      return { asks: asks.reverse(), bids };
    }, [price]);
    const maxQ = Math.max(...book.asks.map(a => a.q), ...book.bids.map(b => b.q));

    return (
      <div>
        <div className="row between" style={{ marginBottom: 12 }}>
          <div className="bs-tabs" style={{ flex: 1 }}>
            <button className={'buy' + (side === 'buy' ? ' on' : '')} onClick={() => setSide('buy')}>Buy</button>
            <button className={'sell' + (side === 'sell' ? ' on' : '')} onClick={() => setSide('sell')}>Sell</button>
          </div>
        </div>
        <div className="seg" style={{ width: '100%', marginBottom: 14 }}>
          {['market', 'limit'].map((t) => (
            <button key={t} className={ordType === t ? 'on' : ''} style={{ flex: 1, textTransform: 'capitalize' }} onClick={() => setOrdType(t)}>{t}</button>
          ))}
        </div>

        {/* mini order book */}
        <div style={{ marginBottom: 14 }}>
          <div className="row between" style={{ fontSize: 10.5, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700, marginBottom: 6 }}>
            <span>Price</span><span>Size</span>
          </div>
          {book.asks.map((a, i) => (
            <div key={'a' + i} style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '3px 6px' }}>
              <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: (a.q / maxQ * 100) + '%', background: 'var(--red-tint)', borderRadius: 4 }} />
              <span className="num neg" style={{ position: 'relative' }}>{a.p.toFixed(2)}</span><span className="num dim" style={{ position: 'relative' }}>{a.q}</span>
            </div>
          ))}
          <div className="num" style={{ textAlign: 'center', fontSize: 15, fontWeight: 700, padding: '6px 0', color: song.change >= 0 ? 'var(--green)' : 'var(--red)' }}>{F.money(price, 2)}</div>
          {book.bids.map((b, i) => (
            <div key={'b' + i} style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '3px 6px' }}>
              <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: (b.q / maxQ * 100) + '%', background: 'var(--green-tint)', borderRadius: 4 }} />
              <span className="num pos" style={{ position: 'relative' }}>{b.p.toFixed(2)}</span><span className="num dim" style={{ position: 'relative' }}>{b.q}</span>
            </div>
          ))}
        </div>

        <div className="field">
          <label>Quantity (shares)</label>
          <div className="input"><input type="number" value={o.shares} onChange={(e) => o.setShares(Math.max(0, Math.min(o.max, parseInt(e.target.value || '0'))))} /><span className="suf">sh</span></div>
        </div>
        {ordType === 'limit' && (
          <div className="field mt12">
            <label>Limit price</label>
            <div className="input"><span className="pre">$</span><input type="number" defaultValue={price.toFixed(2)} step="0.01" /></div>
          </div>
        )}

        <div style={{ marginTop: 16 }}>
          <div className="row between" style={{ fontSize: 12, marginBottom: 8 }}><span className="muted">{side === 'buy' ? 'Buying power used' : 'Position sold'}</span><span className="num dim">{pct}%</span></div>
          <input type="range" className={'rng' + (side === 'buy' ? '' : '')} min="0" max="100" value={pct}
            onChange={(e) => o.setShares(Math.max(0, Math.floor(o.max * (e.target.value / 100))))} />
          <div className="row between" style={{ fontSize: 10.5, color: 'var(--text-faint)', marginTop: 4 }}><span>0</span><span>25</span><span>50</span><span>75</span><span>Max</span></div>
        </div>

        <SummaryRows shares={o.shares} price={price} fee={o.fee} total={o.total} side={side} song={song} />

        <button className={'btn btn-block btn-lg mt16 ' + (side === 'buy' ? 'btn-buy' : 'btn-sell')}
          disabled={insufficient || o.shares < 1}
          onClick={() => onTrade({ side, shares: o.shares, price, total: o.total })}>
          {insufficient ? (side === 'buy' ? 'Insufficient balance' : 'Not enough shares') : `Place ${ordType} ${side} · ${F.money(o.total, 2)}`}
        </button>
      </div>
    );
  }

  // ---------- QUICK INVEST ----------
  function QuickPanel({ price, balance, owned, song, onTrade }) {
    const [amount, setAmount] = useState(100);
    const shares = Math.floor(amount / (price * (1 + FEE)));
    const realCost = +(shares * price * (1 + FEE)).toFixed(2);
    const ownPct = ((shares / song.totalShares) * 100);
    const insufficient = realCost > balance;
    const presets = [50, 100, 250, 500];
    const yearly = shares * price * song.yield / 100;
    return (
      <div>
        <div style={{ textAlign: 'center', padding: '6px 0 4px' }}>
          <div className="muted" style={{ fontSize: 12 }}>I want to invest</div>
          <div className="num" style={{ fontSize: 44, fontWeight: 700, letterSpacing: '-0.04em', marginTop: 4 }}>{F.money(amount, 0)}</div>
          <div className="dim" style={{ fontSize: 13, marginTop: 2 }}>≈ <b className="num">{shares.toLocaleString()}</b> shares of {song.title}</div>
        </div>

        <input type="range" className="rng green mt16" min="10" max={Math.max(50, Math.floor(balance))} step="10" value={amount}
          onChange={(e) => setAmount(parseInt(e.target.value))} />

        <div className="stepper mt16" style={{ gridTemplateColumns: 'repeat(4,1fr)' }}>
          {presets.map((p) => (
            <button key={p} className="qbtn" style={amount === p ? { background: 'var(--green-tint)', color: 'var(--green-bright)', borderColor: 'transparent' } : null} onClick={() => setAmount(Math.min(p, Math.floor(balance)))}>${p}</button>
          ))}
        </div>

        <div className="panel mt20" style={{ background: 'var(--surface-2)', borderColor: 'var(--border-soft)' }}>
          <div style={{ padding: 14 }}>
            <div className="summary-row"><span className="k">You'll own</span><span className="v">{ownPct.toFixed(3)}% of this song</span></div>
            <div className="summary-row"><span className="k">Projected yield / yr</span><span className="v pos">+{F.money(yearly, 2)}</span></div>
            <div className="summary-row"><span className="k">Avg. holder return</span><span className="v pos">{song.yield}%</span></div>
          </div>
        </div>

        <button className="btn btn-buy btn-block btn-lg mt20" disabled={insufficient || shares < 1}
          onClick={() => onTrade({ side: 'buy', shares, price, total: realCost })}>
          <I.bolt style={{ width: 16 }} />{insufficient ? 'Insufficient balance' : `Invest ${F.money(realCost, 2)} now`}
        </button>
        <div className="row between mt12" style={{ fontSize: 12 }}>
          <span className="muted">Balance</span><span className="num dim">{F.money(balance, 2)}</span>
        </div>
        <div className="row gap6 mt12" style={{ justifyContent: 'center', fontSize: 12 }}>
          <span className="muted">Hold shares already?</span>
          <a style={{ color: 'var(--red-bright)', cursor: 'pointer', fontWeight: 600 }} onClick={() => owned > 0 ? onTrade({ side: 'sell', shares: Math.min(owned, shares || 10), price, total: +(Math.min(owned, shares || 10) * price * (1 - FEE)).toFixed(2) }) : window.toast({ kind: 'sell', title: 'No position', desc: 'You don’t own shares of this song yet.' })}>Sell</a>
        </div>
      </div>
    );
  }

  function TradePanel({ variant, ...props }) {
    if (variant === 'pro') return <ProPanel {...props} />;
    if (variant === 'quick') return <QuickPanel {...props} />;
    return <SimplePanel {...props} />;
  }

  window.TradePanel = TradePanel;
})();
