// Portfolio screen
function Portfolio() {
  const { t, lang } = useT();
  const [period, setPeriod] = useState('1y');
  const [filter, setFilter] = useState('all');

  const data = window.DIVIDIS_DATA;
  const positions = filter === 'all' ? data.positions : data.positions.filter(p => p.type === filter);

  const totalInvested = data.positions.reduce((s, p) => s + p.invested, 0);
  const totalCurrent = data.positions.reduce((s, p) => s + p.current, 0);
  const totalReturn = totalCurrent - totalInvested;
  const returnPct = (totalReturn / totalInvested) * 100;

  // Allocation
  const alloc = ['invoice', 'fixed', 'equity', 'seed'].map(type => {
    const sum = data.positions.filter(p => p.type === type).reduce((s, p) => s + p.current, 0);
    return { type, sum, pct: (sum / totalCurrent) * 100 };
  });

  // Upcoming
  const upcoming = data.positions.filter(p => p.payment).sort((a, b) => new Date(a.maturity) - new Date(b.maturity));

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">{t('pf_title')}</h1>
          <div className="page-sub">{t('pf_sub')}</div>
        </div>
      </div>

      {/* KPIs */}
      <div className="pf-kpis">
        <div className="card card-pad pf-kpi-hero">
          <div className="stat">
            <div className="stat-label">{t('pf_value')}</div>
            <div className="stat-value num">{fmtEUR(totalCurrent)}</div>
            <div className="stat-sub">
              <span className="stat-delta-up">↑ {fmtEUR(totalReturn)} ({returnPct.toFixed(1)}%)</span> · TIR neta 9.4%
            </div>
          </div>
          <Sparkline values={data.chartData} width={140} height={40} />
        </div>
        <div className="card card-pad">
          <div className="stat">
            <div className="stat-label">{t('pf_invested')}</div>
            <div className="stat-value num" style={{ fontSize: 26 }}>{fmtEUR(totalInvested)}</div>
            <div className="stat-sub">7 posiciones · 4 categorías</div>
          </div>
        </div>
        <div className="card card-pad">
          <div className="stat">
            <div className="stat-label">{t('pf_xirr')}</div>
            <div className="stat-value num" style={{ fontSize: 26, color: 'var(--emerald-2)' }}>9,4%</div>
            <div className="stat-sub"><span className="stat-delta-up">↑ +2,1%</span> vs. media</div>
          </div>
        </div>
        <div className="card card-pad">
          <div className="stat">
            <div className="stat-label">{t('pf_next')}</div>
            <div className="stat-value num" style={{ fontSize: 26 }}>{fmtEUR(312)}</div>
            <div className="stat-sub">18 jun · IMT</div>
          </div>
        </div>
      </div>

      {/* Chart + Allocation */}
      <div className="pf-row-2">
        <div className="card card-pad-lg">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 22 }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{t('pf_chart_title')}</div>
              <div className="num" style={{ fontFamily: 'var(--serif)', fontSize: 32, letterSpacing: '-0.02em', marginTop: 4 }}>{fmtEUR(totalCurrent)}</div>
            </div>
            <div className="period-toggle">
              {['1m', '3m', 'ytd', '1y', 'all'].map(p => (
                <button key={p} className={`period-btn ${period === p ? 'active' : ''}`} onClick={() => setPeriod(p)}>
                  {t('pf_chart_' + p)}
                </button>
              ))}
            </div>
          </div>
          <PortfolioChart data={data.chartData} />
        </div>

        <div className="card card-pad-lg">
          <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 18 }}>{t('pf_alloc_title')}</div>
          <DonutChart alloc={alloc} total={totalCurrent} />
          <div className="alloc-legend">
            {alloc.map(a => (
              <div key={a.type} className="alloc-row">
                <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span className="alloc-dot" style={{ background: typeColor(a.type) }}></span>
                  <TypeIcon type={a.type} size={12} />
                  <span style={{ fontSize: 13 }}>{typeLabel(a.type, t)}</span>
                </span>
                <span style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <span className="num" style={{ fontSize: 12, color: 'var(--text-3)' }}>{fmtEUR(a.sum)}</span>
                  <span className="num" style={{ fontSize: 13, fontWeight: 500, width: 44, textAlign: 'right' }}>{a.pct.toFixed(0)}%</span>
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Positions table */}
      <div style={{ marginTop: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <h2 style={{ fontFamily: 'var(--serif)', fontSize: 22, letterSpacing: '-0.02em', fontWeight: 400 }}>{t('pf_pos_title')}</h2>
          <div className="mkt-filters">
            {[
              { id: 'all', label: t('mkt_filter_all') },
              { id: 'invoice', label: t('mkt_filter_invoice') },
              { id: 'fixed', label: t('mkt_filter_fixed') },
              { id: 'equity', label: t('mkt_filter_equity') },
            ].map(f => (
              <button key={f.id} className={`mkt-fbtn ${filter === f.id ? 'active' : ''}`} onClick={() => setFilter(f.id)}>{f.label}</button>
            ))}
          </div>
        </div>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="pos-tbl">
            <div className="pos-head">
              <div>{t('pf_pos_name')}</div>
              <div>{t('pf_pos_cat')}</div>
              <div className="r">{t('pf_pos_invested')}</div>
              <div className="r">{t('pf_pos_current')}</div>
              <div className="r">{t('pf_pos_yield')}</div>
              <div>Vencimiento</div>
              <div>{t('pf_pos_status')}</div>
            </div>
            {positions.map(p => (
              <div key={p.id} className="pos-row">
                <div style={{ fontWeight: 500 }}>{p.issuer}</div>
                <div><TypeBadge type={p.type} /></div>
                <div className="r num">{fmtEUR(p.invested)}</div>
                <div className="r num">{fmtEUR(p.current)}</div>
                <div className="r num" style={{ color: p.yieldPct > 0 ? 'var(--emerald-2)' : 'var(--text-3)' }}>
                  {p.yieldPct > 0 ? `+${p.yieldPct.toFixed(1)}%` : '—'}
                </div>
                <div className="num" style={{ color: 'var(--text-2)', fontSize: 12 }}>{fmtDate(p.maturity, lang)}</div>
                <div>
                  <span className={`tag tag-${p.status}`}>{t('pf_status_' + p.status)}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Upcoming payments */}
      <div style={{ marginTop: 28 }}>
        <h2 style={{ fontFamily: 'var(--serif)', fontSize: 22, letterSpacing: '-0.02em', fontWeight: 400, marginBottom: 14 }}>{t('pf_calendar_title')}</h2>
        <div className="upcoming-grid">
          {upcoming.map(p => (
            <div key={p.id} className="card card-pad upcoming-card">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <TypeBadge type={p.type} />
                <span className="num" style={{ fontSize: 11, color: 'var(--text-3)' }}>{fmtDate(p.maturity, lang)}</span>
              </div>
              <div style={{ fontFamily: 'var(--serif)', fontSize: 22, letterSpacing: '-0.02em', marginTop: 14, marginBottom: 6 }}>{p.issuer}</div>
              <div className="num" style={{ fontSize: 22, color: 'var(--emerald-2)', fontWeight: 500 }}>+{fmtEUR(p.payment)}</div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        .pf-kpis { display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 16px; margin-bottom: 24px; }
        .pf-kpi-hero {
          background: linear-gradient(135deg, var(--surface), rgba(45,190,126,0.04));
          border-color: var(--emerald-line);
          display: flex; justify-content: space-between; align-items: flex-end;
        }
        .pf-row-2 { display: grid; grid-template-columns: 1.6fr 1fr; gap: 16px; }
        .period-toggle { display: flex; background: var(--bg-1); border: 1px solid var(--line); border-radius: 8px; padding: 2px; gap: 0; }
        .period-btn { padding: 6px 12px; background: transparent; border: none; color: var(--text-3); font-size: 11px; font-weight: 500; border-radius: 6px; cursor: pointer; letter-spacing: 0.04em; }
        .period-btn.active { background: var(--surface-3); color: var(--text); }
        .alloc-legend { display: flex; flex-direction: column; gap: 8px; margin-top: 18px; }
        .alloc-row { display: flex; justify-content: space-between; align-items: center; padding: 6px 0; border-top: 1px solid var(--line); }
        .alloc-dot { width: 8px; height: 8px; border-radius: 50%; }
        .pos-head, .pos-row {
          display: grid;
          grid-template-columns: 2fr 1fr 1fr 1fr 0.9fr 1fr 0.9fr;
          gap: 12px;
          padding: 14px 22px;
          align-items: center;
        }
        .pos-head { font-size: 11px; color: var(--text-3); letter-spacing: 0.06em; text-transform: uppercase; border-bottom: 1px solid var(--line); }
        .pos-row { font-size: 13px; border-bottom: 1px solid var(--line); transition: background .15s; }
        .pos-row:last-child { border-bottom: none; }
        .pos-row:hover { background: var(--surface-2); }
        .pos-head .r, .pos-row .r { text-align: right; }
        .upcoming-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
      `}</style>
    </div>
  );
}

function typeColor(type) {
  return { invoice: '#5B8DEF', fixed: '#2DBE7E', equity: '#C8A961', seed: '#E5484D' }[type];
}

function PortfolioChart({ data }) {
  const W = 800, H = 200, pad = 10;
  const min = Math.min(...data) * 0.96;
  const max = Math.max(...data) * 1.02;
  const range = max - min;
  const step = (W - 2 * pad) / (data.length - 1);
  const points = data.map((v, i) => `${pad + i * step},${H - ((v - min) / range) * (H - 20) - 10}`);
  const areaPath = `M${points[0]} L${points.join(' L')} L${pad + (data.length - 1) * step},${H} L${pad},${H} Z`;
  const linePath = `M${points.join(' L')}`;

  return (
    <svg viewBox={`0 0 ${W} ${H + 24}`} width="100%" preserveAspectRatio="none" style={{ display: 'block', overflow: 'visible' }}>
      <defs>
        <linearGradient id="pfg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#2DBE7E" stopOpacity="0.18"/>
          <stop offset="1" stopColor="#2DBE7E" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map(g => (
        <line key={g} x1={pad} x2={W - pad} y1={H * g} y2={H * g} stroke="var(--line)" strokeDasharray="3 5" />
      ))}
      <path d={areaPath} fill="url(#pfg)" />
      <path d={linePath} fill="none" stroke="var(--emerald-2)" strokeWidth="1.8" />
      <circle cx={pad + (data.length - 1) * step} cy={H - ((data[data.length - 1] - min) / range) * (H - 20) - 10} r="4" fill="var(--emerald-2)" />
      <circle cx={pad + (data.length - 1) * step} cy={H - ((data[data.length - 1] - min) / range) * (H - 20) - 10} r="8" fill="var(--emerald-2)" opacity="0.2" />
    </svg>
  );
}

function DonutChart({ alloc, total }) {
  const cx = 90, cy = 90, r = 70, stroke = 18;
  let cumulative = 0;
  const C = 2 * Math.PI * r;
  return (
    <svg width="180" height="180" viewBox="0 0 180 180" style={{ display: 'block', margin: '0 auto' }}>
      <circle cx={cx} cy={cy} r={r} stroke="rgba(255,255,255,0.06)" strokeWidth={stroke} fill="none" />
      {alloc.map((a, i) => {
        const dash = (a.pct / 100) * C;
        const offset = -((cumulative / 100) * C);
        cumulative += a.pct;
        return (
          <circle
            key={i}
            cx={cx} cy={cy} r={r}
            stroke={typeColor(a.type)}
            strokeWidth={stroke}
            fill="none"
            strokeDasharray={`${dash} ${C - dash}`}
            strokeDashoffset={offset}
            transform={`rotate(-90 ${cx} ${cy})`}
            strokeLinecap="butt"
          />
        );
      })}
      <text x={cx} y={cy - 6} textAnchor="middle" fill="var(--text-3)" fontSize="10" letterSpacing="0.1em">TOTAL</text>
      <text x={cx} y={cy + 18} textAnchor="middle" fill="var(--text)" fontFamily="var(--serif)" fontSize="22" letterSpacing="-0.02em">{fmtEUR(total)}</text>
    </svg>
  );
}

window.Portfolio = Portfolio;
