/* ═══════════════════════════════════════════════════════════════════
   MY HOLDINGS · owner-entered positions (qty + avg cost)
   Powers the "my avg / qty / value / P&L" personalization on every page.
   API-independent — works even though Bybit's private API is geo-blocked.
   ═══════════════════════════════════════════════════════════════════ */

function HoldingsModal({ open, onClose, coins, onSaved }) {
  const [rows, setRows]     = React.useState({});   /* sym -> {qty, avg} */
  const [saving, setSaving] = React.useState(false);
  const [query, setQuery]   = React.useState('');

  /* load existing holdings when opened */
  React.useEffect(() => {
    if (!open) return;
    setQuery('');
    ST_fetch('/holdings').then(d => {
      const map = {};
      (d.holdings || []).forEach(h => { map[h.symbol] = { qty: String(h.qty), avg: String(h.avg_cost) }; });
      setRows(map);
    }).catch(() => setRows({}));
  }, [open]);

  if (!open) return null;

  const list = (coins || ST_COINS).filter(c =>
    !query || c.sym.toLowerCase().includes(query.toLowerCase()) || (c.name||'').toLowerCase().includes(query.toLowerCase())
  );
  /* held coins first */
  list.sort((a, b) => (rows[b.sym] ? 1 : 0) - (rows[a.sym] ? 1 : 0));

  const setRow = (sym, field, val) => setRows(prev => ({ ...prev, [sym]: { ...(prev[sym] || { qty: '', avg: '' }), [field]: val } }));

  const totalValue = list.reduce((s, c) => {
    const r = rows[c.sym]; const q = parseFloat(r?.qty || 0) || 0;
    return s + q * (c.price || 0);
  }, 0);

  const save = async () => {
    setSaving(true);
    const entries = Object.entries(rows);
    for (const [sym, r] of entries) {
      const qty = parseFloat(r.qty || 0) || 0;
      const avg = parseFloat(r.avg || 0) || 0;
      try {
        await fetch(window.ST_API + '/holdings', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ symbol: sym, qty, avg_cost: avg }),
        });
      } catch (_) {}
    }
    setSaving(false);
    if (onSaved) onSaved();
    onClose();
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(5,6,10,0.72)', backdropFilter: 'blur(3px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 620, maxHeight: '82vh', display: 'flex', flexDirection: 'column',
        background: ST.bg2, border: `1px solid ${ST.borderHi}`, borderRadius: 12,
        boxShadow: '0 30px 80px -30px rgba(0,0,0,0.9)', overflow: 'hidden',
      }}>
        {/* header */}
        <div style={{ padding: '16px 20px', borderBottom: `1px solid ${ST.border}`,
          display: 'flex', alignItems: 'center', gap: 12 }}>
          <ShadowMark size={22} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: ST.ink }}>My Holdings</div>
            <div className="mono" style={{ fontSize: 10, color: ST.ink4 }}>
              enter your real qty + avg cost · shown on every page
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="eyebrow" style={{ fontSize: 8 }}>TOTAL VALUE</div>
            <div className="num" style={{ fontSize: 18, fontWeight: 600, color: ST.amber }}>
              {totalValue > 0 ? `$${totalValue.toLocaleString('en-US', { maximumFractionDigits: 0 })}` : '$0'}</div>
          </div>
          <button onClick={onClose} className="mono" style={{
            marginLeft: 6, padding: '6px 10px', borderRadius: 6, cursor: 'pointer',
            background: 'transparent', color: ST.ink3, border: `1px solid ${ST.border}`, fontSize: 12 }}>✕</button>
        </div>

        {/* search */}
        <div style={{ padding: '10px 20px', borderBottom: `1px solid ${ST.border}` }}>
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search coin…"
            className="mono" style={{
              width: '100%', padding: '8px 11px', borderRadius: 7, fontSize: 12,
              background: ST.panel, border: `1px solid ${ST.border}`, color: ST.ink, outline: 'none' }} />
        </div>

        {/* column heads */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr 1fr', gap: 10,
          padding: '8px 20px', borderBottom: `1px solid ${ST.border}` }}>
          {['COIN', 'QUANTITY', 'AVG COST $', 'VALUE / P&L'].map((h, i) => (
            <span key={i} className="eyebrow" style={{ fontSize: 8, textAlign: i === 0 ? 'left' : 'right' }}>{h}</span>
          ))}
        </div>

        {/* rows */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 0' }}>
          {list.map(c => {
            const r = rows[c.sym] || { qty: '', avg: '' };
            const qty = parseFloat(r.qty || 0) || 0;
            const avg = parseFloat(r.avg || 0) || 0;
            const val = qty * (c.price || 0);
            const pnl = (qty > 0 && avg > 0 && c.price) ? ((c.price - avg) / avg * 100) : null;
            const held = qty > 0;
            return (
              <div key={c.sym} style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr 1fr', gap: 10,
                alignItems: 'center', padding: '7px 20px',
                background: held ? ST.amberFog : 'transparent' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                  <CoinGlyph sym={c.sym} size={22} />
                  <div style={{ minWidth: 0 }}>
                    <div className="mono" style={{ fontSize: 12, fontWeight: 600, color: held ? ST.amber : ST.ink }}>{c.sym}</div>
                    <div className="mono" style={{ fontSize: 9, color: ST.ink4 }}>${ST_fmt.price(c.price)}</div>
                  </div>
                </div>
                <input value={r.qty} onChange={e => setRow(c.sym, 'qty', e.target.value)} placeholder="0" inputMode="decimal"
                  className="num" style={inputStyle} />
                <input value={r.avg} onChange={e => setRow(c.sym, 'avg', e.target.value)} placeholder="0.00" inputMode="decimal"
                  className="num" style={inputStyle} />
                <div style={{ textAlign: 'right' }}>
                  <div className="num" style={{ fontSize: 12, color: held ? ST.ink : ST.ink4 }}>{held ? '$' + ST_fmt.price(val) : '—'}</div>
                  {pnl != null && <div className="num" style={{ fontSize: 10, fontWeight: 600, color: pnl >= 0 ? ST.green : ST.red }}>
                    {pnl >= 0 ? '+' : ''}{pnl.toFixed(1)}%</div>}
                </div>
              </div>
            );
          })}
        </div>

        {/* footer */}
        <div style={{ padding: '12px 20px', borderTop: `1px solid ${ST.border}`, display: 'flex', gap: 10 }}>
          <button onClick={onClose} className="mono" style={{
            flex: 1, padding: '10px', borderRadius: 8, cursor: 'pointer', fontSize: 12, fontWeight: 600,
            background: 'transparent', color: ST.ink3, border: `1px solid ${ST.border}` }}>Cancel</button>
          <button onClick={save} disabled={saving} className="mono" style={{
            flex: 2, padding: '10px', borderRadius: 8, cursor: 'pointer', fontSize: 12, fontWeight: 700, letterSpacing: '0.04em',
            background: ST.amber, color: '#0B0D14', border: 'none' }}>
            {saving ? 'Saving…' : 'Save Holdings'}</button>
        </div>
      </div>
    </div>
  );
}

const inputStyle = {
  width: '100%', padding: '7px 9px', borderRadius: 6, fontSize: 12, textAlign: 'right',
  background: '#0B0D14', border: '1px solid #1E2130', color: '#ECEFF6', outline: 'none',
};

window.HoldingsModal = HoldingsModal;
