// SONARA — Messaggi page (artista)
const MIcons = window.SonaraIcons;

// ============= DATA =============
const CHATS_DATA = [
  {
    id: "c1",
    name: "Marco Vega",
    initials: "MV",
    avatarTone: "violet",
    online: true,
    verified: true,
    context: { type: "project", label: "Mix Pro · 'Fade Away'", projectId: "p-4821" },
    lastTime: "14:32",
    unread: 2,
    preview: "Ti ho mandato la v2 con il low-end un po' più caldo, fammi sapere se cambi qualcosa…",
    role: "Mix engineer · @marcovega",
    messages: [
      { id: "m1", who: "them", time: "13:24", body: "Ciao Luca! Ho lavorato sulla traccia oggi pomeriggio.", day: "Oggi" },
      { id: "m2", who: "them", time: "13:25", body: "Ho fatto una passata di EQ sulle voci, ridotto un po' la sibilanza e bilanciato le armonie nel ritornello." },
      { id: "m3", who: "them", time: "13:26", body: "kind: attach", attach: { name: "Fade Away — Mix v2.wav", size: "3:42 · 78 MB", kind: "audio" } },
      { id: "m4", who: "me",   time: "14:02", body: "Top, ascolto e ti dico subito 🙏" },
      { id: "m5", who: "me",   time: "14:18", body: "Ok il mix è solidissimo. Solo: il basso secondo me va un filo giù tra 1:48 e 2:10, schiaccia la voce nel break." },
      { id: "m6", who: "them", time: "14:32", body: "Ti ho mandato la v2 con il low-end un po' più caldo, fammi sapere se cambi qualcosa." },
    ],
  },
  {
    id: "c2",
    name: "Sara K.",
    initials: "SK",
    avatarTone: "pink",
    online: true,
    verified: true,
    context: { type: "predeal" },
    lastTime: "12:15",
    unread: 1,
    preview: "Ciao, ho letto la tua richiesta. Ti scrivo dal mio numero personale 3331234… [contatto nascosto]",
    role: "Vocal producer · @sarak",
    messages: [
      { id: "m1", who: "them", time: "12:08", body: "Ciao Luca, ho letto la tua richiesta open per il vocal coach.", day: "Oggi" },
      { id: "m2", who: "them", time: "12:09", body: "Lavoro con artisti R&B/soul, posso aiutarti su tecnica e arrangement vocale. Sentiamoci in call?" },
      { id: "m3", who: "them", time: "12:15", body: { type: "masked", parts: [
        { kind: "text", value: "Ciao, ti scrivo direttamente al mio numero personale " },
        { kind: "mask", reason: "phone", placeholder: "[contatto nascosto — accetta prima l'offerta]" },
        { kind: "text", value: " così sentiamo subito. Oppure email " },
        { kind: "mask", reason: "email", placeholder: "[contatto nascosto]" },
        { kind: "text", value: "." },
      ]} },
    ],
  },
  {
    id: "c3",
    name: "Hearfield Studio",
    initials: "HS",
    avatarTone: "muted-color",
    online: false,
    verified: true,
    context: { type: "project", label: "Mastering · 'Velvet EP'", projectId: "p-4756" },
    lastTime: "ieri",
    unread: 0,
    preview: "Tutto pronto! I master sono già stati caricati nella sezione progetto.",
    role: "Mastering studio",
    messages: [],
  },
  {
    id: "c4",
    name: "@nightowl",
    initials: "NO",
    avatarTone: "amber",
    online: false,
    verified: true,
    context: { type: "predeal" },
    lastTime: "ieri",
    unread: 0,
    preview: "Ti mando l'offerta entro fine giornata 🙏",
    role: "Beatmaker · @nightowl",
    messages: [],
  },
  {
    id: "c5",
    name: "@luxx",
    initials: "LX",
    avatarTone: "green",
    online: true,
    verified: true,
    context: { type: "predeal" },
    lastTime: "lun",
    unread: 0,
    preview: "Tu: Ascoltato! Lo prendo, ti scrivo dopo per i dettagli.",
    role: "Producer · @luxx",
    messages: [],
  },
  {
    id: "c6",
    name: "@desertcat",
    initials: "DC",
    avatarTone: "violet",
    online: false,
    verified: false,
    context: { type: "predeal" },
    lastTime: "27 apr",
    unread: 0,
    preview: "Ok grazie, alla prossima!",
    role: "Producer · @desertcat",
    messages: [],
  },
];

// ============= ICONS =============
const SendIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
);
const SearchIc = ({ size = 16 }) => (
  <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"/><path d="M21 21l-4.35-4.35"/></svg>
);
const VerifiedIc = ({ 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 = 18 }) => (
  <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 = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2"/><line x1="12" y1="19" x2="12" y2="22"/></svg>
);
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 PhoneIc = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
);
const VideoIc = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>
);
const DotsIc = ({ size = 16 }) => (
  <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 ArrowLeftIc = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
);
const ShieldIc = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
);
const CloseIc = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
);
const FolderIc = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
);
const SmileIc = ({ size = 18 }) => (
  <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"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>
);
const AudioIc = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" 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>
);
const CheckCheckIc = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 11 7 15 17 5"/><polyline points="11 11 15 15 21 9"/></svg>
);

// ============= LIST ITEM =============
function ChatItem({ chat, active, onClick }) {
  return (
    <div className={`msgs-item ${active ? "active" : ""} ${chat.unread > 0 ? "unread" : ""}`} onClick={onClick}>
      <div className={`msgs-avatar ${chat.online ? "online" : ""} ${chat.avatarTone}`}>
        {chat.initials}
      </div>
      <div className="msgs-body">
        {chat.context.type === "project" && (
          <span className="msgs-context project">
            <FolderIc size={10}/>
            Progetto
          </span>
        )}
        {chat.context.type === "predeal" && (
          <span className="msgs-context predeal">
            🔒 Pre-deal
          </span>
        )}
        <div className="msgs-row1">
          <span className="msgs-name">{chat.name}</span>
          {chat.verified && <span className="msgs-verified"><VerifiedIc size={12}/></span>}
        </div>
        <div className="msgs-preview">{chat.preview}</div>
      </div>
      <div className="msgs-right">
        <span className="msgs-time">{chat.lastTime}</span>
        {chat.unread > 0 && <span className="msgs-unread-dot">{chat.unread}</span>}
      </div>
    </div>
  );
}

// ============= MESSAGE BUBBLE =============
function MessageBubble({ msg, prevWho, chat }) {
  const mine = msg.who === "me";
  const showAv = !mine && (!prevWho || prevWho !== msg.who);

  // Voice / attach detection
  const body = msg.body;
  let renderedBody;

  if (msg.kind === "voice" || (typeof body === "object" && body?.type === "voice")) {
    renderedBody = (
      <div className="msgs-voice">
        <button className="msgs-voice-play"><PlayIc size={11}/></button>
        <div className="msgs-voice-wave">
          {[8, 14, 22, 10, 18, 24, 14, 20, 12, 26, 16, 22, 10, 18, 14, 22, 10, 16, 20, 14, 8, 16].map((h, i) => (
            <span key={i} style={{ height: h + "px" }}/>
          ))}
        </div>
        <span className="msgs-voice-dur">0:18</span>
      </div>
    );
  } else if (msg.body === "kind: attach" || msg.attach) {
    const a = msg.attach;
    renderedBody = (
      <div className="msgs-attach-bubble">
        <span className="ic"><AudioIc size={16}/></span>
        <div className="meta">
          <div className="n">{a.name}</div>
          <div className="s">{a.size}</div>
        </div>
      </div>
    );
  } else if (typeof body === "object" && body?.type === "masked") {
    renderedBody = (
      <>
        {body.parts.map((p, i) => p.kind === "text"
          ? <span key={i}>{p.value}</span>
          : <span key={i} className="msgs-masked" title="Visibile dopo l'accordo"><ShieldIc size={11}/>{p.placeholder}</span>
        )}
      </>
    );
  } else {
    renderedBody = body;
  }

  return (
    <div className={`msgs-bubble-row ${mine ? "mine" : ""}`}>
      {showAv && <div className="msgs-bubble-av">{chat.initials}</div>}
      {!showAv && !mine && <div style={{ width: 28 }}/>}
      <div>
        <div className="msgs-bubble">{renderedBody}</div>
        <div className="msgs-bubble-time">
          {msg.time}
          {mine && <span className="check"> <CheckCheckIc size={12}/></span>}
        </div>
      </div>
    </div>
  );
}

// ============= THREAD =============
function Thread({ chat, onBack }) {
  const [draft, setDraft] = React.useState("");

  if (!chat) {
    return (
      <section className="msgs-thread">
        <div className="msgs-thread-empty">
          <div className="ic"><MIcons.connect size={26}/></div>
          <div className="t">Seleziona una conversazione</div>
          <div className="s">Apri una chat dalla lista a sinistra per leggere i messaggi e rispondere.</div>
        </div>
      </section>
    );
  }

  const showBanner = chat.context.type === "predeal";

  return (
    <section className="msgs-thread">
      <header className="msgs-thread-head">
        <button className="msgs-back" onClick={onBack}><ArrowLeftIc size={16}/></button>
        <div className="msgs-thread-info">
          <div className={`av ${chat.online ? "online" : ""} ${chat.avatarTone}`}>{chat.initials}</div>
          <div className="meta">
            <div className="name-row">
              <span className="name">{chat.name}</span>
              {chat.verified && <span className="verified"><VerifiedIc size={13}/></span>}
            </div>
            <div className="sub">
              {chat.online && <span className="dot-online"/>}
              {chat.online ? "Online ora" : `Visto ${chat.lastTime}`} · {chat.role}
            </div>
          </div>
        </div>
        <div className="msgs-thread-actions">
          <button className="msgs-thread-action" title="Chiamata"><PhoneIc size={15}/></button>
          <button className="msgs-thread-action" title="Video"><VideoIc size={15}/></button>
          <button className="msgs-thread-action" title="Altro"><DotsIc size={15}/></button>
        </div>
      </header>

      {chat.context.type === "project" && (
        <div className="msgs-thread-context">
          <span className="ic"><FolderIc size={13}/></span>
          <span>Stai chattando su <strong>{chat.context.label}</strong></span>
          <a className="link">Apri progetto →</a>
        </div>
      )}

      {showBanner && (
        <div className="msgs-banner">
          <div className="ic">🔒</div>
          <div className="body">
            <div className="t">Chat pre-deal protetta</div>
            <div className="s">I contatti diretti (telefono, email, social) sono nascosti finché non accetti un'offerta. Lo facciamo per proteggerti — tutti i pagamenti vivono in escrow Sonara.</div>
          </div>
          <button className="dismiss" title="Nascondi"><CloseIc size={14}/></button>
        </div>
      )}

      <div className="msgs-messages">
        {chat.messages.length > 0 && <div className="msgs-day-sep">{chat.messages[0].day}</div>}
        {chat.messages.map((m, i) => (
          <MessageBubble key={m.id} msg={m} prevWho={i > 0 ? chat.messages[i-1].who : null} chat={chat}/>
        ))}
      </div>

      <div className="msgs-composer">
        <div className="msgs-composer-wrap">
          <div className="msgs-composer-attach">
            <button className="msgs-composer-icon" title="Allega file"><PaperclipIc size={18}/></button>
            <button className="msgs-composer-icon" title="Voice memo"><MicIc size={18}/></button>
            <button className="msgs-composer-icon" title="Emoji"><SmileIc size={18}/></button>
          </div>
          <textarea
            className="msgs-composer-input"
            placeholder={showBanner ? "Scrivi un messaggio… (i contatti diretti vengono mascherati)" : "Scrivi un messaggio…"}
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            rows={1}
          />
          <button className="msgs-composer-send" disabled={!draft.trim()}>
            <SendIcon size={16}/>
          </button>
        </div>
      </div>
    </section>
  );
}

// ============= LIST =============
function ChatList({ active, onSelect }) {
  const [filter, setFilter] = React.useState("all");
  const [query, setQuery] = React.useState("");

  const filtered = React.useMemo(() => {
    let list = CHATS_DATA;
    if (filter === "unread") list = list.filter(c => c.unread > 0);
    if (filter === "projects") list = list.filter(c => c.context.type === "project");
    if (filter === "predeal") list = list.filter(c => c.context.type === "predeal");
    if (query) {
      const q = query.toLowerCase();
      list = list.filter(c => c.name.toLowerCase().includes(q) || c.preview.toLowerCase().includes(q));
    }
    return list;
  }, [filter, query]);

  const counts = {
    unread: CHATS_DATA.filter(c => c.unread > 0).length,
    projects: CHATS_DATA.filter(c => c.context.type === "project").length,
    predeal: CHATS_DATA.filter(c => c.context.type === "predeal").length,
  };

  return (
    <aside className="msgs-list-panel">
      <div className="msgs-list-head">
        <div className="msgs-list-title">
          <span className="t">Messaggi</span>
          {counts.unread > 0 && <span className="count">{counts.unread} non letti</span>}
        </div>
        <div className="msgs-search">
          <SearchIc size={16}/>
          <input placeholder="Cerca chat…" value={query} onChange={(e) => setQuery(e.target.value)}/>
        </div>
      </div>
      <div className="msgs-list-filters">
        <button className={`msgs-list-filter ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>Tutti</button>
        <button className={`msgs-list-filter ${filter === "unread" ? "active" : ""}`} onClick={() => setFilter("unread")}>
          Non letti
          {counts.unread > 0 && <span className="num">{counts.unread}</span>}
        </button>
        <button className={`msgs-list-filter ${filter === "projects" ? "active" : ""}`} onClick={() => setFilter("projects")}>Progetti</button>
        <button className={`msgs-list-filter ${filter === "predeal" ? "active" : ""}`} onClick={() => setFilter("predeal")}>Pre-deal</button>
      </div>
      <div className="msgs-list">
        {filtered.map(c => (
          <ChatItem key={c.id} chat={c} active={active === c.id} onClick={() => onSelect(c.id)}/>
        ))}
      </div>
    </aside>
  );
}

// ============= PAGE =============
function MessaggiPage() {
  const [activeId, setActiveId] = React.useState("c1");
  const chat = CHATS_DATA.find(c => c.id === activeId);

  return (
    <div className={`msgs-shell ${activeId ? "thread-open" : ""}`} data-screen-label="Messaggi">
      <ChatList active={activeId} onSelect={setActiveId}/>
      <Thread chat={chat} onBack={() => setActiveId(null)}/>
    </div>
  );
}

window.MessaggiPage = MessaggiPage;
