/* ============================================================
   CADENCE — Investor Portfolio dashboard
   window.Portfolio
   ============================================================ */
(function () {
  const { useState, useMemo, useEffect } = React;
  const I = window.Icon;
  const F = window.CAD.fmt;
  const C = window.Charts;

  function withdrawMessage(error) {
    switch (error?.message) {
      case 'not_connected': return 'Connect a payout account before withdrawing.';
      case 'no_earnings': return 'You have no earnings to withdraw yet.';
      case 'payouts_not_enabled': return 'Your payout account isn’t ready yet — finish onboarding.';
      case 'stripe_not_configured': return 'Payments are not configured on this server.';
      default: return 'The withdrawal could not be completed.';
    }
  }

  // Real-money earnings from music sales (separate from the play-money balance).
  // Sellers connect a Stripe account and withdraw accrued earnings to their bank.
  function EarningsCard() {
    const [info, setInfo] = useState(null);
    const [busy, setBusy] = useState(false);

    const load = async () => {
      try { setInfo(await window.CadClient.myEarnings()); }
      catch (error) { setInfo({ earningsCents: 0, onboarded: false, stripeAccountId: null, payouts: [] }); }
    };
    useEffect(() => { load(); }, []);
    if (!info) return null;

    const dollars = (info.earningsCents || 0) / 100;

    const onConnect = async () => {
      setBusy(true);
      try {
        const data = await window.CadClient.connectOnboard();
        if (data && data.url) { window.location.assign(data.url); return; }
        setBusy(false);
      } catch (error) {
        window.toast({ kind: 'sell', title: 'Connect failed', desc: error?.message === 'stripe_not_configured' ? 'Payments are not configured on this server.' : 'Could not start payout onboarding.' });
        setBusy(false);
      }
    };

    const onWithdraw = async () => {
      setBusy(true);
      try {
        const data = await window.CadClient.withdraw();
        window.toast({ kind: 'buy', title: 'Withdrawal sent', desc: `${F.money((data.withdrawnCents || 0) / 100, 2)} is on its way to your bank account.` });
        await load();
      } catch (error) {
        window.toast({ kind: 'sell', title: 'Withdraw failed', desc: withdrawMessage(error) });
      } finally {
        setBusy(false);
      }
    };

    return (
      <div className="panel panel-pad fade-up" style={{ marginBottom: 18 }}>
        <div className="row between wrap" style={{ gap: 14, alignItems: 'center' }}>
          <div>
            <div className="row gap6" style={{ fontSize: 12.5, color: 'var(--green)', fontWeight: 600 }}>
              <I.coins style={{ width: 15 }} />Real earnings (from music sales)
            </div>
            <div className="num" style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4 }}>{F.money(dollars, 2)}</div>
            <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>
              {info.onboarded ? 'Available to withdraw to your bank.' : 'Connect a payout account to cash out your earnings.'}
            </div>
          </div>
          <div className="row gap8">
            {info.onboarded ? (
              <button className="btn btn-primary" disabled={busy || dollars <= 0} style={{ opacity: busy || dollars <= 0 ? 0.6 : 1 }} onClick={onWithdraw}>
                {busy ? 'Working…' : 'Withdraw'}
              </button>
            ) : (
              <button className="btn btn-primary" disabled={busy} style={{ opacity: busy ? 0.6 : 1 }} onClick={onConnect}>
                {busy ? 'Working…' : 'Connect payouts'}
              </button>
            )}
          </div>
        </div>
      </div>
    );
  }

  function Portfolio({ go, openSong, holdings, balance, watch }) {
    const [tf, setTf] = useState('3M');
    const value = holdings.reduce((a, h) => a + h.song.price * h.shares, 0);
    const cost = holdings.reduce((a, h) => a + h.cost, 0);
    const pl = value - cost;
    const plPct = (pl / cost) * 100;
    const { portfolio: P } = window.useCad();

    const series = useMemo(() => {
      const map = { '1W': 14, '1M': 30, '3M': 60, 'ALL': 90 };
      const s = P.series.slice(-map[tf]);
      // rescale end to current value
      const scale = value / s[s.length - 1];
      return s.map((x) => +(x * scale).toFixed(2));
    }, [tf, value]);

    // allocation segments by value
    const palette = ['oklch(0.70 0.165 252)', 'oklch(0.755 0.155 158)', 'oklch(0.82 0.11 88)', 'oklch(0.66 0.19 22)', 'oklch(0.62 0.16 300)', 'oklch(0.62 0.14 200)'];
    const alloc = holdings.map((h, i) => ({ label: h.song.title, value: +(((h.song.price * h.shares) / value) * 100).toFixed(1), color: palette[i % palette.length] }));

    const watchSongs = P.watchlist.filter((s) => watch.includes(s.id));

    return (
      <div className="page">
        <div className="row between wrap" style={{ marginBottom: 22, gap: 14 }}>
          <div>
            <h1 className="page-title">Portfolio</h1>
            <div className="page-sub">Your music capital, performance and payouts</div>
          </div>
          <div className="row gap8">
            <button className="btn btn-ghost" onClick={() => go('discover')}><I.discover style={{ width: 15 }} />Discover</button>
            <button className="btn btn-primary"><I.plus style={{ width: 15 }} />Add funds</button>
          </div>
        </div>

        {/* top stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 18 }} className="pf-stats">
          <div className="panel panel-pad fade-up">
            <div className="muted" style={{ fontSize: 12.5 }}>Portfolio value</div>
            <div className="num" style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4 }}>{F.money(value, 2)}</div>
            <div className="mt8"><window.UI.Delta value={plPct} /> <span className="muted" style={{ fontSize: 12 }}>all time</span></div>
          </div>
          <div className="panel panel-pad fade-up" style={{ animationDelay: '50ms' }}>
            <div className="muted" style={{ fontSize: 12.5 }}>Total return</div>
            <div className="num" style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4, color: pl >= 0 ? 'var(--green)' : 'var(--red)' }}>{pl >= 0 ? '+' : ''}{F.money(pl, 2)}</div>
            <div className="muted mt8" style={{ fontSize: 12 }}>on {F.money(cost, 0)} invested</div>
          </div>
          <div className="panel panel-pad fade-up" style={{ animationDelay: '100ms' }}>
            <div className="muted" style={{ fontSize: 12.5 }}>Payouts earned</div>
            <div className="num" style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4, color: 'var(--gold)' }}>{F.money(P.totalPayouts, 2)}</div>
            <div className="muted mt8" style={{ fontSize: 12 }}>across 5 songs</div>
          </div>
          <div className="panel panel-pad fade-up" style={{ animationDelay: '150ms' }}>
            <div className="muted" style={{ fontSize: 12.5 }}>Cash balance</div>
            <div className="num" style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4 }}>{F.money(balance, 2)}</div>
            <div className="muted mt8" style={{ fontSize: 12 }}>buying power</div>
          </div>
        </div>

        {/* real-money earnings + cash-out */}
        <EarningsCard />

        {/* chart + allocation */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 18, marginBottom: 18 }} className="pf-mid">
          <div className="panel">
            <div className="panel-head">
              <div><h3>Portfolio growth</h3><div className="sub num pos">+{F.money(pl, 2)} ({plPct.toFixed(1)}%)</div></div>
              <div className="grow" />
              <div className="seg">{['1W', '1M', '3M', 'ALL'].map((t) => <button key={t} className={tf === t ? 'on' : ''} onClick={() => setTf(t)}>{t}</button>)}</div>
            </div>
            <div style={{ padding: '16px 14px 10px' }}>
              <C.PriceChart data={series} up={pl >= 0} mode="area" height={232} labelFmt={(i, n) => `${n - 1 - i}d ago`} />
            </div>
          </div>
          <div className="panel panel-pad">
            <h3 style={{ margin: '0 0 14px', fontSize: 13, fontWeight: 700 }}>Allocation</h3>
            <div style={{ display: 'grid', placeItems: 'center' }}>
              <C.Donut size={150} thickness={20} segments={alloc} centerLabel={holdings.length} centerSub="songs held" />
            </div>
            <div className="col gap8 mt16">
              {alloc.map((a) => (
                <div key={a.label} className="row gap8" style={{ fontSize: 12.5 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 3, background: a.color, flex: 'none' }}></span>
                  <span className="grow muted" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.label}</span>
                  <span className="num dim">{a.value}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* holdings table */}
        <div className="panel" style={{ marginBottom: 18 }}>
          <div className="panel-head"><h3>Holdings</h3><div className="grow" /><span className="sub">{holdings.length} positions</span></div>
          <div style={{ overflowX: 'auto' }}>
            <table className="tbl">
              <thead><tr>
                <th>Song</th><th className="r">Shares</th><th className="r hide-sm">Avg cost</th><th className="r">Price</th><th className="r">Value</th><th className="r">Return</th><th className="r hide-sm">24h</th>
              </tr></thead>
              <tbody>
                {holdings.map((h) => {
                  const val = h.song.price * h.shares;
                  const cst = h.avgCost * h.shares;
                  const ret = ((val - cst) / cst) * 100;
                  return (
                    <tr key={h.songId} onClick={() => openSong(h.songId)}>
                      <td><div className="row gap12"><window.UI.Cover grad={h.song.coverGrad} size={36} radius={8} /><div><div style={{ fontWeight: 600, fontSize: 13.5 }}>{h.song.title}</div><div className="muted" style={{ fontSize: 11.5 }}>{h.song.artist}</div></div></div></td>
                      <td className="r num">{h.shares.toLocaleString()}</td>
                      <td className="r num dim hide-sm">{F.money(h.avgCost, 2)}</td>
                      <td className="r num">{F.money(h.song.price, 2)}</td>
                      <td className="r num" style={{ fontWeight: 600 }}>{F.money(val, 2)}</td>
                      <td className="r num" style={{ color: ret >= 0 ? 'var(--green)' : 'var(--red)' }}>{ret >= 0 ? '+' : ''}{ret.toFixed(1)}%</td>
                      <td className="r hide-sm"><window.UI.Delta value={h.song.change} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* watchlist + payouts */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }} className="pf-bottom">
          <div className="panel">
            <div className="panel-head"><I.star style={{ width: 16, color: 'var(--gold)' }} /><h3>Watchlist</h3><div className="grow" /><span className="sub">{watchSongs.length}</span></div>
            <div style={{ padding: '4px 18px 12px' }}>
              {watchSongs.length === 0 && <div className="muted" style={{ fontSize: 13, padding: '16px 0' }}>Star songs on the markets to track them here.</div>}
              {watchSongs.map((s) => (
                <div className="feed-item" key={s.id} style={{ cursor: 'pointer' }} onClick={() => openSong(s.id)}>
                  <window.UI.Cover grad={s.coverGrad} size={36} radius={8} />
                  <div className="grow"><div style={{ fontWeight: 600, fontSize: 13.5 }}>{s.title}</div><div className="muted" style={{ fontSize: 11.5 }}>{s.artist}</div></div>
                  <div className="num" style={{ textAlign: 'right' }}><div style={{ fontWeight: 600, fontSize: 13.5 }}>{F.money(s.price, 2)}</div><window.UI.Delta value={s.change} /></div>
                </div>
              ))}
            </div>
          </div>
          <div className="panel">
            <div className="panel-head"><I.coins style={{ width: 16, color: 'var(--gold)' }} /><h3>Revenue payouts</h3><div className="grow" /><span className="sub num pos">{F.money(P.totalPayouts, 2)}</span></div>
            <div style={{ padding: '4px 18px 12px' }}>
              {P.payouts.map((p, i) => (
                <div className="feed-item" key={i}>
                  <div className="feed-dot buy" style={{ background: 'oklch(0.82 0.11 88 / 0.15)', color: 'var(--gold)' }}><I.coins style={{ width: 15 }} /></div>
                  <div className="grow"><div style={{ fontWeight: 600, fontSize: 13.5 }}>{p.song}</div><div className="muted" style={{ fontSize: 11.5 }}>Distribution · {p.date}</div></div>
                  <div className="num pos" style={{ fontWeight: 600, fontSize: 13.5 }}>+{F.money(p.amount, 2)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.Portfolio = Portfolio;
})();
