// EsploraProducer — Producer directory tab
// Owns: ProducerFilterRail, ProducerGrid, ProducerCard
// Producer card focus: Foto + waveform di un beat signature in autoplay on hover

const ProdIcons = window.SonaraIcons;
const { useState: useStateProd } = React;

function ProdGeoFilter() {
  const [mode, setMode] = useStateProd("any");
  const [query, setQuery] = useStateProd("");
  const [radius, setRadius] = useStateProd(50);
  const chips = [
    { id: "any", label: "Ovunque" },
    { id: "near", label: "Vicino a me", icon: true },
    { id: "country", label: "Italia" },
  ];
  return (
    <div className="geo-combo">
      <div className="geo-input-wrap">
        <ProdIcons.pin size={14}/>
        <input
          className="geo-input"
          type="text"
          placeholder="Città, regione, provincia…"
          value={query}
          onChange={e => { setQuery(e.target.value); setMode("custom"); }}
        />
        {query && (
          <button className="geo-clear" onClick={() => { setQuery(""); setMode("any"); }} title="Pulisci">×</button>
        )}
      </div>
      <div className="geo-chips">
        {chips.map(c => (
          <button key={c.id}
            className={`geo-chip ${mode === c.id ? "active" : ""}`}
            onClick={() => { setMode(c.id); setQuery(""); }}>
            {c.icon && <ProdIcons.pin size={11}/>}
            {c.label}
          </button>
        ))}
      </div>
      {mode === "near" && (
        <div className="geo-radius">
          <div className="geo-radius-head">
            <span>Raggio</span>
            <span className="geo-radius-val">{radius} km</span>
          </div>
          <input
            className="geo-radius-slider"
            type="range" min="5" max="500" step="5"
            value={radius}
            onChange={e => setRadius(Number(e.target.value))}
          />
        </div>
      )}
    </div>
  );
}

const PROD_GENRES = ["Trap", "Drill", "Hip-Hop", "R&B", "Afro", "Pop", "House", "Reggaeton"];
const PROD_CITIES = ["Milano", "Roma", "Napoli", "Torino", "Bologna", "Firenze", "Bari", "Palermo", "Verona", "Catania", "Brescia", "Genova"];
const PROD_NAMES = [
  "Yoshi", "Marco V.", "DK Beats", "Riva", "Nemo", "Kyo",
  "Astra", "Frey", "Lume", "Tide", "Vento Sud", "Plata",
  "Echo Lab", "Notturno", "Sirio", "Onyx", "Mira", "Polvere",
  "Nove", "Tessera", "Magma", "Zenith", "Sonar", "Velvet"
];

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

function makeProducers() {
  const r = prodRand(13);
  return PROD_NAMES.map((name, i) => {
    const verified = r() > 0.35;
    const topRated = r() > 0.65;
    const responseHrs = [1, 2, 4, 6, 12, 24][Math.floor(r() * 6)];
    const projects = Math.floor(40 + r() * 280);
    const rating = Math.round((4.4 + r() * 0.6) * 10) / 10;
    const reviews = Math.floor(15 + r() * 220);
    const fromPrice = [29, 39, 49, 59, 79][Math.floor(r() * 5)];
    const open = r() > 0.18;
    const studio = r() > 0.65;
    return {
      id: i + 1,
      name,
      art: i % 6,
      cover: i % 6,
      city: PROD_CITIES[i % PROD_CITIES.length],
      genres: [PROD_GENRES[i % PROD_GENRES.length], PROD_GENRES[(i + 3) % PROD_GENRES.length]],
      verified, topRated,
      responseHrs,
      projects,
      rating,
      reviews,
      fromPrice,
      open,
      studio,
      // signature beat
      sigTitle: ["Notte Lunga","Skyline","Asfalto","Vetro","Magma","Carbone"][i % 6],
      sigBpm: 80 + Math.floor(r() * 80),
      peaks: Array.from({ length: 56 }, (_, k) => {
        const base = 0.3 + 0.5 * Math.abs(Math.sin(i * 0.9 + k * 0.27));
        return Math.min(1, base + (r() - 0.5) * 0.25);
      }),
    };
  });
}

const ALL_PRODUCERS = makeProducers();

// ---------- filter rail (Producer) ----------
function ProducerFilterRail() {
  const [genre, setGenre] = useStateProd("Tutti");
  const [response, setResponse] = useStateProd("any");
  const FS = window.FilterSection;

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

      <FS title="Genere principale" defaultOpen={true} count={genre !== "Tutti" ? 1 : 0}>
        <div className="chip-row">
          {["Tutti", ...PROD_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="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="Rating minimo" defaultOpen={false}>
        <div className="seg">
          {[["any","Tutti"],["4","4★+"],["45","4.5★+"]].map(([v, l]) => (
            <button key={v} className={`seg-btn ${v === "any" ? "active" : ""}`}>{l}</button>
          ))}
        </div>
      </FS>

      <FS title="Response time" defaultOpen={false} count={response !== "any" ? 1 : 0}>
        <div className="seg">
          {[["any","Tutti"],["1h","≤1h"],["6h","≤6h"],["24h","≤24h"]].map(([v, l]) => (
            <button key={v} className={`seg-btn ${response === v ? "active" : ""}`} onClick={() => setResponse(v)}>{l}</button>
          ))}
        </div>
      </FS>

      <FS title="Disponibilità" defaultOpen={true}>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Aperti a ordini</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>Top Rated</span>
        </label>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Risposta ≤6h</span>
        </label>
      </FS>

      <FS title="Località" defaultOpen={false}>
        <ProdGeoFilter/>
      </FS>

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

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

// ---------- producer card ----------
function ProducerCard({ p }) {
  const [hovering, setHovering] = useStateProd(false);
  const arts = ["art-a","art-b","art-c","art-d","art-e","art-f"];
  return (
    <article className={`prod-card ${hovering ? "hovering" : ""}`}
             onMouseEnter={() => setHovering(true)}
             onMouseLeave={() => setHovering(false)}>
      <div className={`prod-cover ${arts[p.cover]}`}>
        <div className="prod-cover-shade"/>
        {p.topRated && <span className="prod-badge top">★ Top Rated</span>}
        {p.studio && <span className="prod-badge studio">🎚 Studio</span>}
        {!p.open && <span className="prod-badge vac">In pausa</span>}
        <div className="prod-cover-bot">
          <div className="prod-cover-l">
            <div className="prod-cover-eyebrow">Signature</div>
            <div className="prod-cover-title">{p.sigTitle} · {p.sigBpm} BPM</div>
          </div>
          <button className="prod-cover-play" title="Play preview">
            {hovering ? (
              <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>
            ) : <ProdIcons.play size={14}/>}
          </button>
        </div>
        <ProdMiniWave peaks={p.peaks} hovering={hovering}/>
      </div>

      <div className="prod-body">
        <div className="prod-id">
          <span className={`prod-av ${arts[p.art]}`}>{p.name.charAt(0)}</span>
          <div className="prod-id-meta">
            <div className="prod-name-row">
              <a className="prod-name" href={(window.ESPLORA_DETAIL_BASE || "") + "Producer.html"} style={{ color: "inherit", textDecoration: "none" }}>{p.name}</a>
              {p.verified && <span className="ver-dot"><ProdIcons.verified size={11}/></span>}
            </div>
            <div className="prod-city">
              <ProdIcons.pin size={11}/>
              <span>{p.city}</span>
            </div>
          </div>
          <div className="prod-rating">
            <ProdIcons.star size={12} filled/>
            <strong>{p.rating.toFixed(1)}</strong>
            <span className="muted">({p.reviews})</span>
          </div>
        </div>

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

        <div className="prod-stats">
          <div className="prod-stat">
            <div className="v">{p.projects}</div>
            <div className="l">progetti</div>
          </div>
          <div className="prod-stat">
            <div className="v">{p.responseHrs}h</div>
            <div className="l">risposta</div>
          </div>
          <div className="prod-stat">
            <div className="v">€{p.fromPrice}</div>
            <div className="l">da</div>
          </div>
        </div>

        <div className="prod-foot">
          <a className="prod-cta-secondary" href={(window.ESPLORA_DETAIL_BASE || "") + "Messaggi.html"}><ProdIcons.message size={13}/> Messaggio</a>
          <a className="prod-cta" href={(window.ESPLORA_DETAIL_BASE || "") + "Producer.html"}>Vedi profilo <ProdIcons.arrowRight size={13}/></a>
        </div>
      </div>
    </article>
  );
}

function ProducerCatalog() {
  const producers = ALL_PRODUCERS;
  return (
    <div className="esplora-body">
      <ProducerFilterRail/>
      <div className="catalog">
        <div className="prod-grid">
          {producers.map(p => <ProducerCard key={p.id} p={p}/>)}
        </div>
        <div className="catalog-foot">
          <button className="btn-load-more">Carica altri 24 producer</button>
        </div>
      </div>
    </div>
  );
}

window.ProducerCatalog = ProducerCatalog;
window.ProducerFilterRail = ProducerFilterRail;
window.ALL_PRODUCERS = ALL_PRODUCERS;
window.PROD_COUNT = ALL_PRODUCERS.length;
