// Baked-in DEX panel — swap ETH <-> curve tokens directly from the marketplace.
// Requires a connected Base wallet; quotes come from the live bonding-curve math.

function PedbyDexPanel({ tokens, wallet, onTrade, trades, selectedId, onSelect, activityReady = true }) {
  // graduated tokens keep trading here too — routed to the locked pool on-chain
  const live = tokens;
  const sel = live.find(t => t.id === selectedId) || live[0];
  const [side, setSide] = React.useState('buy');
  const [amt, setAmt] = React.useState(0.05);
  const [flash, setFlash] = React.useState(false);

  if (!sel) return null;

  const held = wallet.holdings[sel.id] || 0;
  const price = PEDBY_CURVE.price(sel.curve);
  const quote = side === 'buy' ? PEDBY_CURVE.buy(sel.curve, amt) : PEDBY_CURVE.sell(sel.curve, Math.min(amt, held));
  const out = side === 'buy' ? quote.tokensOut : quote.ethOut;
  const impact = (PEDBY_CURVE.price(quote.curve) - price) / price * 100;

  const exec = () => {
    const amount = side === 'sell' ? Math.min(amt, held) : amt;
    if (amount <= 0) return;
    onTrade(sel.id, side, amount);
    setFlash(true);
    setTimeout(() => setFlash(false), 700);
  };

  return (
    <div style={{ position: 'sticky', top: 84, display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{
        background: '#fff', border: '1px solid #E6EAE6', borderRadius: 16, padding: 18,
        animation: flash ? `pedby-flash-${side} .7s ease-out` : 'none',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>Swap</div>
          <BaseBadge />
        </div>

        {!wallet.connected ? (
          <div style={{ textAlign: 'center', padding: '18px 0 8px' }}>
            <div style={{ fontSize: 12.5, color: '#6B7570', marginBottom: 14, lineHeight: 1.5 }}>
              Connect your Base wallet to buy and sell directly on the curve.
            </div>
            <Btn kind="primary" style={{ width: '100%', justifyContent: 'center' }} onClick={wallet.connect}>Connect wallet</Btn>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
              <button onClick={() => setSide('buy')} style={dexTab(side === 'buy', '#E7F4EC', '#0F4E27')}>Buy</button>
              <button onClick={() => setSide('sell')} style={dexTab(side === 'sell', '#FBE3E0', '#7A1E15')}>Sell</button>
            </div>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
              <span style={{ fontSize: 11.5, color: '#6B7570' }}>Token</span>
              <select value={sel.id} onChange={e => { onSelect(e.target.value); setAmt(side === 'buy' ? 0.05 : 0); }} style={dexSelect}>
                {live.map(t => <option key={t.id} value={t.id}>${t.ticker} — {t.name}</option>)}
              </select>
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: '#6B7570' }}>
                <span>{side === 'buy' ? 'You pay (ETH)' : `You sell (${sel.ticker})`}</span>
                <span className="sf-num">
                  {side === 'buy' ? `bal ${wallet.eth.toFixed(3)} ETH` : `bal ${Math.round(held).toLocaleString()}`}
                </span>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <input type="number" min="0" step={side === 'buy' ? 0.01 : 1000} value={amt}
                  onChange={e => setAmt(Math.max(0, +e.target.value))} style={{ ...dexInput, flex: 1 }} />
                <button onClick={() => setAmt(side === 'buy' ? Math.max(0, +((wallet.eth - 0.0003).toFixed(4))) : held)} style={dexMaxBtn}>Max</button>
              </div>
            </label>

            <div style={{ border: '1px solid #E6EAE6', borderRadius: 10, padding: 12, marginBottom: 12, fontSize: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                <span style={{ color: '#6B7570' }}>You receive</span>
                <span className="sf-num" style={{ fontWeight: 600 }}>
                  {side === 'buy' ? Math.round(out).toLocaleString() + ' ' + sel.ticker : PEDBY_CURVE.fmtEth(out)}
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                <span style={{ color: '#6B7570' }}>Price impact</span>
                <span className="sf-num" style={{ fontWeight: 600, color: impact >= 0 ? '#0F4E27' : '#7A1E15' }}>{impact >= 0 ? '+' : ''}{impact.toFixed(2)}%</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: '#6B7570' }}>Route</span>
                <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#3B453F' }}>{sel.graduated ? 'locked pool' : 'bonding curve'}</span>
              </div>
            </div>

            <Btn kind={side === 'buy' ? 'primary' : 'dark'} style={{ width: '100%', justifyContent: 'center' }} onClick={exec}>
              {side === 'buy' ? `Buy $${sel.ticker}` : `Sell $${sel.ticker}`}
            </Btn>
          </React.Fragment>
        )}
      </div>

      {/* Recent trades feed */}
      {(trades.length > 0 || !activityReady) && (
        <div style={{ background: '#fff', border: '1px solid #E6EAE6', borderRadius: 16, padding: 16 }}>
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#6B7570', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 10 }}>Recent trades</div>
          {!activityReady && trades.length === 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[80, 62, 71].map((w, i) => (
                <div key={i} style={{ height: 11, width: w + '%', borderRadius: 6, background: '#EFF2EE', animation: `pedby-shimmer 1.3s ease-in-out ${i * 0.18}s infinite` }} />
              ))}
              <div style={{ fontFamily: 'JetBrains Mono', fontSize: 10, color: '#9AA39E', letterSpacing: 0.8, marginTop: 2 }}>SYNCING TRADE HISTORY…</div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              {trades.slice(0, 6).map(tr => {
                const t = tokens.find(tt => tt.id === tr.tokenId);
                if (!t) return null;
                const isBuy = tr.side === 'buy';
                return (
                  <div key={tr.key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5, fontFamily: 'JetBrains Mono' }}>
                    <span style={{ color: isBuy ? '#1E8C45' : '#C0392B', fontWeight: 700, flex: '0 0 52px', whiteSpace: 'nowrap' }}>{isBuy ? '▲ BUY' : '▼ SELL'}</span>
                    <span style={{ color: '#16201A', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>${t.ticker}</span>
                    <span style={{ color: '#9AA39E', marginLeft: 'auto', whiteSpace: 'nowrap' }}>{tr.ethAmt.toFixed(3)} ETH</span>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

const dexTab = (active, bg, fg) => ({
  flex: 1, height: 32, borderRadius: 9, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
  fontSize: 12.5, fontWeight: 700, background: active ? bg : '#EFF2EE', color: active ? fg : '#6B7570',
});

const dexSelect = {
  height: 38, borderRadius: 10, border: '1px solid #E6EAE6', padding: '0 10px',
  fontFamily: 'inherit', fontSize: 13, background: '#fff', color: '#16201A', outline: 'none',
};

const dexInput = {
  height: 38, borderRadius: 10, border: '1px solid #E6EAE6', padding: '0 10px',
  fontSize: 13.5, fontFamily: 'JetBrains Mono', outline: 'none', background: '#fff', minWidth: 0,
};

const dexMaxBtn = {
  height: 38, padding: '0 12px', borderRadius: 10, border: '1px solid #E6EAE6', background: '#EFF2EE',
  fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700, color: '#3B453F', cursor: 'pointer',
};

window.PedbyDexPanel = PedbyDexPanel;
