// Esplora — container with 3 tabs (Beat / Servizi / Producer)
// Each tab has a different page title, count, sort options, and active filter pills.
// Filter rail content + grid come from EsploraBeat / EsploraServizi / EsploraProducer.

const { useState: useStateEsp } = React;
const EspIcons = window.SonaraIcons;

const TAB_CONFIG = {
  beat: {
    title: "Esplora beat",
    eyebrow: "Catalog",
    sub: "aggiornato in tempo reale",
    activeFilters: [],
    sortOptions: [["relevance","Pertinenza"],["new","Recenti"],["popular","Popolari"],["price-asc","Prezzo ↑"],["price-desc","Prezzo ↓"]],
  },
  servizi: {
    title: "Esplora servizi",
    eyebrow: "Marketplace",
    sub: "Mix, master, vocal, custom production",
    activeFilters: [],
    sortOptions: [["relevance","Pertinenza"],["rating","Rating"],["price-asc","Prezzo ↑"],["fast","Tempi rapidi"]],
  },
  producer: {
    title: "Esplora producer",
    eyebrow: "Directory",
    sub: "Trova chi può lavorare con te",
    activeFilters: [],
    sortOptions: [["relevance","Pertinenza"],["top","Top Rated"],["active","Più attivi"],["new","Recenti"]],
  },
  artisti: {
    title: "Esplora artisti",
    eyebrow: "Directory",
    sub: "Scopri voci emergenti, collabora, segui talenti",
    activeFilters: [],
    sortOptions: [["relevance","Pertinenza"],["emerging","Top emergenti"],["new","Recenti"],["active","Più attivi"]],
  },
};

function SortDropdown({ tab, value, onChange }) {
  const [open, setOpen] = useStateEsp(false);
  const opts = TAB_CONFIG[tab].sortOptions;
  const sel = opts.find(o => o[0] === value) || opts[0];
  return (
    <div className={`sort-dd ${open ? "open" : ""}`}>
      <button className="sort-dd-btn" onClick={() => setOpen(!open)}>
        <span className="sort-l">Ordina per</span>
        <span className="sort-v">{sel[1]}</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
      </button>
      {open && (
        <div className="sort-dd-menu" onMouseLeave={() => setOpen(false)}>
          {opts.map(([v, l]) => (
            <button key={v} className={`sort-dd-opt ${v === value ? "active" : ""}`} onClick={() => { onChange(v); setOpen(false); }}>
              {l}
              {v === value && <EspIcons.check size={13}/>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function EsploraPage({ playerStyle = "expanded", cardStyle = "standard", tabStyle = "subtab" }) {
  const [tab, setTab] = useStateEsp("beat");
  const [view, setView] = useStateEsp("list");
  const [railOpen, setRailOpen] = useStateEsp(() => {
    try { return localStorage.getItem("sonara-rail-open") !== "0"; } catch (e) { return true; }
  });
  React.useEffect(() => {
    try { localStorage.setItem("sonara-rail-open", railOpen ? "1" : "0"); } catch (e) {}
  }, [railOpen]);
  const [sort, setSort] = useStateEsp({ beat: "relevance", servizi: "relevance", producer: "relevance", artisti: "relevance" });

  const cfg = TAB_CONFIG[tab];
  const counts = {
    beat: window.BEAT_COUNT || 24,
    servizi: window.SVC_COUNT || 18,
    producer: window.PROD_COUNT || 24,
    artisti: window.ART_COUNT || 24,
  };

  const tabs = [
    ["beat", "Beat", counts.beat],
    ["servizi", "Servizi", counts.servizi],
    ["producer", "Producer", counts.producer],
    ["artisti", "Artisti", counts.artisti],
  ];

  const supportsMap = tab === "producer" || tab === "artisti";
  const supportsRail = true;
  React.useEffect(() => { if (!supportsMap) setView("list"); }, [tab, supportsMap]);

  return (
    <div className="page-esplora" data-screen-label={cfg.title} data-rail={railOpen ? "open" : "closed"}>
      {/* Tab nav — appears ABOVE the title (changes context like a section switcher) */}
      <nav className={`esplora-tabs tabs-${tabStyle}`}>
        {tabs.map(([id, label, count]) => (
          <button key={id} className={`esplora-tab ${tab === id ? "active" : ""}`} onClick={() => setTab(id)}>
            <span className="esplora-tab-l">{label}</span>
            <span className="esplora-tab-c">{count}</span>
          </button>
        ))}
      </nav>

      <div className="esplora-head">
        <div>
          <div className="eyebrow">{cfg.eyebrow}</div>
          <h1 className="page-title">{cfg.title}</h1>
          <div className="page-sub">
            <strong>{counts[tab].toLocaleString("it")} risultati</strong>
            <span className="sub-sep">·</span>
            <span>{cfg.sub}</span>
          </div>
        </div>
      </div>

      <div className="esplora-toolbar">
        <div className="active-filters">
          {supportsRail && window.RailToggleButton && (
            <window.RailToggleButton open={railOpen} onChange={setRailOpen} activeCount={0}/>
          )}
          {cfg.activeFilters.map(f => (
            <span key={f} className="filter-tag">{f} <button>×</button></span>
          ))}
          {cfg.activeFilters.length > 0 && <button className="filter-tag-clear">Pulisci tutto</button>}
        </div>
        {supportsMap && (
          <div className="view-toggle">
            <button className={view === "list" ? "active" : ""} onClick={() => setView("list")}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
              Lista
            </button>
            <button className={view === "map" ? "active" : ""} onClick={() => setView("map")}>
              <EspIcons.pin size={12}/>
              Mappa
            </button>
          </div>
        )}
        <SortDropdown tab={tab} value={sort[tab]} onChange={(v) => setSort(s => ({ ...s, [tab]: v }))}/>
      </div>

      {tab === "beat" && <window.BeatCatalog playerStyle={playerStyle} cardStyle={cardStyle}/>}
      {tab === "servizi" && <window.ServiziCatalog/>}
      {tab === "producer" && view === "list" && <window.ProducerCatalog/>}
      {tab === "producer" && view === "map" && <window.MapView type="producer"/>}
      {tab === "artisti" && view === "list" && <window.ArtistCatalog/>}
      {tab === "artisti" && view === "map" && <window.MapView type="artisti"/>}
    </div>
  );
}

window.EsploraPage = EsploraPage;
