// Portfolio, Watchlist, Stocks screener — wired to live API

// ─── Portfolio ───────────────────────────────────────────────────────────────
window.PortfolioPage = ({ currency, setPage, setSelectedStock }) => {
  const [token, setToken] = React.useState(() => localStorage.getItem('jastocks-user-token') || '');
  const [inputToken, setInputToken] = React.useState('');
  const [portfolios, setPortfolios] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  async function fetchPortfolios(t) {
    setLoading(true);
    setError(null);
    try {
      // Route through our server proxy — never call Stacks directly from the browser (CORS)
      const res = await fetch('/api/user/portfolios', {
        headers: { 'x-user-token': t },
      });
      if (!res.ok) throw new Error(`Error ${res.status}`);
      const data = await res.json();
      setPortfolios(Array.isArray(data) ? data : [data]);
    } catch (e) {
      setError(e.message);
    }
    setLoading(false);
  }

  const connect = async () => {
    const t = inputToken.trim();
    if (!t) return;
    localStorage.setItem('jastocks-user-token', t);
    setToken(t);
    await fetchPortfolios(t);
  };

  React.useEffect(() => {
    if (token) fetchPortfolios(token);
  }, []);

  const disconnect = () => {
    localStorage.removeItem('jastocks-user-token');
    setToken('');
    setPortfolios(null);
    setInputToken('');
  };

  // ── Not connected ──
  if (!token || (!portfolios && !loading)) {
    return (
      <div className="page">
        <div className="page-header">
          <div>
            <h1 className="page-title">Portfolio</h1>
            <div className="page-subtitle">Connect your JaStocks account to track your holdings</div>
          </div>
        </div>
        <div style={{ maxWidth: 480, margin: '60px auto', textAlign: 'center' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 16,
            background: 'var(--bg-2)', border: '1px solid var(--border)',
            display: 'grid', placeItems: 'center', margin: '0 auto 20px',
          }}>
            <Icons.Portfolio/>
          </div>
          <h2 style={{ margin: '0 0 8px', fontSize: 20, fontWeight: 700 }}>Connect your account</h2>
          <p style={{ color: 'var(--text-3)', marginBottom: 28, lineHeight: 1.6 }}>
            Create a personal API token on{' '}
            <a href="https://stacksja.com/developers" target="_blank" style={{ color: 'var(--accent)' }}>stacksja.com/developers</a>
            {' '}to see your live portfolio, holdings, and projected dividend income.
          </p>
          <div style={{ display: 'flex', gap: 8 }}>
            <input
              value={inputToken}
              onChange={e => setInputToken(e.target.value)}
              placeholder="stk_your_personal_token"
              style={{
                flex: 1, padding: '10px 14px', background: 'var(--bg-2)',
                border: '1px solid var(--border)', borderRadius: 8,
                color: 'var(--text)', fontSize: 13, fontFamily: 'Geist Mono, monospace',
              }}
              onKeyDown={e => e.key === 'Enter' && connect()}
            />
            <button className="btn primary" onClick={connect} disabled={!inputToken.trim()}>
              Connect
            </button>
          </div>
          {error && <div style={{ color: 'var(--down)', fontSize: 12, marginTop: 10 }}>{error}</div>}
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="page">
        <div className="page-header"><div><h1 className="page-title">Portfolio</h1></div></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {[...Array(4)].map((_, i) => <Skeleton key={i} h={80}/>)}
        </div>
      </div>
    );
  }

  // ── Connected — show portfolios ──
  const { bySym } = JASTOCKS_DATA;
  const allHoldings = (portfolios || []).flatMap(p => (p.holdings || []).map(h => ({ ...h, portfolio: p.name })));

  const totalValue = (portfolios || []).reduce((s, p) => s + (p.total_value || 0), 0);
  const totalInvested = (portfolios || []).reduce((s, p) => s + (p.total_invested || 0), 0);
  const totalGain = totalValue - totalInvested;
  const totalGainPct = totalInvested > 0 ? (totalGain / totalInvested) * 100 : 0;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Portfolio</h1>
          <div className="page-subtitle">{portfolios?.length} portfolio{portfolios?.length !== 1 ? 's' : ''} · Live data</div>
        </div>
        <div className="flex gap-2">
          <button className="btn ghost" onClick={disconnect} style={{ color: 'var(--text-3)' }}>Disconnect</button>
        </div>
      </div>

      <div className="grid g-4 mb-4">
        <div className="metric">
          <div className="label">Portfolio value</div>
          <div className="value">{fmtMoney(totalValue, currency)}</div>
          <div className={`delta ${totalGain >= 0 ? 'up' : 'down'}`}>
            {totalGain >= 0 ? '▲' : '▼'} {fmtMoney(Math.abs(totalGain), currency)} ({fmtPct(totalGainPct)})
          </div>
        </div>
        <div className="metric">
          <div className="label">Total invested</div>
          <div className="value">{fmtMoney(totalInvested, currency)}</div>
          <div className="delta text-3">{allHoldings.length} positions</div>
        </div>
        <div className="metric">
          <div className="label">Day change</div>
          <div className="value" style={{ fontSize: 20 }}>
            {fmtMoney(allHoldings.reduce((s, h) => s + (h.day_change_pct || 0) * (h.market_value || 0) / 100, 0), currency)}
          </div>
          <div className="delta text-3">Across all holdings</div>
        </div>
        <div className="metric">
          <div className="label">Portfolios</div>
          <div className="value">{portfolios?.length}</div>
          <div className="delta text-3">Active accounts</div>
        </div>
      </div>

      {(portfolios || []).map((p, pi) => (
        <div key={pi} className="card mb-4">
          <div className="card-header">
            <div className="card-title">{p.name}</div>
            <div className="flex gap-3 items-center">
              <span className="mono up" style={{ fontSize: 12 }}>
                {fmtPct(p.total_gain_pct || 0)}
              </span>
              <span className="text-3 mono" style={{ fontSize: 12 }}>{fmtMoney(p.total_value || 0, currency)}</span>
            </div>
          </div>
          <table className="data portfolio-table">
            <thead>
              <tr>
                <th>Symbol</th>
                <th style={{textAlign:'right'}}>Shares</th>
                <th style={{textAlign:'right'}}>Avg cost</th>
                <th style={{textAlign:'right'}}>Price</th>
                <th style={{textAlign:'right'}}>Value</th>
                <th style={{textAlign:'right'}}>Gain/loss</th>
                <th style={{textAlign:'right'}}>Day Δ</th>
              </tr>
            </thead>
            <tbody>
              {(p.holdings || []).map(h => {
                const sym = h.symbol || h.sym;
                return (
                  <tr key={sym} style={{ cursor: 'pointer' }}
                      onClick={() => { window.setSelectedStock && window.setSelectedStock(sym); }}>
                    <td>
                      <div className="sym-cell">
                        <SymBadge sym={sym} size={28}/>
                        <div>
                          <div style={{ fontWeight: 600 }}>{sym}</div>
                          <div className="text-3" style={{ fontSize: 11 }}>{bySym[sym]?.name || sym}</div>
                        </div>
                      </div>
                    </td>
                    <td className="mono" style={{ textAlign: 'right' }}>{fmtNum(h.shares)}</td>
                    <td className="mono text-2" style={{ textAlign: 'right' }}>{fmtPrice(h.buy_price || 0, currency)}</td>
                    <td className="mono" style={{ textAlign: 'right' }}>{fmtPrice(h.current_price || 0, currency)}</td>
                    <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{fmtMoney(h.market_value || 0, currency)}</td>
                    <td style={{ textAlign: 'right' }}>
                      <div className={`mono ${(h.gain_loss || 0) >= 0 ? 'up' : 'down'}`} style={{ fontWeight: 600 }}>
                        {(h.gain_loss || 0) >= 0 ? '+' : ''}{fmtMoney(h.gain_loss || 0, currency)}
                      </div>
                      <div className={`mono ${(h.gain_loss_pct || 0) >= 0 ? 'up' : 'down'}`} style={{ fontSize: 11 }}>
                        {fmtPct(h.gain_loss_pct || 0)}
                      </div>
                    </td>
                    <td className="mono" style={{ textAlign: 'right' }}>
                      {h.day_change_pct != null
                        ? <span className={h.day_change_pct >= 0 ? 'up' : 'down'}>{fmtPct(h.day_change_pct)}</span>
                        : <span className="text-3">—</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
};

// ─── Watchlist (localStorage-based) ──────────────────────────────────────────
window.WatchlistPage = ({ currency, setPage, setSelectedStock, livePrices }) => {
  const [symbols, setSymbols] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('jastocks-watchlist') || '[]'); } catch { return []; }
  });
  const [adding, setAdding] = React.useState('');
  const [addError, setAddError] = React.useState('');
  const [sparks, setSparks] = React.useState({}); // real 30-day closing prices keyed by sym
  const { bySym, dividends } = JASTOCKS_DATA;

  const save = (syms) => {
    setSymbols(syms);
    localStorage.setItem('jastocks-watchlist', JSON.stringify(syms));
  };

  // Fetch real 30-day history for each watchlist symbol
  React.useEffect(() => {
    symbols.forEach(sym => {
      if (sparks[sym]) return; // already loaded
      JaAPI.history(sym, 30).then(res => {
        const prices = JaAPI.transformHistory(res).map(h => h.c).filter(c => c > 0);
        if (prices.length > 1) setSparks(prev => ({ ...prev, [sym]: prices }));
      }).catch(() => {});
    });
  }, [symbols]);

  const addStock = async () => {
    const q = adding.trim().toUpperCase();
    if (!q) return;
    if (symbols.includes(q)) { setAddError('Already in watchlist'); return; }
    // Validate via API
    try {
      const res = await JaAPI.quote(q);
      const sym = res.symbol || q;
      save([...symbols, sym]);
      setAdding('');
      setAddError('');
    } catch {
      // Try local lookup
      if (bySym[q]) {
        save([...symbols, q]);
        setAdding('');
        setAddError('');
      } else {
        setAddError('Stock not found');
      }
    }
  };

  const remove = (sym) => save(symbols.filter(s => s !== sym));

  const rows = symbols.map(sym => {
    const stock = bySym[sym];
    const lp = livePrices[sym];
    const price = lp ? lp.price : (stock?.price || 0);
    const change = lp ? lp.change : (stock?.change || 0);
    const changePct = lp ? lp.changePct : (stock?.changePct || 0);
    const nextDiv = dividends.filter(d => d.sym === sym && d.exDate >= JASTOCKS_DATA.today).sort((a, b) => a.exDate - b.exDate)[0];
    return { sym, stock, price, change, changePct, nextDiv, spark: sparks[sym] || null };
  });

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Watchlist</h1>
          <div className="page-subtitle">{symbols.length} stocks · Live prices</div>
        </div>
        <div className="flex gap-2 items-center">
          <input
            value={adding}
            onChange={e => { setAdding(e.target.value); setAddError(''); }}
            onKeyDown={e => e.key === 'Enter' && addStock()}
            placeholder="Add symbol (e.g. GK)"
            style={{
              padding: '7px 12px', background: 'var(--bg-2)',
              border: `1px solid ${addError ? 'var(--down)' : 'var(--border)'}`,
              borderRadius: 7, color: 'var(--text)', fontSize: 13, width: 180,
              fontFamily: 'Geist Mono, monospace',
            }}
          />
          <button className="btn primary" onClick={addStock}><Icons.Plus/> Add</button>
        </div>
      </div>
      {addError && <div style={{ color: 'var(--down)', fontSize: 12, marginBottom: 12 }}>{addError}</div>}

      {symbols.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--text-3)' }}>
          <div style={{ marginBottom: 12 }}><Icons.Watchlist/></div>
          <div style={{ fontWeight: 600, marginBottom: 6 }}>Your watchlist is empty</div>
          <div style={{ fontSize: 13 }}>Add stocks using the field above to track live prices and dividends</div>
        </div>
      ) : (
        <div className="card">
          <table className="data watchlist-table">
            <thead>
              <tr>
                <th>Symbol</th>
                <th style={{textAlign:'right'}}>Price</th>
                <th style={{textAlign:'right'}}>Day change</th>
                <th>Trend (30d)</th>
                <th style={{textAlign:'right'}}>Yield</th>
                <th>Next dividend</th>
                <th style={{textAlign:'right'}}>Volume</th>
                <th style={{width:40}}></th>
              </tr>
            </thead>
            <tbody>
              {rows.map(({ sym, stock, price, change, changePct, nextDiv, spark }) => (
                <tr key={sym} onClick={() => { setSelectedStock(sym); setPage('stock'); }} style={{ cursor: 'pointer' }}>
                  <td>
                    <div className="sym-cell">
                      <SymBadge sym={sym} size={30}/>
                      <div>
                        <div style={{ fontWeight: 600 }}>{sym}</div>
                        <div className="text-3" style={{ fontSize: 11 }}>{stock?.name || sym} · {stock?.sector || ''}</div>
                      </div>
                    </div>
                  </td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{fmtPrice(price, currency)}</td>
                  <td style={{ textAlign: 'right' }}>
                    <div className={`mono ${change >= 0 ? 'up' : 'down'}`} style={{ fontWeight: 600 }}>
                      {change >= 0 ? '+' : ''}{fmtPrice(Math.abs(change), currency)}
                    </div>
                    <div className={`mono ${change >= 0 ? 'up' : 'down'}`} style={{ fontSize: 11 }}>{fmtPct(changePct)}</div>
                  </td>
                  <td>
                    {spark
                      ? <Sparkline values={spark} width={130} height={32}/>
                      : <span className="text-3 mono" style={{ fontSize: 11 }}>—</span>}
                  </td>
                  <td className="mono" style={{ textAlign: 'right', color: 'var(--accent)', fontWeight: 600 }}>
                    {stock?.yield > 0 ? `${stock.yield.toFixed(2)}%` : '—'}
                  </td>
                  <td>
                    {nextDiv ? (
                      <div className="flex items-center gap-2">
                        <span className="tag ex">Ex {fmtDate(nextDiv.exDate)}</span>
                        <span className="mono text-2" style={{ fontSize: 12 }}>
                          {nextDiv.currency === 'USD' ? 'US$' : 'J$'}{nextDiv.amount.toFixed(4)}
                        </span>
                      </div>
                    ) : <span className="text-3">—</span>}
                  </td>
                  <td className="mono text-2" style={{ textAlign: 'right' }}>
                    {stock ? `${((stock.volume || 0) / 1000).toFixed(0)}k` : '—'}
                  </td>
                  <td>
                    <button className="icon-btn" style={{ width: 28, height: 28 }}
                            onClick={e => { e.stopPropagation(); remove(sym); }}>
                      <Icons.X/>
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// ─── Stocks screener ──────────────────────────────────────────────────────────
window.StocksPage = ({ currency, setPage, setSelectedStock, livePrices }) => {
  const { stocks } = JASTOCKS_DATA;
  const [sort, setSort] = React.useState('yield');
  const [market, setMarket] = React.useState('all');
  const [q, setQ] = React.useState('');
  const [sector, setSector] = React.useState('all');

  // Apply live prices
  const liveStocks = React.useMemo(() => stocks.map(s => {
    const lp = livePrices[s.sym];
    return lp ? { ...s, price: lp.price, change: lp.change, changePct: lp.changePct } : s;
  }), [stocks, livePrices]);

  const sectors = React.useMemo(() => {
    const s = new Set(liveStocks.map(s => s.sector).filter(s => s && s !== 'Other'));
    return ['all', ...Array.from(s).sort()];
  }, [liveStocks]);

  const filtered = liveStocks
    .filter(s => market === 'all' || s.market.toLowerCase() === market)
    .filter(s => sector === 'all' || s.sector === sector)
    .filter(s => !q || s.sym.toLowerCase().includes(q.toLowerCase()) || s.name.toLowerCase().includes(q.toLowerCase()))
    .sort((a, b) => {
      if (sort === 'yield')   return b.yield - a.yield;
      if (sort === 'change')  return b.changePct - a.changePct;
      if (sort === 'price')   return b.price - a.price;
      if (sort === 'volume')  return b.volume - a.volume;
      if (sort === 'pe')      return (a.pe || 999) - (b.pe || 999);
      return 0;
    });

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Stocks</h1>
          <div className="page-subtitle">All {stocks.length} stocks listed on the JSE · Live prices</div>
        </div>
        <div className="flex gap-2 items-center">
          <div className="search" style={{ maxWidth: 260 }}>
            <Icons.Search/>
            <input placeholder="Search…" value={q} onChange={e => setQ(e.target.value)}/>
          </div>
          <div className="seg">
            <button className={market==='all'?'active':''} onClick={()=>setMarket('all')}>All</button>
            <button className={market==='main'?'active':''} onClick={()=>setMarket('main')}>Main</button>
            <button className={market==='junior'?'active':''} onClick={()=>setMarket('junior')}>Junior</button>
          </div>
        </div>
      </div>

      {/* Sector filter */}
      <div className="flex gap-2 mb-4" style={{ flexWrap: 'wrap' }}>
        {sectors.map(s => (
          <div key={s} className={`chip ${sector === s ? 'active' : ''}`} onClick={() => setSector(s)}>
            {s === 'all' ? 'All sectors' : s}
          </div>
        ))}
      </div>

      <div className="card">
        <div className="card-header">
          <div className="card-title">Showing {filtered.length} of {stocks.length} stocks</div>
          <div className="seg">
            <button className={sort==='yield'?'active':''} onClick={()=>setSort('yield')}>Yield</button>
            <button className={sort==='change'?'active':''} onClick={()=>setSort('change')}>% Change</button>
            <button className={sort==='volume'?'active':''} onClick={()=>setSort('volume')}>Volume</button>
            <button className={sort==='pe'?'active':''} onClick={()=>setSort('pe')}>P/E</button>
            <button className={sort==='price'?'active':''} onClick={()=>setSort('price')}>Price</button>
          </div>
        </div>
        <table className="data stocks-table">
          <thead>
            <tr>
              <th>Symbol</th>
              <th>Sector</th>
              <th style={{textAlign:'right'}}>Price</th>
              <th style={{textAlign:'right'}}>Change</th>
              <th style={{textAlign:'right'}}>P/E</th>
              <th style={{textAlign:'right'}}>Yield</th>
              <th style={{textAlign:'right'}}>Volume</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(s => (
              <tr key={s.sym} onClick={() => { setSelectedStock(s.sym); setPage('stock'); }} style={{ cursor: 'pointer' }}>
                <td>
                  <div className="sym-cell">
                    <SymBadge sym={s.sym} size={28}/>
                    <div>
                      <div style={{ fontWeight: 600 }}>{s.sym}</div>
                      <div className="text-3" style={{ fontSize: 11 }}>{s.name}</div>
                    </div>
                  </div>
                </td>
                <td><span className="tag">{s.sector}</span></td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{fmtPrice(s.price, currency)}</td>
                <td style={{ textAlign: 'right' }}><ChangeBadge change={s.change} pct={s.changePct}/></td>
                <td className="mono text-2" style={{ textAlign: 'right' }}>{s.pe ? s.pe.toFixed(1) : '—'}</td>
                <td className="mono" style={{ textAlign: 'right', color: s.yield > 0 ? 'var(--accent)' : 'var(--text-3)', fontWeight: s.yield > 0 ? 600 : 400 }}>
                  {s.yield > 0 ? `${s.yield.toFixed(2)}%` : '—'}
                </td>
                <td className="mono text-2" style={{ textAlign: 'right' }}>{fmtNum(s.volume)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};
