// EsploraBeat — Beat catalog tab
// Owns: BeatFilterRail, BeatGrid, BeatCard, Waveform, StickyPlayer, BuyModal
// Sort options + active filter pills are owned by parent (Esplora.jsx); beat catalog
// just renders its rail + grid + active player.

const BeatIcons = window.SonaraIcons;
const { useState: useStateBeat, useMemo: useMemoBeat } = React;

// Reusable Geo filter for the rail (free-text location + quick chips + "near me" radius)
function BeatGeoFilter() {
  const [mode, setMode] = useStateBeat("any"); // "any" | "near" | "country" | "region" | "custom"
  const [query, setQuery] = useStateBeat("");
  const [radius, setRadius] = useStateBeat(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">
        <BeatIcons.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 && <BeatIcons.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>
  );
}

// ---------- mock data ----------
const BEAT_GENRES   = ["Trap", "Drill", "Hip-Hop", "R&B", "Afro", "Pop", "House", "Reggaeton", "UK Garage"];
const BEAT_MOODS    = ["Dark", "Hype", "Chill", "Emo", "Aggressive", "Romantic", "Dreamy", "Bouncy"];
const BEAT_KEYS     = ["A min", "A maj", "B min", "C# min", "D min", "E min", "F maj", "F# min", "G min", "G# min"];
const BEAT_PRODS    = ["Yoshi", "Marco V.", "DK Beats", "Riva", "Nemo", "Kyo", "Astra", "Frey", "Lume", "Tide"];

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

function makeBeats() {
  const r = beatRand(7);
  const titles = [
    "Notte Lunga","Asfalto","Skyline","Vetro Rotto","Mare Nero","Polvere d'Oro","Riflesso","Ferro Caldo",
    "Anima Lenta","Frequenza 88","Capo Bianco","Vento Sud","Eco","Tempesta","Velluto","Magma","Onda Lunga",
    "Carbone","Vela","Solstizio","Treno Notturno","Luce Bassa","Pioggia 4am","Nebbia Soft"
  ];
  return titles.map((title, i) => {
    const bpm = 80 + Math.floor(r() * 80);
    const exclusive = r() > 0.55;
    const lease = [29, 39, 49, 59, 79][Math.floor(r() * 5)];
    const exclusivePrice = lease * (8 + Math.floor(r() * 16));
    return {
      id: i + 1, title,
      producer: BEAT_PRODS[i % BEAT_PRODS.length],
      verified: r() > 0.45,
      genre: BEAT_GENRES[i % BEAT_GENRES.length],
      mood: BEAT_MOODS[i % BEAT_MOODS.length],
      bpm, key: BEAT_KEYS[i % BEAT_KEYS.length],
      duration: `${Math.floor(2 + r() * 2)}:${String(Math.floor(r() * 60)).padStart(2, "0")}`,
      lease, exclusive, exclusivePrice,
      plays: Math.floor(800 + r() * 12000),
      art: i % 6,
      stems: r() > 0.5,
      peaks: Array.from({ length: 64 }, (_, k) => {
        const base = 0.25 + 0.5 * Math.abs(Math.sin(i * 0.7 + k * 0.31));
        return Math.min(1, base + (r() - 0.5) * 0.3);
      }),
    };
  });
}

const ALL_BEATS = makeBeats();

// ---------- waveform ----------
function Waveform({ peaks, progress = 0, playing = false, compact = false }) {
  const h = compact ? 28 : 44;
  return (
    <div className={`wf ${compact ? "compact" : ""} ${playing ? "playing" : ""}`} style={{ height: h }}>
      {peaks.map((p, i) => (
        <span key={i} className={`wf-bar ${i / peaks.length < progress ? "filled" : ""}`}
              style={{ height: `${Math.round(p * 100)}%` }}/>
      ))}
    </div>
  );
}

// ---------- filter rail (Beat-specific) ----------
function BeatFilterRail() {
  const [genre, setGenre]   = useStateBeat("Tutti");
  const [mood, setMood]     = useStateBeat("Tutti");
  const [bpmMin, setBpmMin] = useStateBeat(60);
  const [bpmMax, setBpmMax] = useStateBeat(180);
  const [licenseType, setLicenseType] = useStateBeat("any");
  const [stemsOnly, setStemsOnly] = useStateBeat(false);

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

      <window.FilterSection title="Genere" defaultOpen={true} count={genre !== "Tutti" ? 1 : 0}>
        <div className="chip-row">
          {["Tutti", ...BEAT_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>
      </window.FilterSection>

      <window.FilterSection title="BPM" defaultOpen={false}>
        <div className="filter-label" style={{padding:0, textTransform:"none", letterSpacing:0, fontWeight:500}}><span className="muted">{bpmMin}–{bpmMax}</span></div>
        <div className="range-track">
          <span className="range-fill" style={{ left: `${(bpmMin - 60) / 1.2}%`, right: `${100 - (bpmMax - 60) / 1.2}%` }}/>
          <span className="range-thumb" style={{ left: `${(bpmMin - 60) / 1.2}%` }}/>
          <span className="range-thumb" style={{ left: `${(bpmMax - 60) / 1.2}%` }}/>
        </div>
        <div className="range-tags">
          <span className="range-tag">60</span><span className="range-tag">90</span>
          <span className="range-tag">120</span><span className="range-tag">150</span>
          <span className="range-tag">180</span>
        </div>
      </window.FilterSection>

      <window.FilterSection title="Tonalità" defaultOpen={false}>
        <div className="chip-row tight">
          {["Tutte","A min","C# min","D min","F maj","G min"].map(k => (
            <button key={k} className="chip">{k}</button>
          ))}
        </div>
      </window.FilterSection>

      <window.FilterSection title="Mood" defaultOpen={false} count={mood !== "Tutti" ? 1 : 0}>
        <div className="chip-row tight">
          {["Tutti", ...BEAT_MOODS.slice(0, 5)].map(m => (
            <button key={m} className={`chip ${mood === m ? "active" : ""}`} onClick={() => setMood(m)}>{m}</button>
          ))}
        </div>
      </window.FilterSection>

      <window.FilterSection title="Prezzo" defaultOpen={false}>
        <div className="range-track">
          <span className="range-fill" style={{ left: "8%", right: "30%" }}/>
          <span className="range-thumb" style={{ left: "8%" }}/>
          <span className="range-thumb" style={{ left: "70%" }}/>
        </div>
        <div className="range-tags"><span className="range-tag">€10</span><span className="range-tag">€80</span><span className="range-tag">€200</span></div>
      </window.FilterSection>

      <window.FilterSection title="Licenza" defaultOpen={false} count={licenseType !== "any" ? 1 : 0}>
        <div className="lic-stack">
          {[
            ["any", "Tutte le licenze", "Mostra qualsiasi tipologia", null],
            ["lease", "Non-esclusiva", "Lease — uso condiviso", "da €25"],
            ["excl", "Esclusiva", "Diritti completi, beat ritirato", "da €180"],
          ].map(([v, t, s, p]) => (
            <button key={v}
              className={`lic-opt ${licenseType === v ? "active" : ""}`}
              onClick={() => setLicenseType(v)}>
              <span className="lic-opt-radio"></span>
              <span className="lic-opt-body">
                <span className="lic-opt-t">{t}</span>
                <span className="lic-opt-s">{s}</span>
                {p && <span className="lic-opt-price">{p}</span>}
              </span>
            </button>
          ))}
        </div>
      </window.FilterSection>

      <window.FilterSection title="Opzioni" defaultOpen={false}>
        <label className="check-row">
          <input type="checkbox" checked={stemsOnly} onChange={e => setStemsOnly(e.target.checked)}/>
          <span className="check"></span>
          <span>Solo con stems</span>
        </label>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Producer verificato</span>
        </label>
        <label className="check-row">
          <input type="checkbox"/>
          <span className="check"></span>
          <span>Sotto i €40</span>
        </label>
      </window.FilterSection>

      <window.FilterSection title="Località" defaultOpen={false}>
        <BeatGeoFilter/>
      </window.FilterSection>

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

// ---------- beat card ----------
function BeatCard({ beat, isPlaying, onPlay, onLike, onBuy, hero, liked }) {
  const arts = ["art-a","art-b","art-c","art-d","art-e","art-f"];
  return (
    <div className={`beat-card ${hero ? "hero" : ""} ${isPlaying ? "playing" : ""}`}>
      <div className={`beat-art ${arts[beat.art]}`} onClick={onPlay}>
        <div className="beat-art-ovl">
          <button className="beat-play">
            {isPlaying ? (
              <svg width="22" height="22" 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>
            ) : <BeatIcons.play size={22}/>}
          </button>
          <span className="beat-duration">{beat.duration}</span>
        </div>
        {beat.exclusive && <span className="beat-flag-excl">Esclusiva disp.</span>}
        <span className="beat-art-bpm">{beat.bpm} BPM</span>
      </div>

      <div className="beat-body">
        <div className="beat-row1">
          <a className="beat-title" href={(window.ESPLORA_DETAIL_BASE || "") + "Beat.html"} style={{ color: "inherit", textDecoration: "none" }}>{beat.title}</a>
          <button className={`beat-fav ${liked ? "active" : ""}`} onClick={onLike} title="Salva nei preferiti">
            <BeatIcons.star size={16} filled={liked}/>
          </button>
        </div>
        <div className="beat-prod">
          <span className="av">{beat.producer.charAt(0)}</span>
          <span>{beat.producer}</span>
          {beat.verified && <span className="ver-dot" title="Verified"><BeatIcons.verified size={11}/></span>}
        </div>

        <Waveform peaks={beat.peaks} progress={isPlaying ? 0.34 : 0} playing={isPlaying} compact={!hero}/>

        <div className="beat-tags">
          <span className="tag">{beat.genre}</span>
          <span className="tag">{beat.mood}</span>
          <span className="tag muted">{beat.key}</span>
          {beat.stems && <span className="tag stems">+ Stems</span>}
        </div>

        <div className="beat-foot">
          <div className="beat-prices">
            <span className="price-lease">€{beat.lease}<span className="lbl">licenza</span></span>
            {beat.exclusive && (
              <span className="price-excl">€{beat.exclusivePrice}<span className="lbl">esclusiva</span></span>
            )}
          </div>
          <button className="beat-buy" onClick={onBuy}>
            Acquista <BeatIcons.arrowRight size={13}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- BuyModal ----------
function BuyModal({ beat, onClose }) {
  const [tier, setTier] = useStateBeat("lease");
  const tiers = [
    { id: "lease", t: "Licenza non-esclusiva", p: beat.lease,
      desc: "Stream illimitato, monetizzazione fino a 50k stream. MP3 + WAV.",
      includes: ["MP3 + WAV", "Streaming + monetizzazione", "Crediti producer obbligatori"] },
    { id: "lease-plus", t: "Lease + Stems", p: beat.lease + 30,
      desc: "Tutto della licenza, più gli stems separati per mix custom.",
      includes: ["MP3 + WAV + Stems separati", "Streaming + monetizzazione", "Mixaggio personalizzabile"] },
    { id: "excl", t: "Esclusiva", p: beat.exclusivePrice,
      desc: "Diritti esclusivi. Il beat viene rimosso dal catalogo entro 24h. Solo 18+.",
      includes: ["Tutti i file + stems", "Diritti esclusivi a vita", "Contratto firmato digitalmente", "Rimozione catalogo entro 24h"],
      flag: "Solo 18+" },
  ];
  const sel = tiers.find(t => t.id === tier);

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="buy-modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><BeatIcons.close size={16}/></button>
        <div className="buy-head">
          <div className="buy-art art-c"><BeatIcons.waveform size={28}/></div>
          <div>
            <div className="buy-eyebrow">Acquisto licenza</div>
            <div className="buy-title">{beat.title}</div>
            <div className="buy-prod">
              <span>di {beat.producer}</span>
              {beat.verified && <BeatIcons.verified size={12}/>}
              <span className="dot"/>
              <span>{beat.bpm} BPM · {beat.key} · {beat.genre}</span>
            </div>
          </div>
        </div>
        <div className="buy-section">
          <div className="buy-section-t">Scegli la licenza</div>
          <div className="buy-tiers">
            {tiers.map(t => (
              <button key={t.id} className={`buy-tier ${tier === t.id ? "active" : ""} ${t.id === "excl" ? "excl" : ""}`} onClick={() => setTier(t.id)}>
                <div className="buy-tier-head">
                  <div className="t">{t.t}</div>
                  <div className="p">€{t.p}</div>
                </div>
                <div className="d">{t.desc}</div>
                {t.flag && <span className="tier-flag">{t.flag}</span>}
              </button>
            ))}
          </div>
        </div>
        <div className="buy-includes">
          <div className="buy-section-t">Cosa ricevi</div>
          <ul>
            {sel.includes.map(it => (
              <li key={it}><span className="bullet"><BeatIcons.check size={12}/></span>{it}</li>
            ))}
          </ul>
        </div>
        {tier === "excl" && (
          <div className="buy-warning">
            <span className="ic"><BeatIcons.shield size={14}/></span>
            <div>
              <div className="t">Contratto digitale richiesto</div>
              <div className="s">Allo step successivo firmerai il contratto di cessione esclusiva (SES). Verifica età 18+ richiesta.</div>
            </div>
          </div>
        )}
        <div className="buy-pay">
          <div className="buy-pay-method">
            <div className="buy-section-t">Metodo</div>
            <div className="pay-row">
              <button className="pay-opt active">
                <BeatIcons.coins size={14}/>
                <span>Wallet · €25,00</span>
                <span className="pay-bal">disponibile</span>
              </button>
              <button className="pay-opt">
                <span className="cc">VISA</span>
                <span>•••• 4242</span>
              </button>
              <button className="pay-opt ghost">+ Aggiungi metodo</button>
            </div>
          </div>
          <div className="buy-summary">
            <div className="row"><span>Prezzo</span><span>€{sel.p}</span></div>
            <div className="row muted"><span>Saldo wallet usato</span><span>−€25,00</span></div>
            <div className="row total"><span>Da pagare</span><span>€{Math.max(0, sel.p - 25)}</span></div>
            <a href="Ordine.html" className="cta-buy">
              {tier === "excl" ? "Vai al contratto →" : "Conferma acquisto →"}
            </a>
            <div className="legal">Pagamento sicuro. Beat pronti: download immediato. Esclusive: contratto + verifica.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- StickyPlayer ----------
function StickyPlayer({ beat, playing, onToggle, onClose, style = "expanded" }) {
  if (!beat) return null;
  const arts = ["art-a","art-b","art-c","art-d","art-e","art-f"];
  return (
    <div className={`sticky-player ${style}`}>
      <div className={`sp-art ${arts[beat.art]}`}><BeatIcons.waveform size={20}/></div>
      <div className="sp-meta">
        <div className="sp-title">{beat.title}</div>
        <div className="sp-prod">{beat.producer} · {beat.bpm} BPM · {beat.key}</div>
      </div>
      <div className="sp-controls">
        <button className="sp-ctrl"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="19 20 9 12 19 4 19 20"/><line x1="5" y1="19" x2="5" y2="5"/></svg></button>
        <button className="sp-play" onClick={onToggle}>
          {playing ? (
            <svg width="20" height="20" 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>
          ) : <BeatIcons.play size={20}/>}
        </button>
        <button className="sp-ctrl"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 4 15 12 5 20 5 4"/><line x1="19" y1="5" x2="19" y2="19"/></svg></button>
      </div>
      {style === "expanded" && (
        <div className="sp-track">
          <span className="sp-time">1:14</span>
          <Waveform peaks={beat.peaks} progress={0.34} playing={playing} compact/>
          <span className="sp-time">{beat.duration}</span>
        </div>
      )}
      <div className="sp-actions">
        <button className="sp-ctrl" title="Salva"><BeatIcons.star size={16}/></button>
        <a href={(window.ESPLORA_DETAIL_BASE || "") + "Beat.html"} className="sp-buy">Acquista €{beat.lease}</a>
        <button className="sp-ctrl" onClick={onClose} title="Chiudi"><BeatIcons.close size={14}/></button>
      </div>
    </div>
  );
}

// ---------- BeatCatalog ----------
function BeatCatalog({ playerStyle = "expanded", cardStyle = "standard" }) {
  const [playing, setPlaying] = useStateBeat({ id: null, on: false });
  const [liked, setLiked] = useStateBeat(new Set([3, 7, 12]));
  const [buying, setBuying] = useStateBeat(null);

  const playBeat = (b) => setPlaying(p => p.id === b.id ? { id: b.id, on: !p.on } : { id: b.id, on: true });
  const toggleLike = (id) => setLiked(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });

  const beats = ALL_BEATS;
  const playingBeat = beats.find(b => b.id === playing.id);

  return (
    <>
      <div className="esplora-body">
        <BeatFilterRail/>
        <div className="catalog">
          <div className="catalog-grid">
            {beats.map(b => (
              <BeatCard key={b.id}
                beat={b}
                hero={cardStyle === "hero"}
                liked={liked.has(b.id)}
                isPlaying={playing.id === b.id && playing.on}
                onPlay={() => playBeat(b)}
                onLike={() => toggleLike(b.id)}
                onBuy={() => setBuying(b)}
              />
            ))}
          </div>
          <div className="catalog-foot">
            <button className="btn-load-more">Carica altri 24 beat</button>
          </div>
        </div>
      </div>

      {playingBeat && (
        <StickyPlayer
          beat={playingBeat}
          playing={playing.on}
          onToggle={() => setPlaying(p => ({ ...p, on: !p.on }))}
          onClose={() => setPlaying({ id: null, on: false })}
          style={playerStyle}
        />
      )}
      {buying && <BuyModal beat={buying} onClose={() => setBuying(null)}/>}
    </>
  );
}

window.BeatCatalog = BeatCatalog;
window.ALL_BEATS = ALL_BEATS;
window.BEAT_COUNT = ALL_BEATS.length;
