// SONARA — Order detail page (shared across artista + producer)
// Reads window.SONARA_ROLE → renders different actions for each role.
// Same structure, same layout, same CSS — coherence is locked by design.

const OrdIcons = window.SonaraIcons;

/* ────────── ORDER STATES ────────── */
const ORDER_STATES = {
  pending_acceptance: { label: "In attesa di conferma", color: "warning",  step: 1 },
  awaiting_stems:     { label: "In attesa di stems",    color: "warning",  step: 2 },
  in_progress:        { label: "In lavorazione",        color: "info",     step: 3 },
  delivered:          { label: "Consegnato",            color: "info",     step: 4 },
  revision_requested: { label: "Revisione richiesta",   color: "warning",  step: 4 },
  completed:          { label: "Completato",            color: "success",  step: 5 },
  cancelled:          { label: "Annullato",             color: "neutral",  step: 0 },
};

const TIMELINE_STEPS = [
  { k: "acceptance", l: "Accettato",         when: o => o.acceptedOn },
  { k: "stems",      l: "Briefing & stems",  when: o => o.stemsOn },
  { k: "work",       l: "Lavorazione",       when: o => o.workOn },
  { k: "review",     l: "Revisione",         when: o => o.reviewOn },
  { k: "done",       l: "Consegnato",        when: o => o.doneOn },
];

const MOCK_ORDER = {
  id: "ORD-4821",
  kind: "Mix + Master",
  title: "EP \"Asfalto\" (5 brani)",
  state: "revision_requested",
  artist: { name: "Romeo Zappalà", alias: "RAZZA", init: "RZ", verified: true, age: 24, city: "Catania", orders: 12, rating: 4.7 },
  producer: { name: "Nico Vega", alias: "@nicovega", init: "NV", verified: true, topRated: true, rating: 4.9, city: "Milano" },
  startedOn: "8 maggio 2026",
  acceptedOn: "8 maggio",
  stemsOn: "9 maggio",
  workOn: "9–14 maggio",
  reviewOn: "in corso",
  deadline: "16 maggio 2026 · 18:00",
  deadlineHours: 22,
  payment: { gross: 180, fee: 21.6, net: 158.4 },
  revisions: { included: 2, used: 1, extraCost: 20 },
  brief: 'EP 5 tracce, già recorded. Mood notturno, 808 spaziali. Cerco un mix radio-ready ma che mantenga la profondità — riferimento Travis Scott "After Hours" + spazialità su voci stile Frank Ocean. Vorrei master loud ma con dinamica preservata sui crash.',
  specs: [
    { l: "Tracce", v: "5" },
    { l: "Mix incluso", v: "Sì · stereo" },
    { l: "Master", v: "Sì · radio-ready" },
    { l: "Revisioni incluse", v: "2 · usate 1" },
  ],
  stems: [
    { name: "01_intro_stems.zip", size: "412 MB", time: "9 mag · 14:22" },
    { name: "02_vento_stems.zip", size: "388 MB", time: "9 mag · 14:24" },
    { name: "03_asfalto_stems.zip", size: "445 MB", time: "9 mag · 14:30" },
    { name: "04_pioggia_stems.zip", size: "367 MB", time: "9 mag · 14:35" },
    { name: "05_outro_stems.zip", size: "390 MB", time: "9 mag · 14:42" },
  ],
  deliverables: [
    { name: "Asfalto_v1_MIX.zip", size: "186 MB", time: "13 mag · 22:10", version: "v1" },
  ],
  revisionNote: "v1 ottimo, ma 808 troppo grossi sul brano 3 (Asfalto) → vorrei più punch, meno sub. Pulire un po' la riverbero sul ritornello di Vento.",
  autoApprovalDays: 7,
  autoApprovalLeft: "6gg 22h",
  chat: [
    { from: "artist",   t: "8 mag 19:42", text: "Ehi Nico, ti carico stems entro domani." },
    { from: "producer", t: "8 mag 19:55", text: "Perfetto, accetto l'ordine. Ti aggiorno mercoledì con v1." },
    { from: "producer", t: "13 mag 22:10", text: "Caricato v1. Fammi sapere cosa ne pensi." },
    { from: "artist",   t: "14 mag 09:31", text: "Bella v1, lasciami sentire bene poi ti dico." },
  ],
};

/* ────────── Small UI bits ────────── */

const ChevR = () => <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>;

function StatusBadge({ state }) {
  const s = ORDER_STATES[state];
  const cls = { success: "ok", warning: "warn", info: "info", neutral: "muted" }[s.color] || "muted";
  return <span className={`ord-status ${cls}`}>{s.label}</span>;
}

function Timeline({ order }) {
  const cur = ORDER_STATES[order.state].step;
  return (
    <div className="ord-timeline">
      {TIMELINE_STEPS.map((step, i) => {
        const idx = i + 1;
        const done = idx < cur;
        const active = idx === cur;
        return (
          <React.Fragment key={step.k}>
            <div className={`ord-tl-node ${done ? "done" : active ? "active" : ""}`}>
              <div className="ord-tl-circle">
                {done ? <OrdIcons.check size={13}/> : <span className="n">{idx}</span>}
              </div>
              <div className="ord-tl-meta">
                <div className="t">{step.l}</div>
                <div className="s">{step.when(order) || "—"}</div>
              </div>
            </div>
            {idx < TIMELINE_STEPS.length && <div className={`ord-tl-bar ${done ? "done" : ""}`}/>}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function FilesList({ items, icon, emptyText }) {
  if (!items?.length) return <div className="ord-empty">{emptyText}</div>;
  return (
    <div className="ord-file-list">
      {items.map((f, i) => (
        <div className="ord-file-row" key={i}>
          <span className="ic">{icon || <OrdIcons.audioFile size={14}/>}</span>
          <div className="m">
            <div className="n">{f.name}</div>
            <div className="s">{f.size} · {f.time}{f.version ? ` · ${f.version}` : ""}</div>
          </div>
          <button className="ord-file-dl"><OrdIcons.download size={13}/></button>
        </div>
      ))}
    </div>
  );
}

function ChatInline({ order, role }) {
  const [text, setText] = React.useState("");
  return (
    <div className="ord-chat">
      <div className="ord-chat-stream">
        {order.chat.map((m, i) => {
          const me = (role === "artista" && m.from === "artist") || (role === "producer" && m.from === "producer");
          return (
            <div key={i} className={`ord-chat-msg ${me ? "me" : "them"}`}>
              <div className="bubble">{m.text}</div>
              <div className="time">{m.t}</div>
            </div>
          );
        })}
      </div>
      <div className="ord-chat-compose">
        <input className="ipt" placeholder="Scrivi un messaggio…" value={text} onChange={(e) => setText(e.target.value)}/>
        <button className="snd"><OrdIcons.arrowRight size={14}/></button>
      </div>
    </div>
  );
}

/* ────────── ROLE-SPECIFIC ACTION PANELS ────────── */

function ProducerActions({ order, setOrder }) {
  const s = order.state;

  if (s === "pending_acceptance") return (
    <div className="ord-action-card urgent">
      <div className="ord-action-eyebrow"><OrdIcons.clock size={11}/> Devi rispondere entro 47h</div>
      <h3 className="ord-action-title">Vuoi accettare questo ordine?</h3>
      <p className="ord-action-sub">Hai letto il brief e i requisiti? Una volta accettato, il countdown della deadline parte appena l'artista carica gli stems.</p>
      <div className="ord-action-row">
        <button className="ip-btn ghost">Domanda all'artista</button>
        <button className="ip-btn">Rifiuta</button>
        <button className="ip-btn primary lg">Accetta ordine</button>
      </div>
    </div>
  );

  if (s === "awaiting_stems") return (
    <div className="ord-action-card neutral">
      <div className="ord-action-eyebrow"><OrdIcons.clock size={11}/> Countdown deadline in pausa</div>
      <h3 className="ord-action-title">In attesa che l'artista carichi gli stems</h3>
      <p className="ord-action-sub">La deadline contrattuale parte solo dal momento in cui ricevi i file. Se preferisci puoi sollecitarlo.</p>
      <div className="ord-action-row">
        <button className="ip-btn">Sollecita stems</button>
        <button className="ip-btn primary">Apri chat</button>
      </div>
    </div>
  );

  if (s === "in_progress") return (
    <div className="ord-action-card info">
      <div className="ord-action-eyebrow"><OrdIcons.waveform size={11}/> In lavorazione</div>
      <h3 className="ord-action-title">Consegna la prima versione</h3>
      <p className="ord-action-sub">Deadline contrattuale: <strong>16 maggio · 18:00</strong>. Carica il deliverable quando è pronto.</p>
      <div className="ord-action-row">
        <button className="ip-btn">Salva bozza</button>
        <button className="ip-btn primary lg"><OrdIcons.upload size={11}/> Carica v1</button>
      </div>
    </div>
  );

  if (s === "delivered") return (
    <div className="ord-action-card info">
      <div className="ord-action-eyebrow"><OrdIcons.check size={11}/> v1 consegnata · in attesa di feedback</div>
      <h3 className="ord-action-title">L'artista sta valutando la tua consegna</h3>
      <p className="ord-action-sub">Auto-approval tra <strong>{order.autoApprovalLeft}</strong>. Se accetta, l'escrow viene rilasciato automaticamente.</p>
      <div className="ord-action-row">
        <button className="ip-btn">Apri chat</button>
      </div>
    </div>
  );

  if (s === "revision_requested") return (
    <div className="ord-action-card warning">
      <div className="ord-action-eyebrow"><OrdIcons.message size={11}/> Revisione richiesta · {order.revisions.included - order.revisions.used} incluse rimaste</div>
      <h3 className="ord-action-title">Note dell'artista</h3>
      <p className="ord-action-sub" style={{ fontStyle: "italic" }}>"{order.revisionNote}"</p>
      <div className="ord-action-row">
        <button className="ip-btn">Proponi revisione extra (+€{order.revisions.extraCost})</button>
        <button className="ip-btn primary lg"><OrdIcons.upload size={11}/> Carica v2</button>
      </div>
    </div>
  );

  if (s === "completed") return (
    <div className="ord-action-card success">
      <div className="ord-action-eyebrow"><OrdIcons.check size={11}/> Ordine completato · €{order.payment.net} in clearance</div>
      <h3 className="ord-action-title">Lascia una recensione all'artista</h3>
      <p className="ord-action-sub">La sua recensione su di te sarà visibile solo dopo che entrambi avete scritto (o dopo 14gg). Niente bias.</p>
      <div className="ord-action-row">
        <button className="ip-btn primary lg"><OrdIcons.star size={11}/> Scrivi recensione</button>
      </div>
    </div>
  );

  return null;
}

function ArtistActions({ order, setOrder }) {
  const s = order.state;

  if (s === "pending_acceptance") return (
    <div className="ord-action-card neutral">
      <div className="ord-action-eyebrow"><OrdIcons.clock size={11}/> In attesa del producer · 47h rimasti</div>
      <h3 className="ord-action-title">Nico sta valutando il tuo brief</h3>
      <p className="ord-action-sub">Se rifiuta o non risponde entro 48h, riceverai un <strong>refund automatico</strong> sul wallet. I tuoi €180 sono al sicuro in escrow.</p>
      <div className="ord-action-row">
        <button className="ip-btn">Annulla ordine</button>
        <button className="ip-btn primary">Manda messaggio</button>
      </div>
    </div>
  );

  if (s === "awaiting_stems") return (
    <div className="ord-action-card urgent">
      <div className="ord-action-eyebrow"><OrdIcons.upload size={11}/> Manca solo questo per iniziare</div>
      <h3 className="ord-action-title">Carica gli stems</h3>
      <p className="ord-action-sub">Il producer non può partire finché non riceve i file sorgente. Stai bloccando il tuo stesso ordine. Soft-deadline: <strong>entro 7gg</strong> o l'ordine viene cancellato.</p>
      <div className="ord-action-row">
        <button className="ip-btn primary lg"><OrdIcons.upload size={11}/> Carica stems</button>
      </div>
    </div>
  );

  if (s === "in_progress") return (
    <div className="ord-action-card info">
      <div className="ord-action-eyebrow"><OrdIcons.waveform size={11}/> Nico è al lavoro</div>
      <h3 className="ord-action-title">Aspetta la prima versione</h3>
      <p className="ord-action-sub">La consegna è attesa entro <strong>16 maggio · 18:00</strong>. Ti notifichiamo via push + email appena è pronta.</p>
      <div className="ord-action-row">
        <button className="ip-btn">Manda messaggio</button>
      </div>
    </div>
  );

  if (s === "delivered") return (
    <div className="ord-action-card warning">
      <div className="ord-action-eyebrow"><OrdIcons.zap size={11}/> Auto-approval tra {order.autoApprovalLeft}</div>
      <h3 className="ord-action-title">Hai ricevuto la v1 — cosa ne pensi?</h3>
      <p className="ord-action-sub">Ascoltala con calma. Se non rispondi entro <strong>{order.autoApprovalDays}gg</strong>, l'ordine si chiude in automatico e l'escrow va a Nico.</p>
      <div className="ord-action-row">
        <button className="ip-btn">Apri disputa</button>
        <button className="ip-btn">Richiedi revisione</button>
        <button className="ip-btn primary lg"><OrdIcons.check size={11}/> Approva consegna</button>
      </div>
    </div>
  );

  if (s === "revision_requested") return (
    <div className="ord-action-card info">
      <div className="ord-action-eyebrow"><OrdIcons.message size={11}/> Revisione in corso</div>
      <h3 className="ord-action-title">Nico sta lavorando alle tue note</h3>
      <p className="ord-action-sub" style={{ fontStyle: "italic", marginBottom: 8 }}>"{order.revisionNote}"</p>
      <p className="ord-action-sub">Ti aspettiamo entro 2-3 giorni. Una revisione su due usate.</p>
    </div>
  );

  if (s === "completed") return (
    <div className="ord-action-card success">
      <div className="ord-action-eyebrow"><OrdIcons.check size={11}/> Ordine completato · file scaricabili indefinitamente</div>
      <h3 className="ord-action-title">Lascia una recensione</h3>
      <p className="ord-action-sub">Verrà visibile sul profilo di Nico solo dopo che anche lui ne ha scritto una su di te (o dopo 14gg).</p>
      <div className="ord-action-row">
        <button className="ip-btn primary lg"><OrdIcons.star size={11}/> Scrivi recensione</button>
      </div>
    </div>
  );

  return null;
}

/* ────────── MAIN PAGE ────────── */
function OrdinePage() {
  const role = window.SONARA_ROLE || "producer";
  const [order, setOrder] = React.useState(MOCK_ORDER);
  const back = role === "artista" ? "Progetti.html" : "Ordini.html";

  return (
    <main className="page ord-page" data-screen-label={`Ordine ${order.id} · ${role}`}>
      <a href={back} className="ord-back"><OrdIcons.arrowLeft size={13}/> Tutti gli ordini</a>

      {/* HEADER */}
      <header className="ord-header">
        <div className="ord-header-l">
          <div className="ord-header-meta">
            <span className="ord-kind">{order.kind}</span>
            <StatusBadge state={order.state}/>
            <span className="ord-id">{order.id}</span>
          </div>
          <h1 className="ord-title">{order.title}</h1>
          <div className="ord-counter">
            <span className="av">{role === "producer" ? order.artist.init : order.producer.init}</span>
            <span><strong>{role === "producer" ? order.artist.name : order.producer.name}</strong></span>
            {role === "producer" && order.artist.verified && <OrdIcons.verified size={11}/>}
            <span className="sep">·</span>
            <span>{role === "producer" ? order.artist.alias : order.producer.alias}</span>
            <span className="sep">·</span>
            <span>Iniziato il {order.startedOn}</span>
          </div>
        </div>
        <div className="ord-header-r">
          <div className="ord-stat-card">
            <div className="l"><OrdIcons.clock size={11}/> Deadline</div>
            <div className="v hot">Tra {order.deadlineHours}h</div>
            <div className="s">{order.deadline}</div>
          </div>
          {role === "producer" ? (
            <div className="ord-stat-card">
              <div className="l">Netto a te</div>
              <div className="v">€{order.payment.net.toLocaleString("it", { minimumFractionDigits: 2 })}</div>
              <div className="s">In escrow · si libera alla consegna</div>
            </div>
          ) : (
            <div className="ord-stat-card">
              <div className="l">Hai pagato</div>
              <div className="v">€{order.payment.gross}</div>
              <div className="s">In escrow · si libera all'approvazione</div>
            </div>
          )}
        </div>
      </header>

      {/* TIMELINE */}
      <Timeline order={order}/>

      {/* ROLE ACTION CARD */}
      <div className="ord-action-wrap">
        {role === "producer" ? <ProducerActions order={order} setOrder={setOrder}/> : <ArtistActions order={order} setOrder={setOrder}/>}
      </div>

      {/* MAIN GRID */}
      <div className="ord-grid">
        <div className="ord-col">
          <section className="ord-section">
            <header className="ord-section-head">
              <h3>Brief dell'artista</h3>
            </header>
            <p className="ord-brief">{order.brief}</p>
            <div className="ord-specs">
              {order.specs.map((s, i) => (
                <div className="ord-spec" key={i}>
                  <div className="l">{s.l}</div>
                  <div className="v">{s.v}</div>
                </div>
              ))}
            </div>
          </section>

          <section className="ord-section">
            <header className="ord-section-head">
              <h3>Stems ricevuti dall'artista <span className="c">{order.stems.length}</span></h3>
              {role === "producer" && (
                <button className="ord-section-cta"><OrdIcons.download size={12}/> Scarica tutti (ZIP)</button>
              )}
            </header>
            <FilesList items={order.stems} emptyText="Nessuno stem caricato"/>
          </section>

          <section className="ord-section">
            <header className="ord-section-head">
              <h3>Deliverable consegnati dal producer <span className="c">{order.deliverables.length}</span></h3>
              {role === "artista" && order.deliverables.length > 0 && (
                <button className="ord-section-cta"><OrdIcons.download size={12}/> Scarica tutti (ZIP)</button>
              )}
            </header>
            <FilesList items={order.deliverables} emptyText="Ancora niente da scaricare"/>
          </section>

          <section className="ord-section">
            <header className="ord-section-head">
              <h3>Chat dell'ordine</h3>
              <button className="ord-section-cta">Apri in Messaggi <ChevR/></button>
            </header>
            <ChatInline order={order} role={role}/>
          </section>
        </div>

        <aside className="ord-col aside">
          <section className="ord-section">
            <header className="ord-section-head">
              <h3>Pagamento</h3>
              <span className={`ord-pay-pill ${order.state === "completed" ? "ok" : "wait"}`}>
                {order.state === "completed" ? "RILASCIATO" : "IN ESCROW"}
              </span>
            </header>
            <div className="ord-pay-body">
              {role === "producer" ? (
                <>
                  <div className="ord-pay-row"><span>Lordo cliente</span><span>€{order.payment.gross.toFixed(2)}</span></div>
                  <div className="ord-pay-row"><span>Fee Sonara (12%)</span><span>– €{order.payment.fee.toFixed(2)}</span></div>
                  <div className="ord-pay-row total"><span>Netto a te</span><span>€{order.payment.net.toFixed(2)}</span></div>
                </>
              ) : (
                <>
                  <div className="ord-pay-row"><span>Totale ordine</span><span>€{order.payment.gross.toFixed(2)}</span></div>
                  <div className="ord-pay-row sub"><span>(comprende fee piattaforma)</span></div>
                  <div className="ord-pay-row total"><span>Pagato</span><span>€{order.payment.gross.toFixed(2)}</span></div>
                </>
              )}
              <div className="ord-pay-note">
                <OrdIcons.info size={11}/>
                {role === "producer"
                  ? "Il pagamento si sblocca quando l'artista approva la consegna. Auto-approval dopo 7gg dalla v consegnata."
                  : "I tuoi soldi sono protetti in escrow. Vengono rilasciati a Nico solo dopo che approvi tu la consegna."}
              </div>
            </div>
          </section>

          <section className="ord-section">
            <header className="ord-section-head"><h3>Tempi</h3></header>
            <div className="ord-times">
              <div className="r"><span>Ordine accettato</span><span>8 maggio 2026 · 19:42</span></div>
              <div className="r"><span>Deadline contrattuale</span><span>{order.deadline}</span></div>
              <div className="r"><span>Revisioni</span><span>{order.revisions.used} usate · {order.revisions.included - order.revisions.used} rimanenti</span></div>
              {role === "producer" && (
                <button className="ord-times-cta">Proponi revisione extra (+€{order.revisions.extraCost})</button>
              )}
            </div>
          </section>

          <section className="ord-section">
            <header className="ord-section-head">
              <h3>{role === "producer" ? "Cliente" : "Producer"}</h3>
              <button className="ord-section-cta">Profilo <ChevR/></button>
            </header>
            {role === "producer" ? (
              <div className="ord-counter-card">
                <span className="av lg">{order.artist.init}</span>
                <div className="meta">
                  <div className="n">{order.artist.name} {order.artist.verified && <OrdIcons.verified size={11}/>}</div>
                  <div className="s">{order.artist.alias} · {order.artist.city} · {order.artist.age} anni</div>
                  <div className="s2">★ {order.artist.rating} · {order.artist.orders} ordini su Sonara</div>
                </div>
              </div>
            ) : (
              <div className="ord-counter-card">
                <span className="av lg">{order.producer.init}</span>
                <div className="meta">
                  <div className="n">{order.producer.name} {order.producer.verified && <OrdIcons.verified size={11}/>}</div>
                  <div className="s">{order.producer.alias} · {order.producer.city}</div>
                  <div className="s2">★ {order.producer.rating} · Top Rated</div>
                </div>
              </div>
            )}
          </section>

          <section className="ord-section danger-zone">
            <header className="ord-section-head"><h3>Azioni</h3></header>
            <button className="ord-danger-btn">Annulla d'accordo</button>
            <button className="ord-danger-btn">Apri disputa</button>
            <button className="ord-danger-btn red">Segnala problema</button>
            <div className="ord-danger-note">
              L'annullamento richiede l'accordo di entrambi · refund completo. La disputa è solo per casi gravi.
            </div>
          </section>
        </aside>
      </div>
    </main>
  );
}

window.OrdinePage = OrdinePage;
window.SONARA_ORDER_STATES = ORDER_STATES;
window.SONARA_MOCK_ORDER = MOCK_ORDER;
