// Pantalla de Portafolio: resumen + holdings + watchlist + movers
function Portfolio({ onOpenTicker, watchlist, holdings, accent, intensity }) {
  // Cálculos sobre holdings
  const positions = holdings.map((h) => {
    const t = window.TICKERS[h.symbol];
    const value = t.price * h.shares;
    const cost  = h.avgCost * h.shares;
    const pl    = value - cost;
    const plPct = (pl / cost) * 100;
    const dayPl = t.change * h.shares;
    return { ...h, t, value, cost, pl, plPct, dayPl };
  });

  const totalValue = positions.reduce((s, p) => s + p.value, 0);
  const totalCost  = positions.reduce((s, p) => s + p.cost, 0);
  const totalPl    = totalValue - totalCost;
  const totalPlPct = (totalPl / totalCost) * 100;
  const dayPl      = positions.reduce((s, p) => s + p.dayPl, 0);
  const dayPlPct   = (dayPl / (totalValue - dayPl)) * 100;
  const cash       = 12480.50;

  // Movers: del universo de tickers, top 3 ganadores y 3 perdedores
  const allTickers = Object.values(window.TICKERS);
  const gainers = [...allTickers].sort((a, b) => b.pct - a.pct).slice(0, 3);
  const losers  = [...allTickers].sort((a, b) => a.pct - b.pct).slice(0, 3);

  // Serie agregada del portafolio (suma de series de holdings, normalizada)
  const portfolioSeries = React.useMemo(() => {
    const N = 80;
    const sums = new Array(N).fill(0);
    positions.forEach((p) => {
      const s = window.genSeries(p.symbol, '1A', N);
      s.forEach((v, i) => { sums[i] += v * p.shares; });
    });
    return sums;
  }, [holdings]);

  const fmt = (n) => n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const allocations = positions
    .map((p) => ({ ...p, alloc: (p.value / totalValue) * 100 }))
    .sort((a, b) => b.alloc - a.alloc);

  return (
    <div className="portfolio-screen">
      {/* ── HERO RESUMEN ── */}
      <section className="pf-hero">
        <div className="pf-hero-left">
          <div className="pf-hero-label">Valor total del portafolio</div>
          <div className="pf-hero-value">
            <span className="pf-curr">$</span>{fmt(totalValue)}
          </div>
          <div className="pf-hero-meta">
            <span className={`pf-pill ${dayPl >= 0 ? 'up' : 'dn'}`}>
              {dayPl >= 0 ? '▲' : '▼'} ${fmt(Math.abs(dayPl))} · {dayPlPct >= 0 ? '+' : ''}{dayPlPct.toFixed(2)}% hoy
            </span>
            <span className="pf-meta-divider">·</span>
            <span className={totalPl >= 0 ? 'up' : 'dn'} style={{ fontWeight: 600 }}>
              {totalPl >= 0 ? '+' : ''}${fmt(totalPl)} total
            </span>
            <span className="pf-meta-divider">·</span>
            <span className="pf-meta-muted">{totalPlPct >= 0 ? '+' : ''}{totalPlPct.toFixed(1)}% desde apertura</span>
          </div>

          <div className="pf-hero-secondary">
            <div className="pf-sec-item">
              <span className="pf-sec-label">Efectivo disponible</span>
              <span className="pf-sec-val">${fmt(cash)}</span>
            </div>
            <div className="pf-sec-item">
              <span className="pf-sec-label">Posiciones abiertas</span>
              <span className="pf-sec-val">{positions.length}</span>
            </div>
            <div className="pf-sec-item">
              <span className="pf-sec-label">Coste base</span>
              <span className="pf-sec-val">${fmt(totalCost)}</span>
            </div>
            <div className="pf-sec-item">
              <span className="pf-sec-label">Poder de compra</span>
              <span className="pf-sec-val">${fmt(cash + totalValue * 0.5)}</span>
            </div>
          </div>
        </div>

        <div className="pf-hero-right">
          <div className="pf-hero-sparkline">
            <window.Sparkline values={portfolioSeries}
                       color={totalPl >= 0 ? 'var(--accent)' : 'var(--neg)'}
                       width={320} height={120} strokeWidth={2} fill={true}/>
            <div className="pf-hero-sparkline-labels">
              <span>Hace 1 año</span>
              <span>Hoy</span>
            </div>
          </div>
        </div>
      </section>

      <div className="pf-grid">
        {/* ── HOLDINGS ── */}
        <section className="pf-card pf-holdings">
          <header className="pf-card-head">
            <h3>Mis posiciones</h3>
            <div className="pf-card-tabs">
              <button className="pf-tab on">Holdings</button>
              <button className="pf-tab">Asignación</button>
              <button className="pf-tab">Rendimiento</button>
            </div>
          </header>

          <table className="pf-table">
            <thead>
              <tr>
                <th>Ticker</th>
                <th>Acciones</th>
                <th>Coste medio</th>
                <th>Último</th>
                <th>Cambio hoy</th>
                <th>Valor</th>
                <th>P&amp;L total</th>
                <th style={{ width: 90 }}>1A</th>
              </tr>
            </thead>
            <tbody>
              {positions.map((p) => {
                const spark = window.genSeries(p.symbol, '1A', 36);
                const dayUp = p.t.pct >= 0;
                const plUp  = p.pl >= 0;
                return (
                  <tr key={p.symbol} className="pf-row" onClick={() => onOpenTicker(p.symbol)}>
                    <td>
                      <div className="pf-ticker">
                        <div className="pf-tic-sym">{p.symbol}</div>
                        <div className="pf-tic-name">{p.t.name}</div>
                      </div>
                    </td>
                    <td className="num">{p.shares}</td>
                    <td className="num">${p.avgCost.toFixed(2)}</td>
                    <td className="num strong">${p.t.price.toFixed(2)}</td>
                    <td className={`num ${dayUp ? 'up' : 'dn'}`}>
                      {dayUp ? '+' : ''}{p.t.pct.toFixed(2)}%
                    </td>
                    <td className="num strong">${fmt(p.value)}</td>
                    <td className={`num ${plUp ? 'up' : 'dn'}`}>
                      <div>{plUp ? '+' : ''}${fmt(Math.abs(p.pl))}</div>
                      <div style={{ fontSize: 10.5, opacity: .7 }}>{plUp ? '+' : ''}{p.plPct.toFixed(1)}%</div>
                    </td>
                    <td>
                      <window.Sparkline values={spark} color={plUp ? 'var(--accent)' : 'var(--neg)'}
                                 width={86} height={28}/>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </section>

        {/* ── ASIGNACIÓN ── */}
        <section className="pf-card pf-alloc">
          <header className="pf-card-head">
            <h3>Asignación</h3>
          </header>
          <div className="alloc-bars">
            {allocations.map((p) => (
              <div key={p.symbol} className="alloc-row" onClick={() => onOpenTicker(p.symbol)}>
                <div className="alloc-line">
                  <span className="alloc-sym">{p.symbol}</span>
                  <span className="alloc-pct">{p.alloc.toFixed(1)}%</span>
                </div>
                <div className="alloc-bar">
                  <div className="alloc-bar-fill" style={{ width: `${p.alloc}%` }}></div>
                </div>
              </div>
            ))}
            <div className="alloc-row alloc-cash">
              <div className="alloc-line">
                <span className="alloc-sym muted">Efectivo</span>
                <span className="alloc-pct muted">{((cash / (totalValue + cash)) * 100).toFixed(1)}%</span>
              </div>
              <div className="alloc-bar">
                <div className="alloc-bar-fill cash" style={{ width: `${(cash / (totalValue + cash)) * 100}%` }}></div>
              </div>
            </div>
          </div>
        </section>

        {/* ── WATCHLIST ── */}
        <section className="pf-card pf-watch">
          <header className="pf-card-head">
            <h3>Watchlist</h3>
            <button className="pf-link">Editar</button>
          </header>
          <div className="watch-list">
            {watchlist.map((sym) => {
              const t = window.TICKERS[sym];
              const spark = window.genSeries(sym, '1S', 28);
              const up = t.pct >= 0;
              return (
                <div key={sym} className="watch-item" onClick={() => onOpenTicker(sym)}>
                  <div className="watch-info">
                    <div className="watch-sym">{sym}</div>
                    <div className="watch-name">{t.name}</div>
                  </div>
                  <window.Sparkline values={spark} color={up ? 'var(--accent)' : 'var(--neg)'}
                             width={64} height={24} strokeWidth={1.5}/>
                  <div className="watch-pricing">
                    <div className="watch-price">${t.price.toFixed(2)}</div>
                    <div className={`watch-pct ${up ? 'up' : 'dn'}`}>
                      {up ? '+' : ''}{t.pct.toFixed(2)}%
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        {/* ── MOVERS ── */}
        <section className="pf-card pf-movers">
          <header className="pf-card-head">
            <h3>Movimientos del mercado</h3>
            <div className="pf-card-tabs">
              <button className="pf-tab on">Ganadores</button>
              <button className="pf-tab">Perdedores</button>
            </div>
          </header>
          <div className="movers-list">
            {gainers.map((t) => {
              const spark = window.genSeries(t.symbol, '1D', 24);
              return (
                <div key={t.symbol} className="mover-item" onClick={() => onOpenTicker(t.symbol)}>
                  <div className="mover-left">
                    <div className="mover-sym">{t.symbol}</div>
                    <div className="mover-name">{t.name}</div>
                  </div>
                  <window.Sparkline values={spark} color="var(--accent)" width={70} height={26}/>
                  <div className="mover-right">
                    <div className="mover-price">${t.price.toFixed(2)}</div>
                    <div className="mover-pct up">+{t.pct.toFixed(2)}%</div>
                  </div>
                </div>
              );
            })}
            <div className="movers-divider">Perdedores</div>
            {losers.map((t) => {
              const spark = window.genSeries(t.symbol, '1D', 24);
              return (
                <div key={t.symbol} className="mover-item" onClick={() => onOpenTicker(t.symbol)}>
                  <div className="mover-left">
                    <div className="mover-sym">{t.symbol}</div>
                    <div className="mover-name">{t.name}</div>
                  </div>
                  <window.Sparkline values={spark} color="var(--neg)" width={70} height={26}/>
                  <div className="mover-right">
                    <div className="mover-price">${t.price.toFixed(2)}</div>
                    <div className="mover-pct dn">{t.pct.toFixed(2)}%</div>
                  </div>
                </div>
              );
            })}
          </div>
        </section>
      </div>
    </div>
  );
}

window.Portfolio = Portfolio;
