// SONARA — Richieste open page (artista)
const RIcons = window.SonaraIcons;

// ============= DATA =============
const RICHIESTE = [
  {
    id: "r1",
    title: "Beat trap melodico per pezzo radio-friendly",
    status: "open",
    statusLabel: "Aperta",
    publishedAgo: "2 giorni fa",
    expiresIn: "28 giorni",
    urgent: false,
    budget: { min: 80, max: 200 },
    deliveryDays: 10,
    offers: 7,
    offersUnread: 3,
    views: 142,
    tags: ["Trap", "Melodic", "Radio-friendly", "BPM 140-150"],
    refs: ["Lil Tjay", "Travis Scott — High Five"],
    brief: [
      "Cerco un beat trap con linea melodica forte e drop pulito. Idealmente con archi sintetici, 808 calde e hi-hat triplet ma non aggressive.",
      "Deve funzionare per una hook melodica in italiano. Ho già la voce demo (allegata). Strofa rap, ritornello cantato.",
      "Importante: ricevo stems separati per il mix. Non interessato a beat già usati o licenze esclusive — preferisco non-esclusiva."
    ],
    attachments: [
      { name: "voice-memo-demo.m4a", size: "0:48 · 320 KB", icon: "audio" },
      { name: "ref-track.mp3", size: "Reference · 2.1 MB", icon: "audio" },
    ],
    offersList: [
      { id: "o1", producer: "@nightowl", initials: "NO", verified: true, rating: 4.9, completedJobs: 87, price: 145, days: 7, message: "Ho una bozza che funziona perfettamente per questo brief. Stems inclusi, 1 revisione free. Sentiamo?", featured: true, hasAttach: true, attachLabel: "snippet 0:24" },
      { id: "o2", producer: "@luxx", initials: "LX", verified: true, rating: 4.8, completedJobs: 142, price: 180, days: 5, message: "Producer da 6 anni. Posso consegnare in 5gg con fino a 3 revisioni. Stems WAV 24-bit.", featured: false, hasAttach: true, attachLabel: "snippet 0:32" },
      { id: "o3", producer: "@808king", initials: "8K", verified: false, rating: 4.6, completedJobs: 34, price: 95, days: 12, message: "Ho un beat in stock che combacia col brief, posso adattarlo per te. Prezzo basso perché parto da una base esistente.", featured: false, hasAttach: false, attachLabel: null },
      { id: "o4", producer: "@desertcat", initials: "DC", verified: true, rating: 4.7, completedJobs: 51, price: 165, days: 8, message: "Posso lavorarci subito, ho slot libero questa settimana. Mando una demo entro 24h.", featured: false, hasAttach: true, attachLabel: "snippet 0:18" },
    ],
  },
  {
    id: "r2",
    title: "Servizio di mixing per EP 4 tracce indie alternative",
    status: "open",
    statusLabel: "Aperta",
    publishedAgo: "5 giorni fa",
    expiresIn: "3 giorni",
    urgent: true,
    budget: { min: 250, max: 500 },
    deliveryDays: 14,
    offers: 4,
    offersUnread: 1,
    views: 89,
    tags: ["Mix", "Indie", "Alternative", "EP 4 tracce"],
    refs: ["Phoebe Bridgers", "Big Thief"],
    brief: [
      "Sto cercando un mix engineer per finalizzare un EP indie alternative di 4 tracce. Stems multitraccia già editati, niente vocal tuning richiesto.",
      "Cerco un suono organico, intimo, con dinamica preservata. Niente master loud."
    ],
    attachments: [
      { name: "rough-mix-track1.wav", size: "Demo · 18 MB", icon: "audio" },
    ],
    offersList: [
      { id: "o5", producer: "Hearfield Studio", initials: "HS", verified: true, rating: 4.9, completedJobs: 218, price: 380, days: 14, message: "Mix engineer dal 2014, lavorato su artisti indie italiani. Posso mandarti 1 track campione gratuita.", featured: true, hasAttach: false, attachLabel: null },
      { id: "o6", producer: "Marco Vega", initials: "MV", verified: true, rating: 4.8, completedJobs: 96, price: 320, days: 10, message: "Specializzato indie/folk. 2 revisioni incluse. Lavoro in Pro Tools + analog summing.", featured: false, hasAttach: false, attachLabel: null },
    ],
  },
  {
    id: "r3",
    title: "Cerco vocal coach per registrazione di 2 brani",
    status: "open",
    statusLabel: "Aperta",
    publishedAgo: "1 settimana fa",
    expiresIn: "21 giorni",
    urgent: false,
    budget: { min: 100, max: 250 },
    deliveryDays: 5,
    offers: 2,
    offersUnread: 0,
    views: 45,
    tags: ["Vocal coach", "R&B", "Soul"],
    refs: ["SZA", "H.E.R."],
    brief: [
      "Cerco un vocal coach per affinare la tecnica su 2 brani prima di entrare in studio. Sessioni online ok."
    ],
    attachments: [],
    offersList: [
      { id: "o7", producer: "Sara K.", initials: "SK", verified: true, rating: 5.0, completedJobs: 67, price: 180, days: 3, message: "Vocal coach + producer. Sessioni online via Zoom. Esperienza R&B/soul italiano.", featured: false, hasAttach: false, attachLabel: null },
      { id: "o8", producer: "@voicelab", initials: "VL", verified: false, rating: 4.5, completedJobs: 22, price: 120, days: 5, message: "Coaching tecnica vocale + arrangement. Posso mandare un primo modulo gratis di 30 min.", featured: false, hasAttach: false, attachLabel: null },
    ],
  },
  {
    id: "r4",
    title: "Beat boombap classico anni '90",
    status: "closed",
    statusLabel: "Chiusa",
    publishedAgo: "3 settimane fa",
    expiresIn: null,
    urgent: false,
    budget: { min: 50, max: 120 },
    deliveryDays: 7,
    offers: 11,
    offersUnread: 0,
    views: 220,
    tags: ["Boombap", "90s", "Hip-hop"],
    refs: [],
    brief: ["Richiesta chiusa senza accettazione. Nessun match con ciò che cercavo."],
    attachments: [],
    offersList: [],
  },
];

// ============= ICONS =============
const VerifiedIcon = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M12 1l2.39 1.73 2.95-.13.13 2.95L19.27 7l-1.73 2.39 1.73 2.39-1.8 2.46-.13 2.95-2.95-.13L12 19l-2.39-1.73-2.95.13-.13-2.95L4.73 12l1.73-2.39L4.73 7l1.8-2.46.13-2.95 2.95.13zM10.5 14.6l5-5-1.1-1.1-3.9 3.9-1.9-1.9-1.1 1.1z"/></svg>
);

const PlusIcon2 = ({ size = 16 }) => (
  <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 StarIcon2 = ({ size = 12, filled = true }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><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 ChatIcon = ({ 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="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
);

const CheckIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
);

const PlayIcon2 = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9V3z"/></svg>
);

const AudioFileIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><path d="M9 14v3a1.5 1.5 0 1 1-1.5-1.5"/><path d="M13 13v3a1.5 1.5 0 1 1-1.5-1.5"/></svg>
);

// ============= QUOTA =============
function Quota({ openCount }) {
  const max = 3;
  const pct = (openCount / max) * 100;
  const r = 22;
  const c = 2 * Math.PI * r;
  const offset = c * (1 - pct / 100);

  return (
    <div className="req-quota">
      <div className="req-quota-left">
        <div className="req-quota-ring">
          <svg width="56" height="56">
            <circle cx="28" cy="28" r={r} fill="none" stroke="var(--muted)" strokeWidth="4"/>
            <circle cx="28" cy="28" r={r} fill="none" stroke="var(--violet, #7b55d0)" strokeWidth="4" strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round"/>
          </svg>
          <div className="num">{openCount}/{max}</div>
        </div>
        <div className="req-quota-meta">
          <div className="t">Slot richieste open</div>
          <div className="s">Hai {openCount} richieste attive su {max} massimo. Le richieste auto-archiviate liberano lo slot.</div>
        </div>
      </div>
      <a className="req-quota-cta" href="PubblicaRichiesta.html">
        <PlusIcon2 size={14}/>
        Pubblica richiesta
      </a>
    </div>
  );
}

// ============= LIST =============
function RichiestaItem({ item, active, onClick }) {
  return (
    <div className={`req-item ${active ? "active" : ""}`} onClick={onClick}>
      <div className="req-item-row1">
        <span className={`req-item-status ${item.status}`}/>
        <span className="req-item-title">{item.title}</span>
      </div>
      <div className="req-item-meta">
        <span>{item.publishedAgo}</span>
        {item.status === "open" && (
          <>
            <span className="sep">·</span>
            <span className="badge offers">{item.offers} offerte{item.offersUnread > 0 ? ` · ${item.offersUnread} nuove` : ""}</span>
          </>
        )}
        {item.urgent && <span className="badge urgent">⏰ {item.expiresIn}</span>}
        {item.status === "closed" && <><span className="sep">·</span><span>Chiusa</span></>}
      </div>
    </div>
  );
}

function ListPanel({ items, activeId, onSelect }) {
  const [tab, setTab] = React.useState("active");
  const filtered = items.filter(i => tab === "active" ? i.status === "open" : i.status === "closed");
  return (
    <aside className="req-list-panel">
      <div className="req-list-head">
        <div className="t">Le tue richieste</div>
        <div className="req-list-tabs">
          <button className={`req-list-tab ${tab === "active" ? "active" : ""}`} onClick={() => setTab("active")}>
            Attive {items.filter(i => i.status === "open").length}
          </button>
          <button className={`req-list-tab ${tab === "closed" ? "active" : ""}`} onClick={() => setTab("closed")}>
            Archivio
          </button>
        </div>
      </div>
      <div className="req-list">
        {filtered.length === 0 ? (
          <div style={{ padding: "30px 16px", textAlign: "center", color: "var(--muted-foreground)", fontSize: 13 }}>
            Nessuna richiesta in archivio.
          </div>
        ) : (
          filtered.map(i => (
            <RichiestaItem key={i.id} item={i} active={activeId === i.id} onClick={() => onSelect(i.id)}/>
          ))
        )}
      </div>
    </aside>
  );
}

// ============= OFFER CARD =============
function OfferCard({ offer }) {
  return (
    <div className={`req-offer ${offer.featured ? "featured" : ""}`}>
      <div className="req-offer-head">
        <div className="req-offer-av">{offer.initials}</div>
        <div className="req-offer-who">
          <div className="req-offer-name">
            {offer.producer}
            {offer.verified && <span className="verified"><VerifiedIcon size={12}/></span>}
          </div>
          <div className="req-offer-rating">
            <span className="star"><StarIcon2 size={11} filled/></span>
            <strong>{offer.rating.toFixed(1)}</strong>
            <span>· {offer.completedJobs} lavori</span>
          </div>
        </div>
      </div>

      <div className="req-offer-stats">
        <div className="req-offer-stat">
          <div className="l">Prezzo</div>
          <div className="v"><span className="ccy">€</span>{offer.price}</div>
        </div>
        <div className="req-offer-stat">
          <div className="l">Consegna</div>
          <div className="v">{offer.days}<span className="ccy">gg</span></div>
        </div>
      </div>

      <div className="req-offer-msg">{offer.message}</div>

      {offer.hasAttach ? (
        <button className="req-offer-snippet has">
          <span className="play"><PlayIcon2 size={11}/></span>
          <span className="snip-wave">
            {Array.from({ length: 22 }).map((_, i) => (
              <span key={i} style={{ height: `${30 + ((Math.sin(i * 0.9) + 1) * 28 + (i % 5) * 6)}%` }}/>
            ))}
          </span>
          <span className="snip-label">Anteprima · {offer.attachLabel}</span>
        </button>
      ) : (
        <div className="req-offer-snippet none">
          <RIcons.info size={12}/>
          Nessuna anteprima allegata · solo testo
        </div>
      )}

      <div className="req-offer-actions">
        <button className="req-offer-btn primary">
          <CheckIcon size={13}/>
          Accetta
        </button>
        <button className="req-offer-btn icon-only" title="Chatta"><ChatIcon size={14}/></button>
        <button className="req-offer-btn icon-only danger" title="Rifiuta">×</button>
      </div>
    </div>
  );
}

// ============= DETAIL =============
function DetailPanel({ richiesta, onOpenOffers }) {
  if (!richiesta) {
    return (
      <section className="req-detail">
        <div className="req-detail-empty">
          <div className="ic"><RIcons.target size={26}/></div>
          <div className="t">Seleziona una richiesta</div>
          <div className="s">Vedi offerte ricevute, brief, allegati e gestisci da qui.</div>
        </div>
      </section>
    );
  }

  return (
    <section className="req-detail">
      <header className="req-detail-head">
        <div className="req-detail-status-row">
          <span className={`req-status-pill ${richiesta.status}`}>
            <span className="dot"/>
            {richiesta.statusLabel}
          </span>
          <span className="req-detail-meta-chip">📅 Pubblicata {richiesta.publishedAgo}</span>
          {richiesta.expiresIn && (
            <span className={`req-detail-meta-chip ${richiesta.urgent ? "urgent" : ""}`}>
              ⏱ {richiesta.urgent ? "Scade tra " : "Auto-chiude tra "}{richiesta.expiresIn}
            </span>
          )}
          <span className="req-detail-meta-chip">👁 {richiesta.views} visite</span>
        </div>
        <h2 className="req-detail-title">{richiesta.title}</h2>
      </header>

      <div className="req-detail-stats">
        <div className="req-detail-stat">
          <div className="l">Budget</div>
          <div className="v"><span className="ccy">€</span>{richiesta.budget.min}–{richiesta.budget.max}</div>
        </div>
        <div className="req-detail-stat">
          <div className="l">Consegna</div>
          <div className="v">{richiesta.deliveryDays}<span className="ccy">gg</span></div>
        </div>
        <div className="req-detail-stat">
          <div className="l">Offerte</div>
          <div className="v">{richiesta.offers}{richiesta.offersUnread > 0 && <span className="ccy" style={{ color: "var(--violet-bright, #7b55d0)" }}>+{richiesta.offersUnread} nuove</span>}</div>
        </div>
        <div className="req-detail-stat">
          <div className="l">Visite</div>
          <div className="v">{richiesta.views}</div>
        </div>
      </div>

      {/* Prominent offers banner → opens modal */}
      {richiesta.status === "open" && richiesta.offersList.length > 0 && (
        <button className="req-offers-cta" onClick={onOpenOffers}>
          <div className="req-offers-cta-avs">
            {richiesta.offersList.slice(0, 4).map((o, i) => (
              <span key={o.id} className="cta-av" style={{ zIndex: 4 - i }}>{o.initials}</span>
            ))}
          </div>
          <div className="req-offers-cta-meta">
            <div className="t">
              {richiesta.offers} offerte ricevute
              {richiesta.offersUnread > 0 && <span className="new-pill-inline">+{richiesta.offersUnread} nuove</span>}
            </div>
            <div className="s">Da €{Math.min(...richiesta.offersList.map(o => o.price))} · {richiesta.offersList.filter(o => o.hasAttach).length} con anteprima audio</div>
          </div>
          <span className="req-offers-cta-btn">Vedi offerte <RIcons.arrowRight size={14}/></span>
        </button>
      )}
      {richiesta.status === "open" && richiesta.offersList.length === 0 && (
        <div className="req-no-offers">
          <RIcons.target size={22}/>
          <div className="t">Ancora nessuna offerta</div>
          <div className="s">La tua richiesta è visibile a {richiesta.views} producer. Ti avvisiamo appena arriva la prima.</div>
        </div>
      )}

      <div className="req-detail-section">
        <div className="req-section-title">Tag</div>
        <div className="req-tag-row">
          {richiesta.tags.map(t => <span className="req-tag" key={t}>{t}</span>)}
        </div>
      </div>

      <div className="req-detail-section">
        <div className="req-section-title">Brief</div>
        <div className="req-brief">
          {richiesta.brief.map((p, i) => <p key={i}>{p}</p>)}
        </div>
      </div>

      {richiesta.refs.length > 0 && (
        <div className="req-detail-section">
          <div className="req-section-title">Riferimenti sonori</div>
          <div className="req-tag-row">
            {richiesta.refs.map(r => <span className="req-tag" key={r}>♫ {r}</span>)}
          </div>
        </div>
      )}

      {richiesta.attachments.length > 0 && (
        <div className="req-detail-section">
          <div className="req-section-title">Allegati</div>
          <div className="req-attach-row">
            {richiesta.attachments.map(a => (
              <div className="req-attach" key={a.name}>
                <span className="ic"><AudioFileIcon size={14}/></span>
                <span className="meta">
                  <span className="n">{a.name}</span>
                  <span className="s">{a.size}</span>
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

// ============= OFFERS MODAL =============
function OffersModal({ richiesta, onClose }) {
  const [sort, setSort] = React.useState("relevance");
  React.useEffect(() => {
    const k = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", k);
    return () => document.removeEventListener("keydown", k);
  }, [onClose]);

  let offers = [...richiesta.offersList];
  if (sort === "price-asc") offers.sort((a, b) => a.price - b.price);
  else if (sort === "price-desc") offers.sort((a, b) => b.price - a.price);
  else if (sort === "rating") offers.sort((a, b) => b.rating - a.rating);
  else if (sort === "fast") offers.sort((a, b) => a.days - b.days);

  return (
    <div className="req-modal-backdrop" onClick={onClose}>
      <div className="req-modal" onClick={(e) => e.stopPropagation()}>
        <header className="req-modal-head">
          <div className="req-modal-head-l">
            <div className="req-modal-title">Offerte ricevute</div>
            <div className="req-modal-sub">{richiesta.title}</div>
          </div>
          <button className="req-modal-close" onClick={onClose}>✕</button>
        </header>

        <div className="req-modal-toolbar">
          <div className="req-modal-count">
            <strong>{richiesta.offersList.length}</strong> offerte
            <span className="sep">·</span>
            da €{Math.min(...richiesta.offersList.map(o => o.price))}
            <span className="sep">·</span>
            {richiesta.offersList.filter(o => o.hasAttach).length} con anteprima
          </div>
          <div className="req-modal-sort">
            {[["relevance","Pertinenza"],["price-asc","Prezzo ↑"],["rating","Rating"],["fast","Più rapidi"]].map(([v, l]) => (
              <button key={v} className={`req-modal-sortbtn ${sort === v ? "active" : ""}`} onClick={() => setSort(v)}>{l}</button>
            ))}
          </div>
        </div>

        <div className="req-modal-body">
          <div className="req-offers-grid modal">
            {offers.map(o => <OfferCard key={o.id} offer={o}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============= PAGE =============
function RichiestePage() {
  const [activeId, setActiveId] = React.useState("r1");
  const [offersOpen, setOffersOpen] = React.useState(false);
  const active = RICHIESTE.find(r => r.id === activeId);
  const openCount = RICHIESTE.filter(r => r.status === "open").length;

  return (
    <main className="page" data-screen-label="Richieste open">
      <div className="greet">
        <div>
          <h1 className="hello">Richieste open</h1>
          <div className="sub">Brief pubblici per ricevere offerte da producer in linea con quello che cerchi.</div>
        </div>
      </div>

      <Quota openCount={openCount}/>

      <div className="req-layout">
        <ListPanel items={RICHIESTE} activeId={activeId} onSelect={setActiveId}/>
        <DetailPanel richiesta={active} onOpenOffers={() => setOffersOpen(true)}/>
      </div>
      {offersOpen && active && <OffersModal richiesta={active} onClose={() => setOffersOpen(false)}/>}
    </main>
  );
}

window.RichiestePage = RichiestePage;
