/* ============================================================
   Mercado.jsx — inversiones (/mercado)
   ============================================================ */
function FxPill({ f }) {
  return (
    <div className="fx-pill">
      <span className="fx-name">{f.name}</span>
      <span className="fx-val">${fmtNum(f.value, 1)}</span>
      <Delta value={f.delta} className="fx-d" />
    </div>
  );
}

function MacroCard({ m }) {
  return (
    <div className="metric" style={{ padding: '14px 16px' }}>
      <div className="m-label" style={{ marginBottom: 8 }}>{m.name}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span className="num" style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{m.value}</span>
        <span className="muted-note">{m.unit}</span>
        <span style={{ marginLeft: 'auto' }}><Delta value={m.delta} /></span>
      </div>
      <div className="muted-note" style={{ marginTop: 8, fontSize: 11.5 }}>{m.hint}</div>
    </div>
  );
}

function AssetTable({ rows, unit, onHover }) {
  const hasInd = rows.some(r => r.indicators != null);
  return (
    <div className="tbl-wrap">
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ textAlign: 'left' }}>Ticker</th>
            <th style={{ textAlign: 'left' }}>Nombre</th>
            <th>Precio</th>
            <th>Var. día</th>
            {hasInd && <th title="RSI 14 períodos">RSI</th>}
            {hasInd && <th title="Momentum 5 días">Mom.5d</th>}
            {hasInd && <th title="Score técnico 0-100">Score</th>}
            <th style={{ textAlign: 'right' }}>Señal</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => {
            const ind = r.indicators;
            const rsiColor = !ind?.rsi ? 'var(--text-3)'
              : ind.rsi < 30 ? 'var(--pos)' : ind.rsi > 70 ? 'var(--neg)' : 'var(--text)';
            const scoreColor = !r.score ? 'var(--text-3)'
              : r.score >= 68 ? 'var(--pos)' : r.score >= 52 ? 'var(--info)' : r.score >= 38 ? 'var(--warn)' : 'var(--neg)';
            return (
              <tr key={r.tk}>
                <td style={{ textAlign: 'left' }}><span className="t-ticker">{r.tk}</span></td>
                <td style={{ textAlign: 'left' }} className="t-name">{r.nm}</td>
                <td className="t-num" style={{ fontWeight: 600 }}>
                  {r.px == null ? '—' : unit === 'US$' ? 'US$' + fmtNum(r.px, 2) : fmtARS(r.px)}
                </td>
                <td className="t-num">{r.v != null ? <Delta value={r.v} /> : <span className="muted-note">—</span>}</td>
                {hasInd && (
                  <td className="t-num" style={{ color: rsiColor, fontWeight: 600, fontSize: 12.5 }}>
                    {ind?.rsi != null ? ind.rsi.toFixed(0) : '—'}
                  </td>
                )}
                {hasInd && (
                  <td className="t-num">
                    {ind?.mom5 != null ? <Delta value={ind.mom5} /> : <span className="muted-note">—</span>}
                  </td>
                )}
                {hasInd && (
                  <td className="t-num" style={{ color: scoreColor, fontWeight: 700 }}>
                    {r.score != null ? r.score : '—'}
                  </td>
                )}
                <td style={{ textAlign: 'right' }}><Signal s={r} onHover={onHover} /></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function BonosTable({ rows, onHover }) {
  return (
    <div className="tbl-wrap">
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ textAlign: 'left' }}>Ticker</th>
            <th style={{ textAlign: 'left' }}>Nombre</th>
            <th>Precio</th>
            <th>Var. día</th>
            <th title="Tasa interna de retorno implícita">TIR</th>
            <th style={{ textAlign: 'right' }}>Señal</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.tk}>
              <td style={{ textAlign: 'left' }}>
                <span className="t-ticker">{r.tk}</span>
                {r.isLive && <span style={{ marginLeft: 5, fontSize: 9, color: 'var(--pos)' }}>●</span>}
              </td>
              <td style={{ textAlign: 'left' }} className="t-name">{r.nm}</td>
              <td className="t-num" style={{ fontWeight: 600 }}>
                {r.px != null ? 'US$' + fmtNum(r.px, 2) : '—'}
              </td>
              <td className="t-num">
                {r.v != null ? <Delta value={r.v} /> : <span className="muted-note">—</span>}
              </td>
              <td className="t-num" style={{ fontWeight: 600, color: 'var(--info)' }}>
                {r.tir != null ? r.tir.toFixed(1) + '%' : '—'}
              </td>
              <td style={{ textAlign: 'right' }}><Signal s={r} onHover={onHover} /></td>
            </tr>
          ))}
        </tbody>
      </table>
      <div className="muted-note" style={{ padding: '10px 0 2px', fontSize: 11, display: 'flex', alignItems: 'center', gap: 5 }}>
        <Icon name="info" size={12} />
        TIR calculada sobre flujos estimados (aproximación). ● = precio live vía BYMA. No es recomendación de inversión.
      </div>
    </div>
  );
}

function Mercado({ go, onHover, data, loading, errors }) {
  const D   = data;
  const [tab, setTab] = useState('cedears');
  const mep = data._mepRate || 1;
  const pf  = window.STATIC.computePortfolio(data._priceMap || {}, mep);

  const tabs = [
    { id: 'cedears',  label: 'CEDEARs',          rows: D.cedears,  unit: '$',   type: 'equity' },
    { id: 'acciones', label: 'Acciones locales',  rows: D.acciones, unit: '$',   type: 'equity' },
    { id: 'bonos',    label: 'Renta Fija',        rows: D.bonos,    unit: 'US$', type: 'bonos'  },
  ];
  const active = tabs.find(t => t.id === tab);

  return (
    <div className="content-inner page-enter">
      {/* FX pills */}
      <div className="section-title">Tipos de cambio</div>
      <div style={{ display: 'flex', gap: 10, marginBottom: 22, flexWrap: 'wrap' }}>
        {D.fx.map(f => <FxPill key={f.name} f={f} />)}
        <div className="fx-pill" style={{ background: 'var(--bg-2)', borderColor: 'var(--border)' }}>
          <span className="fx-name">Brecha</span>
          <span className="fx-val" style={{ color: 'var(--warn)' }}>{fmtNum(D.brecha, 1)}%</span>
          <span className="fx-d muted-note">blue vs oficial</span>
        </div>
      </div>

      {/* Macro */}
      <div className="section-title">Indicadores macro</div>
      <div className="metric-grid" style={{ marginBottom: 22 }}>
        {D.macro.map(m => <MacroCard key={m.name} m={m} />)}
      </div>

      {/* Activos */}
      <div className="card" style={{ marginBottom: 22 }}>
        <div className="card-head" style={{ flexWrap: 'wrap', gap: 12 }}>
          <div className="card-title"><Icon name="market" size={16} className="ico" />Activos · señales del día</div>
          <div className="tabs">
            {tabs.map(t => (
              <button key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>{t.label}</button>
            ))}
          </div>
        </div>
        {active.type === 'bonos'
          ? <BonosTable rows={active.rows} onHover={onHover} />
          : <AssetTable rows={active.rows} unit={active.unit} onHover={onHover} />
        }
        {active.type !== 'bonos' && (
          <div className="muted-note" style={{ marginTop: 12, fontSize: 11.5, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="info" size={13} />Score = análisis técnico (RSI + SMA + momentum) ajustado por contexto macro y portfolio. No es recomendación de inversión.
          </div>
        )}
      </div>

      {/* Mi portfolio */}
      <div className="card">
        <div className="card-head">
          <div className="card-title"><Icon name="coins" size={16} className="ico" />Mi portfolio</div>
          <div style={{ display: 'flex', gap: 22, alignItems: 'center' }}>
            <div style={{ textAlign: 'right' }}>
              <div className="muted-note" style={{ fontSize: 11 }}>Valor total</div>
              <div className="num" style={{ fontSize: 16, fontWeight: 600 }}>{fmtARS(Math.round(pf.totalMV))}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="muted-note" style={{ fontSize: 11 }}>P&L total</div>
              <div className="num" style={{ fontSize: 16, fontWeight: 600, color: pf.totalPnl >= 0 ? 'var(--pos)' : 'var(--neg)' }}>
                {(pf.totalPnl >= 0 ? '+' : '') + fmtARS(Math.round(pf.totalPnl))} <span style={{ fontSize: 12.5 }}>({fmtPct(pf.totalPct)})</span>
              </div>
            </div>
          </div>
        </div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ textAlign: 'left' }}>Activo</th>
                <th style={{ textAlign: 'left' }}>Tipo</th>
                <th>Cantidad</th>
                <th>P. medio</th>
                <th>Actual</th>
                <th>Valor (ARS)</th>
                <th>P&L</th>
                <th style={{ textAlign: 'left' }}>Broker</th>
              </tr>
            </thead>
            <tbody>
              {pf.rows.map(r => (
                <tr key={r.tk}>
                  <td style={{ textAlign: 'left' }}>
                    <span className="t-ticker">{r.tk}</span> <span className="t-name">· {r.nm}</span>
                  </td>
                  <td style={{ textAlign: 'left' }} className="t-sub">{r.cls}</td>
                  <td className="t-num">{fmtNum(r.qty)}</td>
                  <td className="t-num t-sub">{r.cls === 'Bono' ? r.pm.toFixed(2) : fmtARS(r.pm)}</td>
                  <td className="t-num">{r.cls === 'Bono' ? r.px.toFixed(2) : fmtARS(r.px)}</td>
                  <td className="t-num">{fmtARS(Math.round(r.mv))}</td>
                  <td className="t-num" style={{ fontWeight: 600, color: r.pnl >= 0 ? 'var(--pos)' : 'var(--neg)' }}>
                    {fmtPct(r.pnlPct)}
                  </td>
                  <td style={{ textAlign: 'left' }} className="t-sub">{r.broker}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Mercado });
