// SONARA — Producer Messaggi (chat con quick replies + ti aspetta indicator)
const MIcons = window.SonaraIcons;

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 VerifIc = ({ 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 PaperclipIc = ({ 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.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>;
const MicIc = ({ 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="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v4M8 23h8"/></svg>;
const SendIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M2 21l21-9L2 3v7l15 2-15 2v7z"/></svg>;
const BoltIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M13 2L4.09 12.97a.5.5 0 0 0 .38.82h6.03l-1.49 7.42a.5.5 0 0 0 .89.37l8.91-10.97A.5.5 0 0 0 18.42 10h-5.92l1.4-7.45A.5.5 0 0 0 13 2z"/></svg>;
const PlayIc = ({ size = 10 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9V3z"/></svg>;
const InfoIc = ({ size = 13 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>;

const THREADS = [
  {
    id: "T1",
    who: "RAZZA",
    init: "RZ",
    verified: true,
    online: true,
    project: "Mix EP \"Asfalto\" · ORD-4821",
    preview: "Perfetto, aspetto la v2 ✌️ ti faccio sentire anche un riferimento",
    time: "8m",
    unread: 2,
    waitsHours: 0,
    messages: [
      { from: "them", text: "Ciao Nico! Ho ascoltato la v1, suona super pulita 🔥", time: "Ieri · 17:42" },
      { from: "them", text: "Però su \"Vento\" sento la cassa un po' bassa rispetto agli altri brani. Puoi alzarla di qualcosa? Tipo 2-3 dB?", time: "Ieri · 17:44" },
      { from: "me", text: "Ciao! Sì confermo, anche io l'ho notata. La sistemo nella v2.", time: "Ieri · 18:12", read: true },
      { from: "me", text: "Mi serve un attimo per allineare anche le 808 sul minuto 2:15 — c'era un piccolo fade strano. Ti consegno entro domani sera.", time: "Ieri · 18:13", read: true },
      { from: "them", text: "Perfetto, aspetto la v2 ✌️ ti faccio sentire anche un riferimento", time: "8m fa" },
      { from: "them", type: "voice", duration: "0:23", time: "5m fa" },
    ],
    files: 3,
  },
  {
    id: "T2",
    who: "Yoshi K.",
    init: "YK",
    verified: true,
    online: true,
    project: "Beat esclusivo \"Notturno\" · ORD-4815",
    preview: "Mi piacciono i riferimenti che hai mandato. Quanto per esclusiva?",
    time: "1h",
    unread: 1,
    waitsHours: 0,
    messages: [],
    files: 1,
  },
  {
    id: "T3",
    who: "Sara D.",
    init: "SD",
    verified: false,
    online: false,
    project: "Vocal production \"Senza Te\" · ORD-4801",
    preview: "Ti mando gli stems entro stasera, scusa il ritardo",
    time: "Ieri",
    unread: 1,
    waitsHours: 0,
    messages: [],
    files: 0,
  },
  {
    id: "T4",
    who: "M. Lentini",
    init: "ML",
    verified: false,
    online: false,
    project: "Mix \"Mezzanotte\" · chiuso",
    preview: "Ricevuti, suono pulitissimo. Procedo con il pagamento finale",
    time: "2gg",
    unread: 0,
    waitsHours: 48,
    messages: [],
    files: 2,
  },
  {
    id: "T5",
    who: "AlessioRap",
    init: "AR",
    verified: false,
    online: false,
    project: "Pre-deal · richiesta REQ-9214",
    preview: "Ti ho mandato la mia offerta, vediamo se ti torna 👀",
    time: "3gg",
    unread: 0,
    waitsHours: 0,
    messages: [],
    files: 0,
    predeal: true,
  },
  {
    id: "T6",
    who: "Lina Sky",
    init: "LS",
    verified: false,
    online: false,
    project: "Custom prod R&B · ORD-4821",
    preview: "Grande, grazie! Aspetto le prime idee 🙏",
    time: "1 sett.",
    unread: 0,
    waitsHours: 0,
    messages: [],
    files: 0,
  },
];

const QUICK_REPLIES = [
  "Sto lavorando, ti aggiorno entro 24h",
  "Ho ricevuto tutto, mi metto al lavoro",
  "Pronto, dai un'occhiata 🎧",
  "Posso fare una revisione extra a €20",
  "Confermo deadline",
];

/* ─────── THREAD LIST ITEM ─────── */
function ThreadRow({ t, active, onClick }) {
  return (
    <button className={`mp-thread ${active ? "active" : ""} ${t.unread > 0 ? "unread" : ""}`} onClick={onClick}>
      <div className="mp-thread-av">
        {t.init}
        {t.online && <span className="mp-online"/>}
      </div>
      <div className="mp-thread-body">
        <div className="mp-thread-row1">
          <span className="mp-thread-who">
            {t.who}
            {t.verified && <span className="mp-verif"><VerifIc size={10}/></span>}
          </span>
          <span className="mp-thread-time">{t.time}</span>
        </div>
        <div className="mp-thread-project">{t.project}</div>
        <div className="mp-thread-preview">{t.preview}</div>
        <div className="mp-thread-foot">
          {t.waitsHours > 0 && (
            <span className="mp-waits"><BoltIc size={9}/> Ti aspetta da {t.waitsHours >= 24 ? Math.round(t.waitsHours/24) + "gg" : t.waitsHours + "h"}</span>
          )}
          {t.predeal && <span className="mp-predeal">Pre-deal · anti-disinterm.</span>}
          <span className="mp-spacer"/>
          {t.unread > 0 && <span className="mp-unread-pill">{t.unread}</span>}
        </div>
      </div>
    </button>
  );
}

/* ─────── MESSAGE BUBBLE ─────── */
function Bubble({ m }) {
  const mine = m.from === "me";
  if (m.type === "voice") {
    return (
      <div className={`mp-bubble ${mine ? "mine" : "theirs"} voice`}>
        <button className="mp-voice-play"><PlayIc size={11}/></button>
        <div className="mp-voice-wave">
          {Array.from({ length: 22 }).map((_, i) => (
            <span key={i} style={{ height: `${20 + Math.abs(Math.sin(i * 1.3)) * 70}%` }}/>
          ))}
        </div>
        <div className="mp-voice-dur">{m.duration}</div>
        <div className="mp-bubble-time">{m.time}</div>
      </div>
    );
  }
  return (
    <div className={`mp-bubble ${mine ? "mine" : "theirs"}`}>
      <div className="mp-bubble-text">{m.text}</div>
      <div className="mp-bubble-time">{m.time}{mine && m.read && " · letto"}</div>
    </div>
  );
}

/* ─────── CHAT VIEW ─────── */
function ChatView({ t }) {
  const [draft, setDraft] = React.useState("");
  const [showQuick, setShowQuick] = React.useState(false);

  return (
    <div className="mp-chat">
      <div className="mp-chat-head">
        <div className="mp-chat-head-l">
          <div className="mp-thread-av big">
            {t.init}
            {t.online && <span className="mp-online big"/>}
          </div>
          <div>
            <div className="mp-chat-who">
              {t.who}
              {t.verified && <span className="mp-verif"><VerifIc size={10}/></span>}
              {t.online && <span className="mp-online-txt">● online</span>}
            </div>
            <div className="mp-chat-project">{t.project}</div>
          </div>
        </div>
        <div className="mp-chat-head-r">
          <a href="Ordine.html" className="ord-btn ghost">Vai all'ordine →</a>
          <button className="cat-icon-btn"><InfoIc size={14}/></button>
        </div>
      </div>

      {t.predeal && (
        <div className="mp-banner">
          <InfoIc size={13}/>
          <div>
            <strong>Anti-disintermediation attivo</strong> — questa chat è pre-deal: contatti diretti, IBAN e link a piattaforme esterne vengono mascherati. Per pagamenti tracciati e dispute mediation, mantieni le transazioni qui.
          </div>
        </div>
      )}

      <div className="mp-thread-msgs">
        <div className="mp-day-sep"><span>Ieri</span></div>
        {t.messages.filter(m => m.time.startsWith("Ieri")).map((m, i) => <Bubble m={m} key={i}/>)}
        <div className="mp-day-sep"><span>Oggi</span></div>
        {t.messages.filter(m => !m.time.startsWith("Ieri")).map((m, i) => <Bubble m={m} key={`o${i}`}/>)}
      </div>

      <div className="mp-composer-wrap">
        {showQuick && (
          <div className="mp-quick">
            <div className="mp-quick-head">
              <BoltIc size={11}/> Risposte rapide
              <span className="mp-quick-hint">Tocca per inserire</span>
            </div>
            <div className="mp-quick-list">
              {QUICK_REPLIES.map((q, i) => (
                <button key={i} className="mp-quick-item" onClick={() => { setDraft(q); setShowQuick(false); }}>{q}</button>
              ))}
              <button className="mp-quick-add">+ Gestisci templates</button>
            </div>
          </div>
        )}
        <div className="mp-composer">
          <button className="cat-icon-btn" title="Allega"><PaperclipIc size={15}/></button>
          <button className={`cat-icon-btn ${showQuick ? "active" : ""}`} title="Risposte rapide" onClick={() => setShowQuick(!showQuick)}>
            <BoltIc size={14}/>
          </button>
          <textarea
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder={`Scrivi a ${t.who}…`}
            rows={1}
          />
          <button className="cat-icon-btn" title="Vocale"><MicIc size={15}/></button>
          <button className="mp-send" disabled={draft.length === 0}><SendIc size={14}/></button>
        </div>
      </div>
    </div>
  );
}

/* ─────── PAGE ─────── */
function MessaggiPage() {
  const [selected, setSelected] = React.useState("T1");
  const [filter, setFilter] = React.useState("all"); // all | unread | waiting | predeal
  const t = THREADS.find(x => x.id === selected);

  let items = THREADS;
  if (filter === "unread") items = items.filter(x => x.unread > 0);
  if (filter === "waiting") items = items.filter(x => x.waitsHours > 0);
  if (filter === "predeal") items = items.filter(x => x.predeal);

  return (
    <main className="page mp-page" data-screen-label="Messaggi Producer">
      <div className="mp-layout">
        <aside className="mp-feed">
          <div className="mp-feed-head">
            <div className="mp-feed-title">Messaggi <span className="c">{THREADS.filter(x => x.unread > 0).length}</span></div>
          </div>
          <div className="mp-feed-search">
            <SearchIc size={14}/>
            <input placeholder="Cerca per nome o progetto…"/>
          </div>
          <div className="ord-chips" style={{ padding: "0 12px 10px", margin: 0 }}>
            {[
              { v: "all", l: "Tutte" },
              { v: "unread", l: "Da leggere" },
              { v: "waiting", l: "Ti aspettano" },
              { v: "predeal", l: "Pre-deal" },
            ].map(c => (
              <button key={c.v} className={`cat-chip ${filter === c.v ? "active" : ""}`} onClick={() => setFilter(c.v)}>{c.l}</button>
            ))}
          </div>
          <div className="mp-feed-list">
            {items.map(t => <ThreadRow key={t.id} t={t} active={t.id === selected} onClick={() => setSelected(t.id)}/>)}
            {items.length === 0 && (
              <div className="cat-empty" style={{ padding: "40px 16px", margin: 14 }}>
                <div className="t">Nessuna chat</div>
                <div className="s">Cambia filtro per vedere altre conversazioni.</div>
              </div>
            )}
          </div>
        </aside>
        <div className="mp-chat-wrap">
          {t ? <ChatView t={t}/> : null}
        </div>
      </div>
    </main>
  );
}

window.MessaggiPage = MessaggiPage;
