/* ============================================================
   CADENCE — Artist Studio (analytics dashboard)
   window.ArtistStudio — market-style data on your own catalog.
   (Uploading / catalog management lives on the Upload Music page.)
   ============================================================ */
(function () {
  const { useState, useMemo } = React;
  const I = window.Icon;
  const F = window.CAD.fmt;
  const C = window.Charts;

  function initials(name) {
    const parts = String(name || 'Artist').trim().split(/\s+/).filter(Boolean);
    if (parts.length === 0) return 'AR';
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }

  function StatCard({ k, v, sub, color, delay }) {
    return (
      <div className="panel panel-pad fade-up" style={{ animationDelay: delay + 'ms' }}>
        <div className="muted" style={{ fontSize: 12.5 }}>{k}</div>
        <div className="num" style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.03em', marginTop: 4, color }}>{v}</div>
        <div className="muted mt8" style={{ fontSize: 12 }}>{sub}</div>
      </div>
    );
  }

  function MoverCard({ label, song, openSong }) {
    if (!song) return null;
    return (
      <div className="panel panel-pad" style={{ cursor: 'pointer' }} onClick={() => openSong(song.id)}>
        <div className="muted" style={{ fontSize: 11.5, marginBottom: 8 }}>{label}</div>
        <div className="row gap12">
          <window.UI.Cover grad={song.coverGrad} size={40} radius={8} />
          <div className="grow" style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{song.title}</div>
            <div className="num muted" style={{ fontSize: 12 }}>{F.money(song.price, 2)}</div>
          </div>
          <window.UI.Delta value={song.change} />
        </div>
      </div>
    );
  }

  function ArtistStudio({ go, openSong }) {
    const cad = window.useCad();
    const a = cad.artist || {};
    const me = cad.user || window.CAD.currentUser || {};
    const myLinks = Object.entries(me.links || {}).filter(([, v]) => v);
    const songs = a.songs || [];
    const marketFeed = cad.marketFeed || [];
    const trades = marketFeed.filter((t) => a.id && t.song.artistId === a.id).slice(0, 8);
    const [chartMode, setChartMode] = useState('value'); // 'value' | 'revenue'

    // Aggregate catalog series (market cap over time) + revenue bars.
    const aggSeries = useMemo(() => {
      if (songs.length === 0) return [];
      const len = Math.min(...songs.map((s) => (s.series ? s.series.length : 0)));
      if (!len || !Number.isFinite(len)) return [];
      const out = [];
      for (let i = 0; i < len; i += 1) {
        out.push(Math.round(songs.reduce((sum, s) => sum + (s.series[i] || 0) * (s.totalShares || 0), 0)));
      }
      return out;
    }, [songs]);

    const aggRevBars = useMemo(() => {
      const len = 12;
      const out = new Array(len).fill(0);
      songs.forEach((s) => (s.revBars || []).forEach((v, i) => { if (i < len) out[i] += v; }));
      return out;
    }, [songs]);

    const movers = useMemo(() => {
      if (songs.length === 0) return {};
      const byChange = [...songs].sort((x, y) => y.change - x.change);
      const byVol = [...songs].sort((x, y) => y.vol24 - x.vol24);
      return { gainer: byChange[0], loser: byChange[byChange.length - 1], traded: byVol[0] };
    }, [songs]);

    const aggUp = aggSeries.length > 1 ? aggSeries[aggSeries.length - 1] >= aggSeries[0] : true;

    if (!a.id || songs.length === 0) {
      return (
        <div className="page">
          <h1 className="page-title">Artist Studio</h1>
          <div className="page-sub">Analytics for your catalog</div>
          <div className="panel panel-pad muted" style={{ marginTop: 22, fontSize: 13.5 }}>
            You haven't released any music yet. Head to <a href="#" style={{ color: 'var(--blue-bright)', textDecoration: 'none' }} onClick={(e) => { e.preventDefault(); go('upload'); }}>Upload Music</a> to add your first song, then come back to track how it's performing.
          </div>
        </div>
      );
    }

    return (
      <div className="page">
        <div className="row between wrap" style={{ marginBottom: 22, gap: 14 }}>
          <div className="row gap16">
            <div className="avatar" style={{ width: 56, height: 56, fontSize: 20, ...(me.avatarColor ? { background: me.avatarColor } : {}) }}>{initials(a.name)}</div>
            <div>
              <div className="row gap8"><h1 className="page-title">{a.name}</h1>{a.verified && <I.check style={{ width: 18, color: 'var(--blue-bright)', alignSelf: 'center' }} />}</div>
              <div className="page-sub">{a.handle} · Artist Studio · {songs.length} song{songs.length === 1 ? '' : 's'} · {(a.releases || []).length} release{(a.releases || []).length === 1 ? '' : 's'}</div>
              {me.bio && <div className="muted" style={{ fontSize: 13, marginTop: 6, maxWidth: 520, lineHeight: 1.5 }}>{me.bio}</div>}
              {myLinks.length > 0 && (
                <div className="row gap12 wrap" style={{ marginTop: 8 }}>
                  {myLinks.map(([k, v]) => (
                    <a key={k} href={v} target="_blank" rel="noreferrer" style={{ color: 'var(--blue-bright)', fontSize: 12.5, textDecoration: 'none', textTransform: 'capitalize' }}>{k}</a>
                  ))}
                </div>
              )}
            </div>
          </div>
          <div className="row gap8" style={{ alignSelf: 'flex-start' }}>
            <button className="btn btn-ghost" onClick={() => go('profile')}><I.settings style={{ width: 15 }} />Edit profile</button>
            <button className="btn btn-buy" onClick={() => go('upload')}><I.upload style={{ width: 15 }} />Upload music</button>
          </div>
        </div>

        {/* stat cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 18 }} className="pf-stats">
          <StatCard k="Total revenue" v={F.compact(a.revenue)} sub="all songs" color="var(--green)" delay={0} />
          <StatCard k="Active investors" v={a.investors.toLocaleString()} sub="across catalog" color="var(--blue-bright)" delay={50} />
          <StatCard k="Catalog market cap" v={F.compact(a.mcap)} sub="shares outstanding" color="var(--text)" delay={100} />
          <StatCard k="This month payout" v={F.money(a.monthlyPayout, 0)} sub="to shareholders" color="var(--gold)" delay={150} />
        </div>

        {/* aggregate performance */}
        <div className="panel" style={{ marginBottom: 18 }}>
          <div className="panel-head">
            <div><h3>Catalog performance</h3><div className="sub">{chartMode === 'value' ? 'Combined market cap over time' : 'Revenue, last 12 months'}</div></div>
            <div className="grow" />
            <div className="seg">
              <button className={chartMode === 'value' ? 'on' : ''} onClick={() => setChartMode('value')}>Value</button>
              <button className={chartMode === 'revenue' ? 'on' : ''} onClick={() => setChartMode('revenue')}>Revenue</button>
            </div>
          </div>
          <div style={{ padding: '16px 14px 12px' }}>
            {chartMode === 'value'
              ? <C.PriceChart data={aggSeries} up={aggUp} mode="area" height={240} labelFmt={(i, n) => `${n - 1 - i}d ago`} />
              : <C.RevenueBars data={aggRevBars} height={220} labels={['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May']} />}
          </div>
        </div>

        {/* top movers */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginBottom: 18 }} className="pf-stats">
          <MoverCard label="Top gainer · 24h" song={movers.gainer} openSong={openSong} />
          <MoverCard label="Biggest drop · 24h" song={movers.loser} openSong={openSong} />
          <MoverCard label="Most traded · 24h" song={movers.traded} openSong={openSong} />
        </div>

        {/* per-song market table + activity */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18 }} className="pf-bottom">
          <div className="panel">
            <div className="panel-head"><h3>Your songs</h3><div className="grow" /><span className="sub">{songs.length} live</span></div>
            <div style={{ overflowX: 'auto' }}>
              <table className="tbl">
                <thead><tr><th>Song</th><th className="r">Price</th><th className="r">24h</th><th className="r hide-sm">Volume</th><th className="r hide-sm">Mcap</th><th className="r">Revenue</th><th className="r" style={{ width: 90 }}>Trend</th></tr></thead>
                <tbody>
                  {songs.map((s) => (
                    <tr key={s.id} onClick={() => openSong(s.id)}>
                      <td><div className="row gap12"><window.UI.Cover grad={s.coverGrad} size={34} radius={7} /><div><div style={{ fontWeight: 600, fontSize: 13 }}>{s.title}</div><div className="muted" style={{ fontSize: 11.5 }}>{s.release ? s.release.title : s.genreLabel}</div></div></div></td>
                      <td className="r num">{F.money(s.price, 2)}</td>
                      <td className="r"><window.UI.Delta value={s.change} /></td>
                      <td className="r num dim hide-sm">{F.compact(s.vol24)}</td>
                      <td className="r num dim hide-sm">{F.compact(s.mcap)}</td>
                      <td className="r num">{F.compact(s.revenue)}</td>
                      <td className="r" style={{ width: 90 }}><div style={{ width: 80, marginLeft: 'auto' }}><C.Sparkline data={s.series} up={s.change >= 0} height={28} /></div></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head"><h3>Recent investor activity</h3><div className="grow" /><span className="live-dot"></span></div>
            <div style={{ padding: '4px 18px 12px' }}>
              {trades.length === 0 && <div className="muted" style={{ fontSize: 12.5, padding: '10px 0' }}>No recent trades on your songs yet.</div>}
              {trades.map((t, i) => (
                <div className="feed-item" key={i}>
                  <div className={'feed-dot ' + t.side}>{t.side === 'buy' ? 'B' : 'S'}</div>
                  <div className="grow"><div style={{ fontSize: 13, fontWeight: 600 }}>@{t.user} {t.side === 'buy' ? 'bought' : 'sold'} <span className="num">{t.qty}</span></div><div className="muted" style={{ fontSize: 11.5 }}>{t.song.title} · {t.ago}m ago</div></div>
                  <div className="num" style={{ fontSize: 13, fontWeight: 600 }}>{F.money(t.qty * t.px, 0)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.ArtistStudio = ArtistStudio;
})();
