// EsploraServizi — Services catalog tab
// Owns: ServiziFilterRail, ServiziGrid, ServizioCard
// Service card focus: "Cosa include" bullet list visible, with "from €X"

const SvcIcons = window.SonaraIcons;
const { useState: useStateSvc } = React;

function SvcGeoFilter() {
  const [mode, setMode] = useStateSvc("any");
  const [query, setQuery] = useStateSvc("");
  const [radius, setRadius] = useStateSvc(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">
        <SvcIcons.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 && <SvcIcons.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 SVC_CATEGORIES = [
  { id: "mix", label: "Mix", desc: "Mix stereo di singolo brano" },
  { id: "master", label: "Master", desc: "Mastering di brano già mixato" },
  { id: "mix-master", label: "Mix + Master", desc: "Combo (≈70% degli ordini reali)" },
  { id: "vocal", label: "Vocal production", desc: "Recording + tuning + editing voce" },
  { id: "custom", label: "Custom production", desc: "Beat su brief dell'artista" },
  { id: "topline", label: "Topline / Songwriting", desc: "Melodia + testo" },
  { id: "sound", label: "Sound design", desc: "FX, atmosphere, transitions" },
  { id: "altro", label: "Altro", desc: "Free-form" },
];

const SVC_PRODS = ["Marco V.", "Yoshi", "DK Beats", "Riva", "Nemo", "Kyo", "Astra", "Frey", "Lume", "Tide", "Vento", "Plata"];
const SVC_CITIES = ["Milano", "Roma", "Napoli", "Torino", "Bologna", "Firenze", "Bari", "Catania", "Verona", "Brescia"];

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

function makeServizi() {
  const r = svcRand(11);
  const titles = [
    "Mix professionale di singolo trap/drill",
    "Mastering radio-ready 24h",
    "Mix + Master combo per singolo",
    "Vocal production completa con tuning",
    "Beat custom su brief con 2 revisioni",
    "Topline + testo per singolo pop urban",
    "Sound design FX & transitions per album",
    "Mix vocal-forward stile R&B",
    "Master loudness Spotify/YouTube",
    "Mix + Master con 3 revisioni",
    "Vocal recording session in studio",
    "Custom beat con stems separati inclusi",
    "Topline melodica per producer",
    "Atmosphere & risers per progetto",
    "Stems mixing per remix",
    "Master analog warm",
    "Pitch correction trasparente",
    "Beat brief Trap/Drill con 4 revisioni",
  ];
  const cats = ["mix","master","mix-master","vocal","custom","topline","sound","mix","master","mix-master","vocal","custom","topline","sound","mix","master","vocal","custom"];
  const includes = {
    mix: ["File WAV stem-ready", "EQ + comp + balance", "1 revisione gratuita", "Consegna in 5 giorni"],
    master: ["Master 24-bit + 16-bit", "LUFS calibrato per piattaforma", "1 revisione", "Consegna in 24h"],
    "mix-master": ["Mix completo + Master", "WAV + MP3 finali", "2 revisioni gratuite", "Consegna in 7 giorni"],
    vocal: ["Tuning trasparente", "Editing breath/pop", "Comping take", "Stems voce ready"],
    custom: ["Beat originale su brief", "MP3 + WAV", "2 revisioni incluse", "Stems +€80"],
    topline: ["Melodia + testo completo", "Demo vocale", "Pubblishing 50/50", "1 revisione"],
    sound: ["Pacchetto FX custom", "Transitions per ogni brano", "Stem WAV", "Royalty-free"],
  };
  return titles.map((title, i) => {
    const cat = cats[i];
    const price = [49, 79, 129, 159, 199, 249, 299, 349][Math.floor(r() * 8)];
    const delivery = [1, 3, 5, 7, 10][Math.floor(r() * 5)];
    const rating = Math.round((4.4 + r() * 0.6) * 10) / 10;
    const reviews = Math.floor(8 + r() * 140);
    const beforeAfter = r() > 0.45;
    return {
      id: i + 1,
      title,
      category: cat,
      categoryLabel: SVC_CATEGORIES.find(c => c.id === cat).label,
      producer: SVC_PRODS[i % SVC_PRODS.length],
      verified: r() > 0.4,
      city: SVC_CITIES[i % SVC_CITIES.length],
      price,
      delivery, // days
      rating,
      reviews,
      beforeAfter,
      includes: includes[cat] || ["Servizio personalizzato", "Brief iniziale", "1 revisione", "Consegna concordata"],
      art: i % 6,
    };
  });
}

const ALL_SERVIZI = makeServizi();

// ---------- filter rail (Servizi) ----------
function ServiziFilterRail() {
  const [cat, setCat] = useStateSvc("Tutti");
  const [delivery, setDelivery] = useStateSvc("any");
  const [rating, setRating] = useStateSvc("any");

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

      <window.FilterSection title="Categoria" defaultOpen={true} count={cat !== "Tutti" ? 1 : 0}>
        <div className="chip-row">
          {["Tutti", ...SVC_CATEGORIES.map(c => c.label)].map(c => (
            <button key={c} className={`chip ${cat === c ? "active" : ""}`} onClick={() => setCat(c)}>{c}</button>
          ))}
        </div>
      </window.FilterSection>

      <window.FilterSection title="Genere" defaultOpen={false}>
        <div className="chip-row tight">
          {["Tutti","Trap","Drill","Hip-Hop","R&B","Pop"].map(g => (
            <button key={g} className="chip">{g}</button>
          ))}
          <button className="chip ghost">+ altri</button>
        </div>
      </window.FilterSection>

      <window.FilterSection title="Prezzo" defaultOpen={false}>
        <div className="range-track">
          <span className="range-fill" style={{ left: "5%", right: "40%" }}/>
          <span className="range-thumb" style={{ left: "5%" }}/>
          <span className="range-thumb" style={{ left: "60%" }}/>
        </div>
        <div className="range-tags"><span className="range-tag">€20</span><span className="range-tag">€200</span><span className="range-tag">€500+</span></div>
      </window.FilterSection>

      <window.FilterSection title="Tempi consegna" defaultOpen={false}>
        <div className="seg">
          {[["any","Tutti"],["24h","≤24h"],["3d","≤3gg"],["7d","≤7gg"]].map(([v, l]) => (
            <button key={v} className={`seg-btn ${v === "any" ? "active" : ""}`}>{l}</button>
          ))}
        </div>
      </window.FilterSection>

      <window.FilterSection 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>
      </window.FilterSection>

      <window.FilterSection title="Opzioni" defaultOpen={false}>
        <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>
      </window.FilterSection>

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

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

// ---------- service card ----------
function ServizioCard({ svc }) {
  const arts = ["art-a","art-b","art-c","art-d","art-e","art-f"];
  return (
    <article className="svc-card">
      <div className="svc-head">
        <span className={`svc-cat-pill svc-cat-${svc.category}`}>{svc.categoryLabel}</span>
        {svc.beforeAfter && (
          <span className="svc-ba-pill"><SvcIcons.waveform size={11}/> prima/dopo</span>
        )}
      </div>

      <a className="svc-title" href={(window.ESPLORA_DETAIL_BASE || "") + "Servizio.html"} style={{ color: "inherit", textDecoration: "none" }}>{svc.title}</a>

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

      <div className="svc-includes">
        <div className="svc-includes-t">Cosa include</div>
        <ul>
          {svc.includes.map(it => (
            <li key={it}><span className="bullet"><SvcIcons.check size={11}/></span>{it}</li>
          ))}
        </ul>
      </div>

      <div className="svc-foot">
        <div className="svc-meta">
          <div className="svc-price">
            <span className="from">da</span>
            <span className="amt">€{svc.price}</span>
          </div>
          <div className="svc-delivery">
            <SvcIcons.calendar size={12}/>
            <span>{svc.delivery === 1 ? "24h" : `${svc.delivery} giorni`}</span>
          </div>
        </div>
        <a className="svc-cta" href={(window.ESPLORA_DETAIL_BASE || "") + "Servizio.html"}>Vedi <SvcIcons.arrowRight size={13}/></a>
      </div>
    </article>
  );
}

function ServiziCatalog() {
  const servizi = ALL_SERVIZI;
  return (
    <div className="esplora-body">
      <ServiziFilterRail/>
      <div className="catalog">
        <div className="svc-grid">
          {servizi.map(s => <ServizioCard key={s.id} svc={s}/>)}
        </div>
        <div className="catalog-foot">
          <button className="btn-load-more">Carica altri 18 servizi</button>
        </div>
      </div>
    </div>
  );
}

window.ServiziCatalog = ServiziCatalog;
window.ALL_SERVIZI = ALL_SERVIZI;
window.SVC_COUNT = ALL_SERVIZI.length;
