// Invest (buy units) + Withdraw (sell units) modals — wired to real backend.

function InvestModal({ bot, onClose, user }) {
  const [dash] = useApi('/api/dashboard/user');
  const cash = dash?.cash_balance ?? 0;
  const [amount, setAmount] = React.useState(Math.min(10, cash));
  const [step, setStep] = React.useState(0);
  const [busy, setBusy] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  React.useEffect(() => { if (cash > 0 && amount === 0) setAmount(Math.min(10, cash)); }, [cash]);
  const presets = [10, 50, 100, 500].filter(p => p <= cash);
  const units = bot.unit_price ? amount / bot.unit_price : 0;
  const insufficient = amount > cash;

  const submit = async () => {
    setBusy(true); setError(null);
    try {
      const r = await api.post('/api/transactions/buy', { bot_id: bot.id, amount });
      setResult(r); setStep(1);
    } catch (e) { setError(e.detail || e.message); }
    setBusy(false);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-hd">
          <div className="row gap-12">
            <div className="bot-emblem" style={{ background: colorFor(bot.id), width: 36, height: 36, fontSize: 14 }}>{emojiFor(bot.risk_category)}</div>
            <div>
              <div className="tiny muted">Buy units in</div>
              <strong>{bot.name}</strong>
            </div>
          </div>
          <button className="modal-x" onClick={onClose}><IconX size={14}/></button>
        </div>
        <div className="modal-bd">
          {step === 0 ? (
            <>
              <div className="field">
                <label className="field-label">Amount to invest (USDT)</label>
                <input className="input" style={{ fontSize: 22, fontWeight: 700, fontFamily: 'var(--font-num)', padding: '18px 16px' }}
                  value={'$ ' + amount.toLocaleString('en-US')}
                  onChange={(e) => setAmount(Number(e.target.value.replace(/[^0-9.]/g, '')) || 0)}/>
                <div className="field-hint">Available cash: <strong className="num">{USD(cash)}</strong>{cash === 0 ? ' — deposit first' : ''}</div>
              </div>
              <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
                {presets.map(p => (
                  <button key={p} className={'btn ' + (amount === p ? 'soft' : 'ghost') + ' sm'} onClick={() => setAmount(p)}>${p}</button>
                ))}
                {cash > 0 && <button className="btn ghost sm" onClick={() => setAmount(cash)}>Max</button>}
              </div>
              <div className="card flat" style={{ padding: 16 }}>
                <FeeRow label="Unit price (NAV)" v={'$' + fmtNum(bot.unit_price, 4)}/>
                <FeeRow label="You'll receive" v={fmtNum(units, 4) + ' units'}/>
                <div className="row" style={{ justifyContent: 'space-between', padding: '12px 0 0', marginTop: 4, borderTop: '1px solid var(--line)' }}>
                  <strong>Total</strong>
                  <strong className="num" style={{ fontSize: 18 }}>{USD(amount)}</strong>
                </div>
              </div>
              {insufficient && <div style={{ fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8 }}>Amount exceeds available cash. Top up via Deposit first.</div>}
              {error && <div style={{ fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8 }}>{error}</div>}
              <button className="btn primary block lg" onClick={submit} disabled={busy || amount < 1 || insufficient}>{busy ? 'Submitting…' : 'Confirm purchase'}</button>
            </>
          ) : (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--pos-soft)', color: 'var(--pos)', display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}>
                <IconCheck size={28}/>
              </div>
              <h2 className="h2">Units purchased</h2>
              <p className="muted" style={{ fontSize: 14, marginTop: 8 }}>
                <strong className="num">{fmtNum(result?.units, 4)}</strong> units of <strong>{bot.name}</strong><br/>
                at NAV <strong className="num">${fmtNum(result?.unit_price, 4)}</strong>
              </p>
              <button className="btn primary lg" style={{ marginTop: 12 }} onClick={onClose}>Done</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function WithdrawModal({ bot, onClose, user }) {
  const [dash] = useApi('/api/dashboard/user');
  const holding = (dash?.holdings || []).find(h => h.bot_id === bot.id);
  const [units, setUnits] = React.useState(holding ? holding.units / 2 : 0);
  const [busy, setBusy] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [step, setStep] = React.useState(0);
  const [error, setError] = React.useState(null);
  React.useEffect(() => { if (holding && units === 0) setUnits(holding.units / 2); }, [holding]);
  if (!dash) return null;
  if (!holding) {
    return (
      <div className="modal-backdrop" onClick={onClose}>
        <div className="modal" onClick={(e) => e.stopPropagation()}>
          <div className="modal-hd">
            <strong>Sell units</strong>
            <button className="modal-x" onClick={onClose}><IconX size={14}/></button>
          </div>
          <div className="modal-bd"><p className="muted">You don't hold any units in this bot.</p></div>
        </div>
      </div>
    );
  }
  const amount = units * bot.unit_price;
  const submit = async () => {
    setBusy(true); setError(null);
    try {
      const r = await api.post('/api/transactions/sell', { bot_id: bot.id, units });
      setResult(r); setStep(1);
    } catch (e) { setError(e.detail || e.message); }
    setBusy(false);
  };
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-hd">
          <div className="row gap-12">
            <div className="bot-emblem" style={{ background: colorFor(bot.id), width: 36, height: 36, fontSize: 14 }}>{emojiFor(bot.risk_category)}</div>
            <div>
              <div className="tiny muted">Sell units in</div>
              <strong>{bot.name}</strong>
            </div>
          </div>
          <button className="modal-x" onClick={onClose}><IconX size={14}/></button>
        </div>
        <div className="modal-bd">
          {step === 0 ? (
            <>
              <div className="field">
                <label className="field-label">Units to sell</label>
                <input className="input num" style={{ fontSize: 22, fontWeight: 700, padding: '18px 16px' }}
                  value={units} onChange={(e) => setUnits(Math.min(holding.units, Number(e.target.value) || 0))}/>
                <div className="field-hint">You hold <strong className="num">{fmtNum(holding.units, 4)}</strong> units</div>
              </div>
              <input type="range" min="0" max={holding.units} step={holding.units / 1000} value={units}
                onChange={(e) => setUnits(Number(e.target.value))} style={{ width: '100%' }}/>
              <div className="row gap-6">
                {[25, 50, 75, 100].map(p => (
                  <button key={p} className="btn ghost sm" onClick={() => setUnits(holding.units * p / 100)}>{p}%</button>
                ))}
              </div>
              <div className="card flat" style={{ padding: 16 }}>
                <FeeRow label="Unit price (NAV)" v={'$' + fmtNum(bot.unit_price, 4)}/>
                <FeeRow label="Units selling" v={fmtNum(units, 4)}/>
                <FeeRow label="Settlement" v="T+0 NAV"/>
                <div className="row" style={{ justifyContent: 'space-between', padding: '12px 0 0', marginTop: 4, borderTop: '1px solid var(--line)' }}>
                  <strong>You'll receive</strong>
                  <strong className="num" style={{ fontSize: 18 }}>{USD(amount)}</strong>
                </div>
              </div>
              {error && <div style={{ fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8 }}>{error}</div>}
              <button className="btn danger block lg" onClick={submit} disabled={busy || units === 0}>{busy ? 'Submitting…' : 'Confirm sale'}</button>
            </>
          ) : (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--pos-soft)', color: 'var(--pos)', display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}>
                <IconCheck size={28}/>
              </div>
              <h2 className="h2">Units sold</h2>
              <p className="muted" style={{ fontSize: 14, marginTop: 8 }}>
                Sold <strong className="num">{fmtNum(units, 4)}</strong> units<br/>
                for <strong className="num">{USD(result?.amount || amount)}</strong>
              </p>
              <button className="btn primary lg" style={{ marginTop: 12 }} onClick={onClose}>Done</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InvestModal, WithdrawModal });
