/* ============================================================
   SYMPHO · EB — Mensajería interna (IM), como sidebar derecho
   colapsable (estilo Teams/Office). Busca a cualquier persona
   de la red — Master Dealer y agencias — y envía mensajes.
   ============================================================ */

function EbChatSidebar({ open, onClose }) {
  const nav = useNav();
  const contacts = window.EB_CHAT_CONTACTS;
  const [q, setQ] = useState("");
  const [activeId, setActiveId] = useState(null);
  const [threads, setThreads] = useState(() => JSON.parse(JSON.stringify(window.EB_CHAT_THREADS)));
  const [msg, setMsg] = useState("");

  if (!nav || nav.loc.view !== "app" || nav.loc.appId !== "eb") return null;

  const filtered = contacts.filter(c =>
    !q.trim() || c.name.toLowerCase().includes(q.toLowerCase()) || c.org.toLowerCase().includes(q.toLowerCase()));
  const active = contacts.find(c => c.id === activeId);
  const grouped = filtered.reduce((acc, c) => { (acc[c.org] = acc[c.org] || []).push(c); return acc; }, {});

  function send(e) {
    e.preventDefault();
    if (!msg.trim()) return;
    setThreads(t => ({ ...t, [activeId]: [...(t[activeId] || []), { from: "me", text: msg, time: "ahora" }] }));
    setMsg("");
  }

  return (
    <aside className="eb-chat-side" data-open={open}>
      <div className="eb-chat-side-head">
        {active ? (
          <>
            <button className="ic-btn" style={{ width: 30, height: 30 }} onClick={() => setActiveId(null)}><Icon name="chevright" size={15} style={{ transform: "rotate(180deg)" }} /></button>
            <Avatar name={active.name} initials={active.initials} hue={active.hue} size={28} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <b style={{ fontSize: 13, display: "block" }}>{active.name}</b>
              <span className="muted" style={{ fontSize: 10.5 }}>{active.org}{active.online ? " · en línea" : ""}</span>
            </div>
          </>
        ) : (
          <>
            <span className="feed-ic" style={{ "--c": "var(--eb)", width: 28, height: 28 }}><Icon name="contacts" size={14} /></span>
            <b style={{ fontSize: 14, flex: 1 }}>Mensajería</b>
          </>
        )}
        <button className="ic-btn" style={{ width: 30, height: 30 }} onClick={onClose} title="Ocultar panel"><Icon name="ext" size={14} /></button>
      </div>

      {!active ? (
        <>
          <div className="eb-chat-search">
            <input className="field" value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar en la red…" style={{ height: 34 }} />
          </div>
          <div className="eb-chat-contacts scroll">
            {Object.keys(grouped).map(org => (
              <div key={org}>
                <div className="eyebrow" style={{ padding: "10px 14px 4px" }}>{org}</div>
                {grouped[org].map(c => (
                  <div key={c.id} className="eb-chat-row" onClick={() => setActiveId(c.id)}>
                    <Avatar name={c.name} initials={c.initials} hue={c.hue} size={30} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--text)" }}>{c.name}</div>
                      <div className="muted" style={{ fontSize: 10.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.role}</div>
                    </div>
                    {c.online && <span className="dot" style={{ background: "var(--ok)" }} />}
                  </div>
                ))}
              </div>
            ))}
            {!filtered.length && <div className="muted" style={{ padding: 20, fontSize: 12, textAlign: "center" }}>Sin resultados para "{q}"</div>}
          </div>
        </>
      ) : (
        <>
          <div className="eb-chat-thread scroll">
            {(threads[activeId] || []).length === 0 && (
              <div className="muted" style={{ margin: "auto", fontSize: 12 }}>Aún no hay mensajes.</div>
            )}
            {(threads[activeId] || []).map((m, i) => (
              <div key={i} className="eb-chat-bubble" data-me={m.from === "me"}>
                {m.text}
                <div className="eb-chat-time">{m.time}</div>
              </div>
            ))}
          </div>
          <form className="eb-chat-input" onSubmit={send}>
            <input className="field" value={msg} onChange={e => setMsg(e.target.value)} placeholder="Escribe un mensaje…" style={{ flex: 1, height: 34 }} />
            <button className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }}><Icon name="arrowr" size={13} /></button>
          </form>
        </>
      )}
    </aside>
  );
}

function EbChatToggle() {
  const nav = useNav();
  if (!nav || nav.loc.view !== "app" || nav.loc.appId !== "eb") return null;
  return (
    <button className="ic-btn" data-on={nav.ebChatOpen} title="Mensajería interna" onClick={() => nav.setEbChatOpen(v => !v)}>
      <Icon name="contacts" size={17} />
    </button>
  );
}

Object.assign(window, { EbChatSidebar, EbChatToggle });
