// SONARA — EsploraArtisti
// Shared artist directory used by Artist / Producer / Manager Esplora.
// Reuses the .prod-card visual language (same shell, different data).
// Manager gets an extra "Invita nel roster" CTA when window.openInviteModal exists.

const ArtIcons = window.SonaraIcons;
const { useState: useStateArt } = React;

/* ─── Data ───────────────────────────────────────────────────────── */

const ART_GENRES = ["Trap", "Drill", "Hip-Hop", "R&B", "Pop", "Indie", "Cantautorato", "Electronic", "Afro"];
const ART_CITIES = ["Milano", "Roma", "Napoli", "Torino", "Bologna", "Firenze", "Bari", "Palermo", "Verona", "Genova", "Catania", "Brescia"];
const ART_NAMES = [
  "Aïda Low", "Theo Marini", "Simone Caruso", "Noah Miles", "Vale Frey", "Kai Russo",
  "Mia Bertolino", "Yari Khan", "Luca Bianchi", "Martina Rey", "Giada Verdi", "Edo Palma",
  "Kaya Low", "Nora Vento", "Lume", "Selva", "Otto Pace", "Cielo R.",
  "Vela", "Petra K.", "Olmo", "Riva G.", "Tess", "Magma",
];
const SIG_TITLES = [
  "Senza Te", "Notte Lunga", "Marble", "Vento del Sud", "Aria di Marzo", "Bianco Sporco",
  "Caduta libera", "Mezzanotte", "Mira", "Asfalto", "Quartiere", "Resta qui",
];
const ART_LOOKING = [
  ["manager", "Cerca manager"],
  ["featuring", "Aperto featuring"],
  ["producer", "Cerca producer"],
  ["mix", "Cerca mix/master"],
];

function artRand(seed) { let s = seed; return () => (s = (s * 9301 + 49297) % 233280) / 233280; }

function makeArtists() {
  const r = artRand(31);
  return ART_NAMES.map((name, i) => {
    const verified = r() > 0.45;
    const active = r() > 0.30;
    const followers = Math.floor(180 + r() * 18000);
    const plays = Math.floor(2000 + r() * 120000);
    const collabs = Math.floor(0 + r() * 22);
    const rating = collabs > 0 ? Math.round((4.3 + r() * 0.7) * 10) / 10 : null;
    const ratings = collabs;
    const age = 16 + Math.floor(r() * 18);
    const looking = ART_LOOKING.filter(() => r() > 0.55).map(([id]) => id);
    if (looking.length === 0 && r() > 0.5) looking.push("manager");
    const tracks = 2 + Math.floor(r() * 5); // 2-6 tracks
    return {
      id: i + 1,
      name,
      handle: "@" + name.toLowerCase().replace(/[^a-z0-9]/g, ""),
      init: name.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase(),
      art: i % 6,
      cover: i % 6,
      city: ART_CITIES[i % ART_CITIES.length],
      age,
      genres: [ART_GENRES[i % ART_GENRES.length], ART_GENRES[(i + 4) % ART_GENRES.length]],
      verified, active,
      followers, plays, collabs, rating, ratings, tracks,
      looking,
      bioSnippet: [
        "Voce graffiata, scrittura tagliente. Lavoro su singoli per la prima campagna seria.",
        "Cantautore alt-pop, EP in lavorazione. Cerco producer per beat melodici.",
        "R&B contemporaneo. Già un sync moda, sto chiudendo il primo album.",
        "Trap-drill di scuola romana. 200k+ stream cumulati sui due singoli.",
        "Indie con derive elettroniche. Headliner emergente per club 200–500.",
        "Folk acustico, voce cristallina. Live regolari nel circuito veneto.",
      ][i % 6],
      sigTitle: SIG_TITLES[i % SIG_TITLES.length],
      sigDuration: ["3:24", "2:58", "3:12", "2:42", "3:51", "3:08"][i % 6],
      peaks: Array.from({ length: 56 }, (_, k) => {
        const base = 0.32 + 0.48 * Math.abs(Math.sin(i * 1.1 + k * 0.31));
        return Math.min(1, base + (r() - 0.5) * 0.25);
      }),
    };
  });
}

const ALL_ARTISTS = makeArtists();

/* ─── Filter Rail ─────────────────────────────────────────────────── */

function ArtistsFilterRail() {
  const [genre, setGenre] = useStateArt("Tutti");
  const [lookingFilter, setLookingFilter] = useStateArt("any");
  const FS = window.FilterSection;

  return (
    <aside className="filter-rail">
      <div className="filter-rail-head">
        <span className="t">Filtri artisti</span>
        <button className="filter-clear">Pulisci</button>
      </div>

      <FS title="Genere principale" defaultOpen={true} count={genre !== "Tutti" ? 1 : 0}>
        <div className="chip-row">
          {["Tutti", ...ART_GENRES.slice(0, 6)].map(g => (
            <button key={g} className={`chip ${genre === g ? "active" : ""}`} onClick={() => setGenre(g)}>{g}</button>
          ))}
          <button className="chip ghost">+ altri</button>
        </div>
      </FS>

      <FS title="Sta cercando" defaultOpen={true} count={lookingFilter !== "any" ? 1 : 0}>
        <div className="chip-row">
          {[["any", "Tutti"], ["manager", "Manager"], ["producer", "Producer"], ["featuring", "Featuring"], ["mix", "Mix/Master"]].map(([v, l]) => (
            <button key={v} className={`chip ${lookingFilter === v ? "active" : ""}`} onClick={() => setLookingFilter(v)}>{l}</button>
          ))}
        </div>
      </FS>

      <FS title="Città" defaultOpen={false}>
        <div className="chip-row tight">
          {["Tutte", "Milano", "Roma", "Napoli", "Torino", "Bologna"].map(c => (
            <button key={c} className="chip">{c}</button>
          ))}
          <button className="chip ghost">+ altre</button>
        </div>
      </FS>

      <FS title="Età" defaultOpen={false}>
        <div className="seg">
          {[["any", "Tutte"], ["young", "16-21"], ["mid", "22-28"], ["adult", "29+"]].map(([v, l]) => (
            <button key={v} className={`seg-btn ${v === "any" ? "active" : ""}`}>{l}</button>
          ))}
        </div>
      </FS>

      <FS title="Traction (ascolti 30gg)" defaultOpen={false}>
        <div className="seg">
          {[["any", "Tutti"], ["1k", "≥1k"], ["10k", "≥10k"], ["50k", "≥50k"]].map(([v, l]) => (
            <button key={v} className={`seg-btn ${v === "any" ? "active" : ""}`}>{l}</button>
          ))}
        </div>
      </FS>

      <FS title="Disponibilità" defaultOpen={true}>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Aperti a collaborazioni</span>
        </label>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Verified</span>
        </label>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Attivi (ultimi 30gg)</span>
        </label>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Senza manager</span>
        </label>
      </FS>

      <div className="filter-saved">
        <span className="t"><ArtIcons.star size={13}/> Salva ricerca</span>
        <span className="s">Notifica se entrano nuovi artisti che matchano</span>
        <button className="btn-ghost-sm">Salva</button>
      </div>
    </aside>
  );
}

/* ─── Waveform ─────────────────────────────────────────────────────── */

function ArtMiniWave({ peaks, playing }) {
  return (
    <div className={`pwf ${playing ? "hovering" : ""}`}>
      {peaks.map((p, i) => (
        <span key={i} className="pwf-bar"
              style={{ height: `${Math.round(p * 100)}%`, animationDelay: `${i * 18}ms` }}/>
      ))}
    </div>
  );
}

/* ─── Artist Card ─────────────────────────────────────────────────── */

function ArtistEsploraCard({ a, playingId, setPlayingId }) {
  const arts = ["art-a","art-b","art-c","art-d","art-e","art-f"];
  const playing = playingId === a.id;
  const togglePlay = (e) => { e.stopPropagation(); e.preventDefault(); setPlayingId(playing ? null : a.id); };
  const onInvite = (e) => { e.stopPropagation(); e.preventDefault(); window.openInviteModal && window.openInviteModal({
    id: a.id, name: a.name, handle: a.handle, init: a.init, city: a.city,
    looking: a.looking.includes("manager"), hasManager: false,
  }); };
  const looking = a.looking[0];

  return (
    <article className={`prod-card art-card ${playing ? "hovering" : ""}`}>
      <div className={`prod-cover ${arts[a.cover]}`}>
        <div className="prod-cover-shade"/>

        {/* Looking-for badge top-left */}
        {looking && (
          <span className={`art-looking-tag ${looking}`}>
            {looking === "manager" && <ArtIcons.users size={11}/>}
            {looking === "featuring" && <ArtIcons.music size={11}/>}
            {looking === "producer" && <ArtIcons.mixer size={11}/>}
            {looking === "mix" && <ArtIcons.equalizer size={11}/>}
            {ART_LOOKING.find(l => l[0] === looking)[1]}
          </span>
        )}
        {a.verified && (
          <span className="art-cover-verify" title="Verificato"><ArtIcons.verified size={12}/></span>
        )}

        {/* Bottom row: signature track meta + play */}
        <div className="prod-cover-bot">
          <div className="prod-cover-l">
            <div className="prod-cover-eyebrow">Showcase</div>
            <div className="prod-cover-title">{a.sigTitle} · {a.sigDuration}</div>
          </div>
          <button className="prod-cover-play" onClick={togglePlay} title={playing ? "Pausa" : "Anteprima"}>
            {playing ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
            ) : <ArtIcons.play size={14}/>}
          </button>
        </div>
        <ArtMiniWave peaks={a.peaks} playing={playing}/>
      </div>

      <div className="prod-body">
        <div className="prod-id">
          <span className={`prod-av ${arts[a.art]}`}>{a.init}</span>
          <div className="prod-id-meta">
            <div className="prod-name-row">
              <a className="prod-name" href={(window.ESPLORA_ARTIST_BASE || "") + "Artista.html#id=a" + a.id}
                 style={{ color: "inherit", textDecoration: "none" }}>{a.name}</a>
              {a.verified && <span className="ver-dot"><ArtIcons.verified size={11}/></span>}
            </div>
            <div className="prod-city">
              <ArtIcons.pin size={11}/>
              <span>{a.city} · {a.age} anni</span>
            </div>
          </div>
          {a.rating ? (
            <div className="prod-rating">
              <ArtIcons.star size={12} filled/>
              <strong>{a.rating.toFixed(1)}</strong>
              <span className="muted">({a.ratings})</span>
            </div>
          ) : (
            <div className="prod-rating">
              <span className="muted" style={{ fontSize: 11 }}>nuovo</span>
            </div>
          )}
        </div>

        <div className="prod-genres">
          {a.genres.map(g => <span key={g} className="tag">{g}</span>)}
        </div>

        <p className="art-bio">{a.bioSnippet}</p>

        <div className="prod-stats">
          <div className="prod-stat">
            <div className="v">{a.followers >= 1000 ? (a.followers / 1000).toFixed(1) + "k" : a.followers}</div>
            <div className="l">follower</div>
          </div>
          <div className="prod-stat">
            <div className="v">{a.plays >= 1000 ? Math.round(a.plays / 1000) + "k" : a.plays}</div>
            <div className="l">ascolti</div>
          </div>
          <div className="prod-stat">
            <div className="v">{a.tracks}</div>
            <div className="l">tracce</div>
          </div>
          <div className="prod-stat">
            <div className="v">{a.collabs}</div>
            <div className="l">collab</div>
          </div>
        </div>

        <div className="prod-foot art-foot">
          <a className="prod-cta-secondary" href={(window.ESPLORA_MSG_BASE || "") + "Messaggi.html"}><ArtIcons.message size={13}/> Messaggio</a>
          {window.openInviteModal ? (
            <button className="prod-cta primary art-invite-btn" onClick={onInvite}>
              <ArtIcons.users size={13}/> Invita nel roster
            </button>
          ) : (
            <a className="prod-cta" href={(window.ESPLORA_ARTIST_BASE || "") + "Artista.html#id=a" + a.id}>
              Vedi profilo <ArtIcons.arrowRight size={13}/>
            </a>
          )}
        </div>
      </div>
    </article>
  );
}

/* ─── Catalog ─────────────────────────────────────────────────────── */

function ArtistCatalog() {
  const [playingId, setPlayingId] = useStateArt(null);
  return (
    <div className="esplora-body">
      <ArtistsFilterRail/>
      <div className="catalog">
        <div className="prod-grid art-grid">
          {ALL_ARTISTS.map(a => (
            <ArtistEsploraCard key={a.id} a={a} playingId={playingId} setPlayingId={setPlayingId}/>
          ))}
        </div>
        <div className="catalog-foot">
          <button className="btn-load-more">Carica altri 24 artisti</button>
        </div>
      </div>
    </div>
  );
}

window.ArtistCatalog = ArtistCatalog;
window.ArtistsFilterRail = ArtistsFilterRail;
window.ALL_ARTISTS = ALL_ARTISTS;
window.ART_COUNT = ALL_ARTISTS.length;
