/* ============================================================
   CADENCE — Marketplace / Discover view
   window.Marketplace
   ============================================================ */
(function () {
  const { useState, useMemo } = React;
  const I = window.Icon;
  const F = window.CAD.fmt;

  const SORTS = [
    { id: 'trending', label: 'Trending', icon: 'flame' },
    { id: 'gainers', label: 'Top Gainers', icon: 'arrowUp' },
    { id: 'volume', label: 'Most Traded', icon: 'chart' },
    { id: 'revenue', label: 'Top Revenue', icon: 'coins' },
    { id: 'newest', label: 'Newest', icon: 'bolt' },
  ];

  function sortSongs(songs, sort) {
    const a = [...songs];
    switch (sort) {
      case 'gainers': return a.sort((x, y) => y.change - x.change);
      case 'volume': return a.sort((x, y) => y.vol24 - x.vol24);
      case 'revenue': return a.sort((x, y) => y.revenue - x.revenue);
      case 'newest': return a.sort((x, y) => y.year - x.year || y.mcap - x.mcap);
      default: return a.sort((x, y) => (y.change * 0.6 + y.vol24 / 10000) - (x.change * 0.6 + x.vol24 / 10000));
    }
  }

  function Marketplace({ go, openSong, playSong, playingId, query, watch, onWatch }) {
    const [sort, setSort] = useState('trending');
    const [genre, setGenre] = useState('all');
    const { songs: all, genres } = window.useCad();

    // Prefer the seeded breakout, but fall back to the top 24h mover so the hero
    // never depends on a specific song existing (and never crashes if empty).
    const featured = all.find((s) => s.id === 'satellite') || [...all].sort((a, b) => b.change - a.change)[0] || null;

    const filtered = useMemo(() => {
      let list = all;
      if (genre !== 'all') list = list.filter((s) => s.genre === genre);
      if (query) {
        const q = query.toLowerCase();
        list = list.filter((s) => s.title.toLowerCase().includes(q) || s.artist.toLowerCase().includes(q) || s.genreLabel.toLowerCase().includes(q));
      }
      return sortSongs(list, sort);
    }, [sort, genre, query]);

    const movers = useMemo(() => [...all].sort((a, b) => b.change - a.change), [all]);

    return (
      <div className="page">
        {/* hero */}
        {!query && featured && (
          <div className="hero fade-up" style={{ marginBottom: 26 }}>
            <div className="glowblob" style={{ width: 280, height: 280, right: -40, top: -80, background: 'var(--blue)' }} />
            <div className="glowblob" style={{ width: 220, height: 220, right: 180, bottom: -120, background: 'var(--green)' }} />
            <window.UI.Cover grad={featured.coverGrad} size={148} radius={16} style={{ flex: 'none', boxShadow: 'var(--shadow-2)' }} />
            <div style={{ position: 'relative', flex: 1, minWidth: 0 }}>
              <div className="row gap8" style={{ marginBottom: 10 }}>
                <span className="chip" style={{ background: 'var(--green-tint)', color: 'var(--green-bright)', borderColor: 'transparent', cursor: 'default' }}><I.flame style={{ width: 13 }} />Breaking out</span>
                <span className="tag">{featured.genreLabel}</span>
              </div>
              <h1 style={{ fontSize: 34, fontWeight: 800, letterSpacing: '-0.04em', margin: 0 }}>{featured.title}</h1>
              <div className="dim" style={{ fontSize: 15, marginTop: 4 }}>by {featured.artist} · {featured.holders.toLocaleString()} investors hold shares</div>
              <div className="row gap24 mt20 wrap">
                <div><div className="muted" style={{ fontSize: 12 }}>Share price</div><div className="num" style={{ fontSize: 24, fontWeight: 600 }}>{F.money(featured.price, 2)} <window.UI.Delta value={featured.change} /></div></div>
                <div><div className="muted" style={{ fontSize: 12 }}>Market cap</div><div className="num" style={{ fontSize: 24, fontWeight: 600 }}>{F.compact(featured.mcap)}</div></div>
                <div><div className="muted" style={{ fontSize: 12 }}>Est. yield</div><div className="num pos" style={{ fontSize: 24, fontWeight: 600 }}>{featured.yield}%</div></div>
                <div className="row gap8" style={{ marginLeft: 'auto' }}>
                  <button className="btn btn-ghost" onClick={() => playSong(featured.id)}><I.play style={{ width: 14 }} />Preview</button>
                  <button className="btn btn-buy" onClick={() => openSong(featured.id)}>Trade shares<I.arrowRight /></button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* movers strip */}
        {!query && (
          <div className="panel fade-up" style={{ marginBottom: 22, animationDelay: '60ms', overflow: 'hidden' }}>
            <div className="row" style={{ overflowX: 'auto', padding: '12px 8px' }}>
              {movers.map((s) => (
                <div key={s.id} className="row gap8" onClick={() => openSong(s.id)}
                  style={{ padding: '6px 16px', borderRight: '1px solid var(--border-soft)', cursor: 'pointer', flex: 'none' }}>
                  <window.UI.Cover grad={s.coverGrad} size={30} radius={6} />
                  <div>
                    <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap' }}>{s.title}</div>
                    <div className="num" style={{ fontSize: 11, color: s.change >= 0 ? 'var(--green)' : 'var(--red)' }}>
                      {F.money(s.price, 2)} · {s.change >= 0 ? '+' : ''}{s.change.toFixed(1)}%
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="row between wrap" style={{ marginBottom: 18, gap: 14 }}>
          <div>
            <h1 className="page-title">{query ? `Results for “${query}”` : 'Music Genres'}</h1>
            <div className="page-sub">{filtered.length} songs · live share prices update in real time</div>
          </div>
          <div className="seg">
            {SORTS.map((s) => (
              <button key={s.id} className={sort === s.id ? 'on' : ''} onClick={() => setSort(s.id)}>{s.label}</button>
            ))}
          </div>
        </div>

        {/* genre chips */}
        <div className="row gap8 wrap" style={{ marginBottom: 20 }}>
          <span className={'chip' + (genre === 'all' ? ' active' : '')} onClick={() => setGenre('all')}>All genres</span>
          {Object.entries(genres).map(([k, g]) => (
            <span key={k} className={'chip' + (genre === k ? ' active' : '')} onClick={() => setGenre(k)}>{g.label}</span>
          ))}
        </div>

        <div className="grid-cards">
          {filtered.map((s, i) => (
            <window.UI.SongCard key={s.id} song={s} onOpen={openSong} onPlay={playSong} playingId={playingId} delay={i * 35} />
          ))}
        </div>
        {filtered.length === 0 && (
          <div className="panel panel-pad" style={{ textAlign: 'center', color: 'var(--text-mute)', padding: 48 }}>
            No songs match your search.
          </div>
        )}
      </div>
    );
  }

  window.Marketplace = Marketplace;
})();
