// Progetti — command center for the artist
// 3 sub-tabs: Collaborazioni / Richieste open / Acquisti beat (UC-A6, UC-A3, UC-A1 storico)

const ProgIcons = window.SonaraIcons;
const { useState: useStateProg, useMemo: useMemoProg } = React;

// ---------- mock data ----------
const COLLAB_DATA = [
  {
    id: 1, title: "Mix · 'Notte Lunga'", type: "Mix", typeIcon: "mix",
    counterpart: "Marco Vitale", counterpartInit: "MV", counterpartGenre: "Trap",
    art: "art-a", verified: true,
    status: "in_review", statusLabel: "Da revisionare", urgent: false,
    deadline: "2g", deadlineSub: "auto-approval", price: 80,
    lastActivity: "Producer ha consegnato v2 · 1 revisione rimasta",
    progress: 80, started: "12 mar",
  },
  {
    id: 2, title: "Beat custom · 'Trap dark'", type: "Custom production", typeIcon: "beat",
    counterpart: "Yoshi Beats", counterpartInit: "Y", counterpartGenre: "Trap",
    art: "art-b", verified: true,
    status: "in_progress", statusLabel: "In lavorazione", urgent: false,
    deadline: "5g", deadlineSub: "deadline", price: 150,
    lastActivity: "Stems consegnati · revisione 0 di 2",
    progress: 45, started: "8 mar",
  },
  {
    id: 3, title: "Master · 'Skyline EP'", type: "Master", typeIcon: "master",
    counterpart: "Studio Riva", counterpartInit: "SR", counterpartGenre: "R&B",
    art: "art-c", verified: false,
    status: "in_review", statusLabel: "Scade oggi", urgent: true,
    deadline: "6h", deadlineSub: "scadenza", price: 220,
    lastActivity: "Producer chiede approvazione finale",
    progress: 95, started: "5 mar",
  },
  {
    id: 4, title: "Vocal production · 'Onde'", type: "Vocal prod", typeIcon: "vocal",
    counterpart: "Diego K.", counterpartInit: "DK", counterpartGenre: "Pop",
    art: "art-d", verified: true,
    status: "briefing", statusLabel: "Briefing", urgent: false,
    deadline: "12g", deadlineSub: "deadline", price: 60,
    lastActivity: "Stems da caricare · richiesto entro 18 mar",
    progress: 15, started: "13 mar",
  },
];

const COLLAB_CLOSED = [
  {
    id: 5, title: "Mix + Master · 'Verde'", type: "Mix + Master", typeIcon: "mix",
    counterpart: "Studio Riva", counterpartInit: "SR", counterpartGenre: "R&B",
    art: "art-c", verified: false,
    status: "completed", statusLabel: "Completato", urgent: false,
    deadline: null, deadlineSub: null, price: 180,
    lastActivity: "Approvato · ★★★★★ recensione lasciata",
    progress: 100, started: "12 feb", closed: "20 feb",
  },
  {
    id: 6, title: "Beat custom · 'Sonar'", type: "Custom production", typeIcon: "beat",
    counterpart: "Marco Vitale", counterpartInit: "MV", counterpartGenre: "Trap",
    art: "art-a", verified: true,
    status: "completed", statusLabel: "Completato", urgent: false,
    deadline: null, deadlineSub: null, price: 200,
    lastActivity: "Approvato · ★★★★★ recensione lasciata",
    progress: 100, started: "1 feb", closed: "9 feb",
  },
  {
    id: 7, title: "Master · 'Demo 2'", type: "Master", typeIcon: "master",
    counterpart: "Vale Frey", counterpartInit: "VF", counterpartGenre: "Pop",
    art: "art-e", verified: false,
    status: "cancelled", statusLabel: "Annullato", urgent: false,
    deadline: null, deadlineSub: null, price: 50,
    lastActivity: "Annullato per accordo · rimborso emesso",
    progress: 30, started: "20 gen", closed: "23 gen",
  },
];

const RICHIESTE_DATA = [
  {
    id: 1, title: "Cerco beat trap dark · 140 BPM",
    type: "Beat", typeChip: "beat",
    status: "open", statusLabel: "Aperta",
    offers: 8, newOffers: 1,
    budget: "€80–150", deadline: "22g", deadlineSub: "rimasti",
    description: "Cerco un beat dark per nuovo singolo, atmosfera notturna, 808 grossi tipo Sfera Ebbasta ultima produzione…",
    posted: "12 mar", views: 187,
  },
  {
    id: 2, title: "Mix per singolo R&B notturno",
    type: "Mix", typeChip: "mix",
    status: "negotiation", statusLabel: "In trattativa",
    offers: 5, newOffers: 0,
    budget: "€60–100", deadline: "8g", deadlineSub: "rimasti",
    description: "Voce già registrata, stems puliti, cerco mix che valorizzi il low-end e mantenga l'aria…",
    posted: "5 mar", views: 92,
  },
  {
    id: 3, title: "Producer per EP 5 tracce",
    type: "Custom production", typeChip: "custom",
    status: "open", statusLabel: "Aperta",
    offers: 3, newOffers: 2,
    budget: "Decideremo insieme", deadline: "28g", deadlineSub: "rimasti",
    description: "Cerco producer di fiducia per progetto a lungo termine, EP 5 tracce, scadenza estate…",
    posted: "9 mar", views: 64,
  },
];

const RICHIESTE_CLOSED = [
  {
    id: 4, title: "Cerco master per album",
    type: "Master", typeChip: "master",
    status: "accepted", statusLabel: "Accettata",
    offers: 12, newOffers: 0,
    budget: "€200–400", linkedProject: 6,
    description: "Album 9 tracce, già mixato. Cerco mastering coeso e pronto per streaming…",
    posted: "22 feb", closed: "1 mar",
  },
  {
    id: 5, title: "Beat afro per estate",
    type: "Beat", typeChip: "beat",
    status: "expired", statusLabel: "Scaduta",
    offers: 0, newOffers: 0,
    budget: "€40–80",
    description: "Beat afro estivo, vibe spiaggia, melodico…",
    posted: "10 gen", closed: "9 feb",
  },
];

const ACQUISTI_DATA = [
  {
    id: 1, title: "Sognando blue moon", producer: "Yoshi Beats", producerInit: "Y",
    art: "art-a", license: "Non-esclusiva", price: 49,
    bpm: 140, key: "A min", genre: "Trap",
    purchased: "14 mar 2025", verified: true,
  },
  {
    id: 2, title: "Notte di stelle", producer: "Marco Vitale", producerInit: "MV",
    art: "art-b", license: "Non-esclusiva", price: 35,
    bpm: 95, key: "F# min", genre: "R&B",
    purchased: "8 mar 2025", verified: true,
  },
  {
    id: 3, title: "Spirale", producer: "Diego K.", producerInit: "DK",
    art: "art-c", license: "Esclusiva", price: 220,
    bpm: 128, key: "G min", genre: "Drill",
    purchased: "1 mar 2025", verified: true,
  },
  {
    id: 4, title: "Ombre", producer: "Studio Riva", producerInit: "SR",
    art: "art-d", license: "Non-esclusiva", price: 28,
    bpm: 110, key: "C maj", genre: "Pop",
    purchased: "22 feb 2025", verified: false,
  },
  {
    id: 5, title: "Mare scuro", producer: "Vale Frey", producerInit: "VF",
    art: "art-e", license: "Non-esclusiva", price: 40,
    bpm: 92, key: "D min", genre: "Afro",
    purchased: "12 feb 2025", verified: false,
  },
  {
    id: 6, title: "Codice nero", producer: "Yoshi Beats", producerInit: "Y",
    art: "art-f", license: "Non-esclusiva", price: 49,
    bpm: 145, key: "E min", genre: "Drill",
    purchased: "3 feb 2025", verified: true,
  },
];

// ---------- main page ----------
function ProgettiPage() {
  const [tab, setTab] = useStateProg(() => {
    const h = (window.location.hash || "").replace("#", "");
    if (h === "richieste") return "richieste";
    if (h === "acquisti") return "acquisti";
    return "collab";
  });

  const tabs = [
    ["collab", "Collaborazioni", COLLAB_DATA.length, true],
    ["richieste", "Richieste open", RICHIESTE_DATA.length, RICHIESTE_DATA.some(r => r.newOffers > 0)],
    ["acquisti", "Acquisti beat", ACQUISTI_DATA.length, false],
  ];

  return (
    <div className="page-progetti" data-screen-label="Progetti">
      <div className="prog-head">
        <div>
          <div className="eyebrow">Command center</div>
          <h1 className="page-title">Progetti</h1>
        </div>
      </div>

      <div className="prog-stats-row">
        <div className="prog-stat">
          <span className="num">12</span>
          <span className="lbl">completati</span>
        </div>
        <div className="prog-stat-sep"/>
        <div className="prog-stat">
          <span className="num">€1.840</span>
          <span className="lbl">spesi lifetime</span>
        </div>
        <div className="prog-stat-sep"/>
        <div className="prog-stat">
          <span className="num"><ProgIcons.star size={14} filled/> 4,7</span>
          <span className="lbl">rating dato (8 recensioni)</span>
        </div>
      </div>

      <nav className="prog-tabs">
        {tabs.map(([id, label, count, hasDot]) => (
          <button key={id} className={`prog-tab ${tab === id ? "active" : ""}`} onClick={() => setTab(id)}>
            <span className="prog-tab-l">{label}</span>
            <span className="prog-tab-c">{count}</span>
            {hasDot && tab !== id && <span className="prog-tab-dot"/>}
          </button>
        ))}
      </nav>

      {tab === "collab" && <CollaborazioniTab/>}
      {tab === "richieste" && <RichiesteTab/>}
      {tab === "acquisti" && <AcquistiTab/>}
    </div>
  );
}

// ---------- Collaborazioni ----------
function CollaborazioniTab() {
  const [viewMode, setViewMode] = useStateProg("active");
  const [sort, setSort] = useStateProg("deadline");
  const data = viewMode === "active" ? COLLAB_DATA : COLLAB_CLOSED;

  const sorted = useMemoProg(() => {
    const list = [...data];
    if (sort === "deadline") return list.sort((a, b) => a.progress - b.progress);
    if (sort === "recent") return list.sort((a, b) => b.id - a.id);
    if (sort === "price") return list.sort((a, b) => b.price - a.price);
    return list;
  }, [data, sort]);

  return (
    <div className="prog-tab-body">
      <div className="prog-toolbar">
        <div className="seg seg-toggle">
          <button className={`seg-btn ${viewMode === "active" ? "active" : ""}`} onClick={() => setViewMode("active")}>
            In corso <span className="seg-count">{COLLAB_DATA.length}</span>
          </button>
          <button className={`seg-btn ${viewMode === "closed" ? "active" : ""}`} onClick={() => setViewMode("closed")}>
            Chiusi <span className="seg-count">{COLLAB_CLOSED.length}</span>
          </button>
        </div>
        <div className="prog-toolbar-right">
          <button className="btn-ghost-sm">
            <ProgIcons.filter size={13}/> Filtri
          </button>
          <select className="prog-sort" value={sort} onChange={e => setSort(e.target.value)}>
            <option value="deadline">Scadenza più vicina</option>
            <option value="recent">Recenti</option>
            <option value="price">Prezzo</option>
          </select>
        </div>
      </div>

      <div className="collab-list">
        {sorted.map(p => <CollabCard key={p.id} p={p} closed={viewMode === "closed"}/>)}
      </div>
    </div>
  );
}

function CollabCard({ p, closed }) {
  return (
    <article className={`collab-card ${p.urgent ? "urgent" : ""} ${closed ? "closed" : ""}`}>
      <div className={`collab-art ${p.art}`}>
        <span className="ic"><ProgIcons.waveform size={28}/></span>
        <span className="collab-art-type">{p.type}</span>
      </div>
      <div className="collab-body">
        <div className="collab-row1">
          <div className="collab-title-wrap">
            <h3 className="collab-title">{p.title}</h3>
            <span className={`status-tag ${p.status}`}>{p.statusLabel}</span>
          </div>
          <div className="collab-price">€{p.price}</div>
        </div>
        <div className="collab-row2">
          <span className="collab-person">
            <span className="av">{p.counterpartInit}</span>
            <span className="n">{p.counterpart}</span>
            {p.verified && <ProgIcons.verified size={11}/>}
            <span className="dot"/>
            <span className="g">{p.counterpartGenre}</span>
          </span>
        </div>
        <div className="collab-row3">
          <span className="collab-activity">{p.lastActivity}</span>
        </div>
        <div className="collab-progress">
          <span style={{ width: p.progress + "%" }}/>
        </div>
      </div>
      <div className="collab-right">
        {p.deadline && (
          <div className={`collab-deadline ${p.urgent ? "urgent" : ""}`}>
            <span className="big">{p.deadline}</span>
            <span className="sub">{p.deadlineSub}</span>
          </div>
        )}
        {closed && (
          <div className="collab-closed-meta">
            <span className="lbl">Chiuso</span>
            <span className="val">{p.closed}</span>
          </div>
        )}
        <a href="Messaggi.html" className="btn-ghost-sm">
          Apri <ProgIcons.arrowRight size={12}/>
        </a>
      </div>
    </article>
  );
}

// ---------- Richieste open ----------
function RichiesteTab() {
  const [viewMode, setViewMode] = useStateProg("active");
  const data = viewMode === "active" ? RICHIESTE_DATA : RICHIESTE_CLOSED;
  const slotsLeft = 3 - RICHIESTE_DATA.length;

  return (
    <div className="prog-tab-body">
      <div className="richieste-banner">
        <div className="richieste-banner-l">
          <ProgIcons.target size={18}/>
          <div>
            <div className="t">Hai {RICHIESTE_DATA.length} richieste attive · {slotsLeft >= 0 ? slotsLeft : 0} slot{slotsLeft !== 1 ? "" : ""} disponibil{slotsLeft !== 1 ? "i" : "e"}</div>
            <div className="s">Le richieste open invitano i producer a fare offerte a te. Max 3 attive contemporaneamente.</div>
          </div>
        </div>
        {slotsLeft <= 0 ? (
          <button className="btn-primary-sm" disabled>
            <ProgIcons.zap size={13}/> Pubblica richiesta
          </button>
        ) : (
          <a href="PubblicaRichiesta.html" className="btn-primary-sm">
            <ProgIcons.zap size={13}/> Pubblica richiesta
          </a>
        )}
      </div>

      <div className="prog-toolbar">
        <div className="seg seg-toggle">
          <button className={`seg-btn ${viewMode === "active" ? "active" : ""}`} onClick={() => setViewMode("active")}>
            Attive <span className="seg-count">{RICHIESTE_DATA.length}</span>
          </button>
          <button className={`seg-btn ${viewMode === "closed" ? "active" : ""}`} onClick={() => setViewMode("closed")}>
            Storiche <span className="seg-count">{RICHIESTE_CLOSED.length}</span>
          </button>
        </div>
      </div>

      <div className="richieste-list">
        {data.map(r => <RichiestaCard key={r.id} r={r}/>)}
      </div>
    </div>
  );
}

function RichiestaCard({ r }) {
  return (
    <article className={`richiesta-card status-${r.status}`}>
      <div className="richiesta-head">
        <div className="richiesta-head-l">
          <span className={`type-chip type-${r.typeChip}`}>{r.type}</span>
          <span className={`status-tag ${r.status}`}>{r.statusLabel}</span>
        </div>
        <button className="card-menu-btn"><ProgIcons.more size={14}/></button>
      </div>
      <h3 className="richiesta-title">{r.title}</h3>
      <p className="richiesta-desc">{r.description}</p>
      <div className="richiesta-meta-row">
        <span className="rmeta"><ProgIcons.coins size={12}/> {r.budget}</span>
        {r.deadline && <span className="rmeta"><ProgIcons.calendar size={12}/> {r.deadline} {r.deadlineSub}</span>}
        {r.posted && <span className="rmeta sub">Pubblicata {r.posted}</span>}
        {r.views !== undefined && <span className="rmeta sub">{r.views} viste</span>}
      </div>
      {(r.status === "open" || r.status === "negotiation") && (
        <div className="richiesta-foot">
          <div className="offers-counter">
            <span className="big">{r.offers}</span>
            <span className="lbl">{r.offers === 1 ? "offerta ricevuta" : "offerte ricevute"}</span>
            {r.newOffers > 0 && <span className="new-pill">+{r.newOffers} nuova</span>}
          </div>
          <a href="Richieste.html" className="btn-primary-sm" style={{ textDecoration: "none" }}>
            Vedi offerte ({r.offers}) <ProgIcons.arrowRight size={12}/>
          </a>
        </div>
      )}
      {r.status === "accepted" && (
        <div className="richiesta-foot">
          <div className="accepted-info">
            <ProgIcons.check size={14}/> Accettata · convertita in progetto
          </div>
          <a href="Messaggi.html" className="btn-ghost-sm">Vai al progetto <ProgIcons.arrowRight size={12}/></a>
        </div>
      )}
      {r.status === "expired" && (
        <div className="richiesta-foot">
          <div className="expired-info">Scaduta senza offerte</div>
          <a href="PubblicaRichiesta.html" className="btn-ghost-sm">Ripubblica con modifiche</a>
        </div>
      )}
    </article>
  );
}

// ---------- Acquisti beat ----------
function AcquistiTab() {
  const [filter, setFilter] = useStateProg("all");
  const [sort, setSort] = useStateProg("recent");

  const filtered = useMemoProg(() => {
    let list = [...ACQUISTI_DATA];
    if (filter === "exclusive") list = list.filter(a => a.license === "Esclusiva");
    if (filter === "non-exclusive") list = list.filter(a => a.license === "Non-esclusiva");
    if (sort === "price") list.sort((a, b) => b.price - a.price);
    if (sort === "alpha") list.sort((a, b) => a.title.localeCompare(b.title));
    return list;
  }, [filter, sort]);

  const totalSpent = ACQUISTI_DATA.reduce((s, a) => s + a.price, 0);

  return (
    <div className="prog-tab-body">
      <div className="acquisti-summary">
        <div className="acquisti-sum-stat">
          <span className="num">{ACQUISTI_DATA.length}</span>
          <span className="lbl">beat acquistati</span>
        </div>
        <div className="acquisti-sum-stat">
          <span className="num">€{totalSpent}</span>
          <span className="lbl">spesi in beat</span>
        </div>
        <div className="acquisti-sum-stat">
          <span className="num">1</span>
          <span className="lbl">esclusiva</span>
        </div>
      </div>

      <div className="prog-toolbar">
        <div className="seg seg-toggle">
          <button className={`seg-btn ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>
            Tutte <span className="seg-count">{ACQUISTI_DATA.length}</span>
          </button>
          <button className={`seg-btn ${filter === "non-exclusive" ? "active" : ""}`} onClick={() => setFilter("non-exclusive")}>
            Non-esclusive <span className="seg-count">{ACQUISTI_DATA.filter(a=>a.license==="Non-esclusiva").length}</span>
          </button>
          <button className={`seg-btn ${filter === "exclusive" ? "active" : ""}`} onClick={() => setFilter("exclusive")}>
            Esclusive <span className="seg-count">{ACQUISTI_DATA.filter(a=>a.license==="Esclusiva").length}</span>
          </button>
        </div>
        <div className="prog-toolbar-right">
          <select className="prog-sort" value={sort} onChange={e => setSort(e.target.value)}>
            <option value="recent">Recenti</option>
            <option value="price">Prezzo ↓</option>
            <option value="alpha">Alfabetico</option>
          </select>
        </div>
      </div>

      <div className="acquisti-grid">
        {filtered.map(a => <AcquistoCard key={a.id} a={a}/>)}
      </div>
    </div>
  );
}

function AcquistoCard({ a }) {
  return (
    <article className="acquisto-card">
      <div className={`acquisto-art ${a.art}`}>
        <span className="ic"><ProgIcons.waveform size={26}/></span>
        {a.license === "Esclusiva" && <span className="excl-flag"><ProgIcons.shield size={10}/> Esclusiva</span>}
      </div>
      <div className="acquisto-body">
        <h3 className="acquisto-title">{a.title}</h3>
        <div className="acquisto-prod">
          <span className="av">{a.producerInit}</span>
          <span>{a.producer}</span>
          {a.verified && <ProgIcons.verified size={10}/>}
        </div>
        <div className="acquisto-meta">
          <span>{a.bpm} BPM</span>
          <span className="dot"/>
          <span>{a.key}</span>
          <span className="dot"/>
          <span>{a.genre}</span>
        </div>
        <div className="acquisto-foot">
          <div className="acquisto-paid">
            <span className="lbl">Pagato</span>
            <span className="val">€{a.price}</span>
            <span className="when">{a.purchased}</span>
          </div>
          <button className="acquisto-dl" title="Scarica ZIP">
            <ProgIcons.arrowRight size={14} style={{ transform: "rotate(90deg)" }}/>
          </button>
        </div>
      </div>
    </article>
  );
}

window.ProgettiPage = ProgettiPage;
