// SONARA — Producer Catalog (owner view: Beat + Servizi)
const CIcons = window.SonaraIcons;

const BEATS = [
  { id: 1, title: "Notturno", bpm: 142, key: "F# min", grad: "b1", status: "published", price: 45, exclusive: 350, sold: 3, plays: 2100, views: 4200, revenue: 458, updated: "2gg fa", exclusiveAvail: true, genre: "Trap" },
  { id: 2, title: "Asfalto Bagnato", bpm: 138, key: "G min", grad: "b2", status: "published", price: 50, exclusive: 400, sold: 1, plays: 1400, views: 2800, revenue: 168, updated: "1 sett. fa", exclusiveAvail: true, genre: "Trap" },
  { id: 3, title: "Lupo Solitario", bpm: 145, key: "D min", grad: "b3", status: "published", price: 40, exclusive: 300, sold: 5, plays: 3200, views: 6100, revenue: 545, updated: "3gg fa", exclusiveAvail: true, genre: "Drill" },
  { id: 4, title: "Quartiere Nord", bpm: 140, key: "A min", grad: "b4", status: "published", price: 55, exclusive: 450, sold: 2, plays: 1800, views: 3400, revenue: 220, updated: "2 sett. fa", exclusiveAvail: true, genre: "Drill" },
  { id: 5, title: "Settembre", bpm: 132, key: "E min", grad: "b5", status: "published", price: 60, exclusive: 500, sold: 0, plays: 892, views: 1900, revenue: 0, updated: "5gg fa", exclusiveAvail: true, genre: "R&B" },
  { id: 6, title: "Cassetta Vuota", bpm: 148, key: "B min", grad: "b6", status: "published", price: 45, exclusive: 380, sold: 1, plays: 1100, views: 2300, revenue: 120, updated: "4gg fa", exclusiveAvail: true, genre: "Trap" },
  { id: 7, title: "Mezzanotte", bpm: 144, key: "C# min", grad: "b1", status: "sold_exclusive", price: 50, exclusive: 420, sold: 1, plays: 4200, views: 8200, revenue: 420, updated: "1 mese fa", exclusiveAvail: false, genre: "Trap", soldTo: "RAZZA" },
  { id: 8, title: "Veleno", bpm: 150, key: "F min", grad: "b2", status: "draft", price: 0, exclusive: 0, sold: 0, plays: 0, views: 0, revenue: 0, updated: "Ieri", exclusiveAvail: true, genre: "Drill" },
  { id: 9, title: "Solo Per Te", bpm: 90, key: "D maj", grad: "b3", status: "hidden", price: 50, exclusive: 400, sold: 0, plays: 320, views: 800, revenue: 0, updated: "2 mesi fa", exclusiveAvail: true, genre: "R&B" },
  { id: 10, title: "Doppia Faccia", bpm: 146, key: "G# min", grad: "b4", status: "published", price: 45, exclusive: 380, sold: 2, plays: 1600, views: 3100, revenue: 218, updated: "1 sett. fa", exclusiveAvail: true, genre: "Trap" },
  { id: 11, title: "Cobra", bpm: 152, key: "E min", grad: "b5", status: "published", price: 50, exclusive: 420, sold: 1, plays: 980, views: 1800, revenue: 105, updated: "2 sett. fa", exclusiveAvail: true, genre: "Drill" },
  { id: 12, title: "Sirene", bpm: 128, key: "A min", grad: "b6", status: "published", price: 65, exclusive: 550, sold: 0, plays: 420, views: 1200, revenue: 0, updated: "3gg fa", exclusiveAvail: true, genre: "Hip-hop" },
];

const SERVICES = [
  { id: 1, title: "Mix professionale trap/hip-hop", type: "Mix stereo", price: 120, delivery: "3 gg", orders: 24, rating: 4.9, status: "published", views: 1840, conv: 4.2, revenue: 2640, grad: "g3", revisions: 2, addons: 3, active: 2 },
  { id: 2, title: "Mix + Master pacchetto completo", type: "Mix + Master", price: 180, delivery: "4 gg", orders: 18, rating: 4.8, status: "published", views: 2210, conv: 3.8, revenue: 2880, grad: "g4", revisions: 2, addons: 4, active: 1 },
  { id: 3, title: "Custom production su brief", type: "Custom production", price: 350, delivery: "7 gg", orders: 8, rating: 5.0, status: "published", views: 1120, conv: 2.1, revenue: 2464, grad: "g1", revisions: 3, addons: 2, active: 1 },
  { id: 4, title: "Vocal production + tuning", type: "Vocal production", price: 90, delivery: "2 gg", orders: 15, rating: 4.7, status: "published", views: 940, conv: 5.1, revenue: 1188, grad: "g5", revisions: 2, addons: 2, active: 0 },
];

/* ─────── ICONS ─────── */
const PlayIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9V3z"/></svg>;
const EyeIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>;
const EditIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>;
const DotsIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>;
const PlusIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg>;
const StarIc = ({ size = 12, filled = true }) => <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.5"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>;
const SearchIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>;
const ChevDownIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>;
const PauseIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>;

const STATUS = {
  published: { label: "Pubblicato", cls: "ok" },
  draft: { label: "Bozza", cls: "draft" },
  sold_exclusive: { label: "Venduto esclusiva", cls: "exclusive" },
  hidden: { label: "Nascosto", cls: "hidden" },
};

/* ─────── BEAT TABLE ROW ─────── */
function BeatRow({ b, view }) {
  const [playing, setPlaying] = React.useState(false);
  if (view === "card") {
    return (
      <a href="BeatOwner.html" className="cat-card">
        <div className={`cat-card-cover ${b.grad}`}>
          <button onClick={(e) => { e.preventDefault(); setPlaying(!playing); }} className="cat-card-play">
            {playing ? <PauseIc size={14}/> : <PlayIc size={13}/>}
          </button>
          <span className={`cat-status ${STATUS[b.status].cls}`}>{STATUS[b.status].label}</span>
          {b.status === "published" && b.sold > 0 && (
            <span className="cat-card-sold">{b.sold} venduti</span>
          )}
        </div>
        <div className="cat-card-body">
          <div className="cat-card-row1">
            <div className="cat-card-title">{b.title}</div>
            <button className="cat-icon-btn" onClick={(e) => e.preventDefault()}><DotsIc size={14}/></button>
          </div>
          <div className="cat-card-meta">
            <span>{b.bpm} BPM</span><span className="sep">·</span>
            <span>{b.key}</span><span className="sep">·</span>
            <span>{b.genre}</span>
          </div>
          <div className="cat-card-stats">
            <div><span className="l">Plays</span><span className="v">{b.plays.toLocaleString("it-IT")}</span></div>
            <div><span className="l">Visite</span><span className="v">{b.views.toLocaleString("it-IT")}</span></div>
            <div><span className="l">Revenue</span><span className="v">€{b.revenue}</span></div>
          </div>
          <div className="cat-card-prices">
            <span className="basic">€{b.price}</span>
            {b.exclusiveAvail && <span className="excl">€{b.exclusive} excl.</span>}
            {b.status === "sold_exclusive" && <span className="cat-soldto">→ {b.soldTo}</span>}
          </div>
        </div>
      </a>
    );
  }
  // Table row
  return (
    <a href="BeatOwner.html" className="cat-tr">
      <div className="cat-td cat-td-art">
        <div className={`cat-art ${b.grad}`}>
          <button onClick={(e) => { e.preventDefault(); setPlaying(!playing); }} className="cat-art-play">
            {playing ? <PauseIc size={11}/> : <PlayIc size={10}/>}
          </button>
        </div>
        <div>
          <div className="cat-tr-title">{b.title}</div>
          <div className="cat-tr-meta">{b.bpm} BPM · {b.key} · {b.genre}</div>
        </div>
      </div>
      <div className="cat-td cat-td-status">
        <span className={`cat-status ${STATUS[b.status].cls}`}>{STATUS[b.status].label}</span>
      </div>
      <div className="cat-td cat-td-num">{b.plays.toLocaleString("it-IT")}</div>
      <div className="cat-td cat-td-num">{b.views.toLocaleString("it-IT")}</div>
      <div className="cat-td cat-td-num">{b.sold}</div>
      <div className="cat-td cat-td-num strong">€{b.revenue}</div>
      <div className="cat-td cat-td-prices">
        <span className="basic">€{b.price}</span>
        {b.exclusiveAvail && <span className="excl">€{b.exclusive}</span>}
      </div>
      <div className="cat-td cat-td-actions">
        <button className="cat-icon-btn" onClick={(e) => e.preventDefault()}><EditIc size={13}/></button>
        <button className="cat-icon-btn" onClick={(e) => e.preventDefault()}><DotsIc size={14}/></button>
      </div>
    </a>
  );
}

/* ─────── BEAT TAB ─────── */
function BeatTab() {
  const [filter, setFilter] = React.useState("all"); // all, published, draft, sold_exclusive, hidden
  const [sort, setSort] = React.useState("updated"); // updated, plays, sold, revenue
  const [view, setView] = React.useState("table"); // card | table
  const [search, setSearch] = React.useState("");

  let beats = BEATS;
  if (filter !== "all") beats = beats.filter(b => b.status === filter);
  if (search) beats = beats.filter(b => b.title.toLowerCase().includes(search.toLowerCase()));
  beats = [...beats].sort((a, b) => {
    if (sort === "plays") return b.plays - a.plays;
    if (sort === "sold") return b.sold - a.sold;
    if (sort === "revenue") return b.revenue - a.revenue;
    return 0; // updated = order in array
  });

  return (
    <>
      <div className="cat-toolbar">
        <div className="cat-search">
          <SearchIc size={14}/>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Cerca beat per titolo…"/>
        </div>
        <div className="cat-toolbar-filters">
          {[
            { v: "all", l: "Tutti", c: BEATS.length },
            { v: "published", l: "Pubblicati", c: BEATS.filter(b => b.status === "published").length },
            { v: "draft", l: "Bozze", c: BEATS.filter(b => b.status === "draft").length },
            { v: "sold_exclusive", l: "Venduti excl.", c: BEATS.filter(b => b.status === "sold_exclusive").length },
            { v: "hidden", l: "Nascosti", c: BEATS.filter(b => b.status === "hidden").length },
          ].map(f => (
            <button key={f.v} className={`cat-chip ${filter === f.v ? "active" : ""}`} onClick={() => setFilter(f.v)}>
              {f.l}<span className="c">{f.c}</span>
            </button>
          ))}
        </div>
        <div className="cat-toolbar-right">
          <div className="cat-sort">
            <span>Ordina</span>
            <select value={sort} onChange={(e) => setSort(e.target.value)}>
              <option value="updated">Recenti</option>
              <option value="plays">Più ascoltati</option>
              <option value="sold">Più venduti</option>
              <option value="revenue">Revenue</option>
            </select>
            <ChevDownIc size={11}/>
          </div>
          <div className="cat-view-toggle">
            <button className={view === "table" ? "active" : ""} onClick={() => setView("table")} title="Tabella">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
            </button>
            <button className={view === "card" ? "active" : ""} onClick={() => setView("card")} title="Griglia">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
            </button>
          </div>
        </div>
      </div>

      {view === "table" ? (
        <div className="cat-table">
          <div className="cat-table-head">
            <div className="cat-td cat-td-art">Beat</div>
            <div className="cat-td cat-td-status">Stato</div>
            <div className="cat-td cat-td-num">Plays</div>
            <div className="cat-td cat-td-num">Visite</div>
            <div className="cat-td cat-td-num">Venduti</div>
            <div className="cat-td cat-td-num">Revenue</div>
            <div className="cat-td cat-td-prices">Prezzo</div>
            <div className="cat-td cat-td-actions"></div>
          </div>
          {beats.map(b => <BeatRow key={b.id} b={b} view={view}/>)}
          <a href="CaricaBeat.html" className="cat-tr cat-tr-add">
            <div className="cat-td cat-td-art">
              <div className="cat-art-add"><PlusIc size={16}/></div>
              <div>
                <div className="cat-tr-title">Carica nuovo beat</div>
                <div className="cat-tr-meta">Wizard 3-step · audio + metadata + licenze</div>
              </div>
            </div>
          </a>
        </div>
      ) : (
        <div className="cat-grid">
          {beats.map(b => <BeatRow key={b.id} b={b} view={view}/>)}
          <a href="CaricaBeat.html" className="cat-svc-add" style={{ minHeight: 240 }}>
            <div className="ic"><PlusIc size={20}/></div>
            <div className="t">Carica nuovo beat</div>
            <div className="s">WAV / MP3 / AIFF · max 50MB · wizard 3-step</div>
          </a>
        </div>
      )}

      {beats.length === 0 && (
        <div className="cat-empty">
          <div className="ic"><CIcons.disc size={26}/></div>
          <div className="t">Nessun beat in questa categoria</div>
          <div className="s">Cambia filtro o carica il primo beat.</div>
          <a href="CaricaBeat.html" className="pf-action-btn primary" style={{ marginTop: 14, display: "inline-flex" }}>
            <PlusIc size={13}/> Carica beat
          </a>
        </div>
      )}
    </>
  );
}

/* ─────── SERVICE CARD ─────── */
function ServiceCard({ s }) {
  return (
    <a href="ServizioOwner.html" className="cat-svc">
      <div className={`cat-svc-cover ${s.grad}`}>
        <span className="cat-svc-type">{s.type}</span>
        <span className={`cat-status ${STATUS[s.status].cls}`}>{STATUS[s.status].label}</span>
      </div>
      <div className="cat-svc-body">
        <div className="cat-svc-row1">
          <div className="cat-svc-title">{s.title}</div>
          <button className="cat-icon-btn" onClick={(e) => e.preventDefault()}><DotsIc size={14}/></button>
        </div>
        <div className="cat-svc-meta">
          <span><StarIc size={11}/> {s.rating}</span>
          <span className="sep">·</span>
          <span>{s.orders} ordini</span>
          <span className="sep">·</span>
          <span>Consegna {s.delivery}</span>
          {s.active > 0 && <><span className="sep">·</span><span className="active-tag">{s.active} in corso</span></>}
        </div>
        <div className="cat-svc-stats">
          <div><span className="l">Visite</span><span className="v">{s.views.toLocaleString("it-IT")}</span></div>
          <div><span className="l">Conv.</span><span className="v">{s.conv}%</span></div>
          <div><span className="l">Revisioni incl.</span><span className="v">{s.revisions}</span></div>
          <div><span className="l">Add-on</span><span className="v">{s.addons}</span></div>
          <div><span className="l">Revenue lifetime</span><span className="v strong">€{s.revenue}</span></div>
        </div>
        <div className="cat-svc-foot">
          <span className="from">A partire da</span>
          <span className="price">€{s.price}</span>
        </div>
      </div>
    </a>
  );
}

/* ─────── SERVICES TAB ─────── */
function ServicesTab() {
  return (
    <>
      <div className="cat-svc-list">
        {SERVICES.map(s => <ServiceCard key={s.id} s={s}/>)}
        <a href="CreaListing.html" className="cat-svc-add">
          <div className="ic"><PlusIc size={20}/></div>
          <div className="t">Crea nuovo listing</div>
          <div className="s">Mix, master, custom production, vocal prod o altro</div>
        </a>
      </div>
    </>
  );
}

/* ─────── CATALOG PAGE ─────── */
function CatalogPage() {
  const [tab, setTab] = React.useState("beats");
  const revLifetime = BEATS.reduce((a, b) => a + b.revenue, 0) + SERVICES.reduce((a, s) => a + s.revenue, 0);

  return (
    <main className="page" data-screen-label="Catalog Producer">
      <div className="cat-head">
        <div className="cat-head-l">
          <h1 className="cat-h1">Catalog</h1>
          <div className="cat-head-stats">
            <span><strong>{BEATS.length}</strong> beat</span>
            <span className="sep">·</span>
            <span><strong>{SERVICES.length}</strong> servizi</span>
            <span className="sep">·</span>
            <span>€<strong>{revLifetime.toLocaleString("it-IT")}</strong> revenue lifetime</span>
          </div>
        </div>
        <div className="cat-head-actions">
          <a href="CaricaBeat.html" className="pf-action-btn">
            <PlusIc size={13}/> Carica beat
          </a>
          <a href="CreaListing.html" className="pf-action-btn primary">
            <PlusIc size={13}/> Crea listing servizio
          </a>
        </div>
      </div>

      <div className="cat-tabs">
        <button className={`cat-tab ${tab === "beats" ? "active" : ""}`} onClick={() => setTab("beats")}>
          Beat <span className="c">{BEATS.length}</span>
        </button>
        <button className={`cat-tab ${tab === "services" ? "active" : ""}`} onClick={() => setTab("services")}>
          Servizi <span className="c">{SERVICES.length}</span>
        </button>
      </div>

      {tab === "beats" ? <BeatTab/> : <ServicesTab/>}
    </main>
  );
}

window.CatalogPage = CatalogPage;
