/* Page: Portfolio (multi-client overview) */
function PortfolioView({ onOpenClient }) {
  const { data, loading, error } = useApi('/api/clients', []);

  if (loading) return <div className="loading-state">Loading portfolio...</div>;
  if (error) return <div className="error-state">Failed to load portfolio: {error}</div>;

  const clients = data || [];

  const totals = clients.reduce((a, c) => ({
    sessions: a.sessions + c.sessions,
    conv: a.conv + c.conv,
    top10: a.top10 + c.top10,
  }), { sessions: 0, conv: 0, top10: 0 });

  const sortedSessions = [...clients].sort((a,b) => b.sessions - a.sessions);

  return (
    <>
      <div style={{position:'relative'}}>
        <div className="wash agency-only" />
        <div className="page-head" style={{position:'relative', zIndex:1}}>
          <div>
            <div className="eyebrow gold"><span className="dot"/>01 — Agency portfolio</div>
            <h1>Eight clients. Four compounding. Two need attention this week.</h1>
            <div className="sub">Roll-up of organic performance across all SEO retainers. Filter by tier, sort by movement, drill into any client.</div>
          </div>
          <div className="actions">
            <button className="btn btn-secondary"><Icon name="plus" size={13}/> Add client</button>
          </div>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <span className="label">Clients</span>
          <span className="value">8</span>
          <span className="delta flat">+1 this quarter</span>
          <span className="source">GE PH · Active retainers</span>
        </div>
        <div className="kpi">
          <span className="label">Organic sessions · 30d</span>
          <span className="value">{(totals.sessions/1000).toFixed(0)}k</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +14.2% MoM</span>
          <span className="source">GA4 · roll-up</span>
        </div>
        <div className="kpi">
          <span className="label">Conversions · 30d</span>
          <span className="value">{totals.conv.toLocaleString()}</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +18.6% MoM</span>
          <span className="source">GA4 · key events</span>
        </div>
        <div className="kpi">
          <span className="label">Top-10 keywords</span>
          <span className="value">{totals.top10}</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +35</span>
          <span className="source">Semrush · tracked</span>
        </div>
        <div className="kpi">
          <span className="label">At-risk accounts</span>
          <span className="value">2</span>
          <span className="delta down"><Icon name="arrowDown" size={10}/> Isla Verde, Cebu</span>
          <span className="source">GE PH · health rules</span>
        </div>
      </div>

      <div className="section-head">
        <span className="label">Client book</span>
        <span className="rule" />
        <div className="actions">
          <button className="filter-pill active">All <span className="v">8</span></button>
          <button className="filter-pill">Launchpad <span className="v">3</span></button>
          <button className="filter-pill">Engine <span className="v">4</span></button>
          <button className="filter-pill">Full Stack <span className="v">1</span></button>
        </div>
      </div>

      <div className="panel">
        <table className="table">
          <thead>
            <tr>
              <th style={{width: 28}}></th>
              <th>Client</th>
              <th>Tier</th>
              <th>Sources</th>
              <th className="num">Sessions · 30d</th>
              <th className="num">vs prev</th>
              <th className="num">Conversions</th>
              <th className="num">Visibility</th>
              <th className="num">Top-10 KW</th>
              <th>Health</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {sortedSessions.map(c => (
              <tr key={c.id} onClick={() => onOpenClient(c.id)} style={{cursor: 'pointer'}}>
                <td><div className="sb-avatar" style={{width: 26, height: 26, fontSize: 9}}>{c.initials}</div></td>
                <td>
                  <div className="cell-stack">
                    <span className="lead">{c.name}</span>
                    <span className="url">{c.url}</span>
                  </div>
                </td>
                <td><span className="tag">{c.tier}</span></td>
                <td>
                  <div style={{display:'flex', gap: 4}}>
                    {['ga4','gsc','ahrefs','semrush'].map(s => (
                      <span key={s} className="serp-badge" style={{
                        opacity: c.integrations.includes(s) ? 1 : 0.3,
                        color: c.integrations.includes(s) ? 'var(--text-muted)' : 'var(--text-dim)'
                      }}>{s.toUpperCase()}</span>
                    ))}
                  </div>
                </td>
                <td className="num mono">{c.sessions.toLocaleString()}</td>
                <td className="num">
                  <span className={`delta-chip ${c.sessionsDelta >= 0 ? 'up' : 'down'}`}>
                    <Icon name={c.sessionsDelta >= 0 ? 'arrowUp' : 'arrowDown'} size={10}/>
                    {c.sessionsDelta >= 0 ? '+' : ''}{c.sessionsDelta.toFixed(1)}%
                  </span>
                </td>
                <td className="num mono">
                  {c.conv}
                  <span style={{marginLeft: 6}} className={`delta-chip ${c.convDelta >= 0 ? 'up' : 'down'}`}>
                    {c.convDelta >= 0 ? '+' : ''}{c.convDelta.toFixed(1)}%
                  </span>
                </td>
                <td className="num">
                  <div className="bar-cell">
                    <span className="bar"><span style={{width: `${c.visibility}%`}}/></span>
                    <span className="mono">{c.visibility.toFixed(1)}%</span>
                  </div>
                </td>
                <td className="num mono">
                  {c.top10}
                  <span style={{marginLeft: 6, fontSize: 10, color: c.top10Delta >= 0 ? 'var(--accent)' : 'var(--red)'}}>
                    {c.top10Delta >= 0 ? '+' : ''}{c.top10Delta}
                  </span>
                </td>
                <td>
                  <span className={`status ${c.health}`}>
                    <span className="dot"/>
                    {c.health === 'ok' ? 'On track' : c.health === 'warn' ? 'Watch' : 'At risk'}
                  </span>
                </td>
                <td><Icon name="chevR" size={14} color="var(--text-dim)"/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="row-3" style={{marginTop: 24}}>
        <div className="panel">
          <div className="panel-head"><h3>This week's priorities</h3></div>
          <div className="panel-body" style={{display:'flex', flexDirection:'column', gap: 14}}>
            <div style={{display:'flex', gap: 12, alignItems: 'flex-start'}}>
              <span className="status err" style={{marginTop: 4}}><span className="dot"/></span>
              <div>
                <div style={{color:'var(--text)', fontSize: 13, fontWeight: 500}}>Isla Verde — sessions down 4.2%</div>
                <div style={{fontSize: 12, color: 'var(--text-muted)'}}>Cluster cannibalisation across /resorts/ and /destinations/. Audit scheduled.</div>
              </div>
            </div>
            <div style={{display:'flex', gap: 12, alignItems: 'flex-start'}}>
              <span className="status warn" style={{marginTop: 4}}><span className="dot"/></span>
              <div>
                <div style={{color:'var(--text)', fontSize: 13, fontWeight: 500}}>Cebu Clinics — Ahrefs disconnected</div>
                <div style={{fontSize: 12, color: 'var(--text-muted)'}}>Backlink data stale. Reconnect token in Integrations.</div>
              </div>
            </div>
            <div style={{display:'flex', gap: 12, alignItems: 'flex-start'}}>
              <span className="status ok" style={{marginTop: 4}}><span className="dot"/></span>
              <div>
                <div style={{color:'var(--text)', fontSize: 13, fontWeight: 500}}>Pampanga Foods — top-10 +8</div>
                <div style={{fontSize: 12, color: 'var(--text-muted)'}}>Launchpad gaining traction. Promote to Engine review next month.</div>
              </div>
            </div>
          </div>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>Roll-up · top movers</h3><span className="sub" style={{marginLeft:'auto'}}>Last 7 days</span></div>
          <div className="panel-body" style={{display:'flex', flexDirection:'column', gap: 10, fontSize: 13}}>
            {[
              { kw: 'karate near makati', client: 'Karate Nation', from: 12, to: 7 },
              { kw: 'best resorts palawan', client: 'Isla Verde', from: 18, to: 11 },
              { kw: 'family lawyer manila', client: 'Manila Legal', from: 9, to: 5 },
              { kw: 'sourdough delivery makati', client: 'Binondo Bakery', from: 14, to: 9 },
            ].map((m, i) => (
              <div key={i} style={{display:'flex', alignItems:'center', gap: 12, padding: '6px 0', borderBottom: i < 3 ? '1px solid var(--border-light)' : 'none'}}>
                <Icon name="arrowUp" size={12} color="var(--accent)"/>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{m.kw}</div>
                  <div className="mono-label" style={{fontSize: 9}}>{m.client}</div>
                </div>
                <span className="pos-chip top30">{m.from}</span>
                <Icon name="chevR" size={11} color="var(--text-dim)"/>
                <span className="pos-chip top10">{m.to}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>Tier distribution</h3></div>
          <div className="panel-body">
            <HBar items={[
              { label: 'LAUNCH', value: 3, color: 'var(--text-muted)' },
              { label: 'ENGINE', value: 4, color: 'var(--gold)' },
              { label: 'FULL',   value: 1, color: 'var(--accent)' },
            ]} max={5} format={(v) => `${v} client${v === 1 ? '' : 's'}`}/>
            <div style={{marginTop: 24}}>
              <div className="mono-label">Forecast · Q3 2026</div>
              <p style={{fontSize: 13, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.6}}>
                Two Launchpad clients on track to graduate to Engine by August. Capacity opens for one new Full Stack engagement in Q4.
              </p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

window.PortfolioView = PortfolioView;
