// Workspace · Chat tab — WhatsApp-style messaging
function ChatTab() {
  const { useState, useEffect, useRef } = React;
  const [chats, setChats] = useState(D.chat);
  const [active, setActive] = useState(D.chat[0].id);
  const [q, setQ] = useState("");
  const [draft, setDraft] = useState("");
  const [mobileList, setMobileList] = useState(true);
  const bodyRef = useRef(null);
  const wrapRef = useRef(null);

  useEffect(() => { D.chat = chats; }, [chats]);

  // size the chat card to exactly fill the rest of the viewport (footer always visible)
  useEffect(() => {
    const fit = () => {
      const el = wrapRef.current;
      if (!el) return;
      const top = el.getBoundingClientRect().top;
      el.style.height = Math.max(380, window.innerHeight - top - 20) + "px";
    };
    fit();
    const t = setTimeout(fit, 80);
    window.addEventListener("resize", fit);
    window.addEventListener("verp-kpis", fit);
    return () => { clearTimeout(t); window.removeEventListener("resize", fit); window.removeEventListener("verp-kpis", fit); };
  }, []);

  const chat = chats.find((c) => c.id === active);

  // scroll to newest message
  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [active, chat ? chat.msgs.length : 0]);

  const openChat = (id) => {
    setActive(id);
    setMobileList(false);
    setChats((cs) => cs.map((c) => (c.id === id ? { ...c, unread: 0 } : c)));
  };

  const send = () => {
    const v = draft.trim();
    if (!v) return;
    setChats((cs) => cs.map((c) => (c.id === active
      ? { ...c, msgs: [...c.msgs, { who: "me", text: v, time: "11:42", day: "Today" }] }
      : c)));
    setDraft("");
  };

  const last = (c) => c.msgs[c.msgs.length - 1];
  const visible = chats.filter((c) => q === "" || c.name.toLowerCase().includes(q.toLowerCase()));

  return (
    <section className="card chatwrap" ref={wrapRef}>
      {/* conversation list */}
      <div className={"chat-list" + (mobileList ? " show" : "")}>
        <div className="chat-search">
          <div className="searchbox" style={{ width: "100%" }}>
            <Icon name="search" size={15} />
            <input placeholder={T("chat.searchChats")} value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
        </div>
        {visible.map((c) => (
          <button key={c.id} className={"chat-row" + (c.id === active ? " on" : "")} onClick={() => openChat(c.id)}>
            <Avatar name={c.name} size={38} />
            <span className="chat-row-main">
              <span className="chat-row-top">
                <b>{c.name}</b>
                <small className="mono">{last(c).time}</small>
              </span>
              <span className="chat-row-bot">
                <small>{last(c).who === "me" ? T("chat.youPrefix") : c.group ? last(c).who.split(" ")[0] + ": " : ""}{last(c).text}</small>
                {c.unread > 0 ? <i className="chat-unread">{c.unread}</i> : null}
              </span>
            </span>
          </button>
        ))}
      </div>

      {/* conversation */}
      {chat ? (
        <div className={"chat-pane" + (mobileList ? "" : " show")}>
          <header className="chat-head">
            <button className="iconbtn chat-back" onClick={() => setMobileList(true)} aria-label={T("chat.backToChats")}>
              <Icon name="chevR" size={15} style={{ transform: "rotate(180deg)" }} />
            </button>
            <Avatar name={chat.name} size={34} />
            <div className="chat-head-id">
              <b>{chat.name}</b>
              <small>{chat.group ? chat.members.join(", ") : T("chat.online")}</small>
            </div>
          </header>
          <div className="chat-body" ref={bodyRef}>
            {chat.msgs.map((m, i) => {
              const prev = chat.msgs[i - 1];
              const showDay = !prev || prev.day !== m.day;
              const mine = m.who === "me";
              return (
                <React.Fragment key={i}>
                  {showDay ? <div className="chat-day"><span>{TV(m.day)}</span></div> : null}
                  <div className={"bub-row" + (mine ? " mine" : "")}>
                    <div className="bub">
                      {chat.group && !mine && (!prev || prev.who !== m.who) ? <span className="bub-who">{m.who}</span> : null}
                      <span className="bub-text">{m.text}</span>
                      <span className="bub-meta mono">
                        {m.time}
                        {mine ? <Icon name="check" size={11} stroke={2.6} /> : null}
                        {mine ? <Icon name="check" size={11} stroke={2.6} style={{ marginInlineStart: -7 }} /> : null}
                      </span>
                    </div>
                  </div>
                </React.Fragment>
              );
            })}
          </div>
          <footer className="chat-foot">
            <input className="input chat-input" placeholder={T("chat.typeMessage")} value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") send(); }} />
            <button className="chat-send" onClick={send} aria-label={T("chat.send")}>
              <Icon name="send" size={16} />
            </button>
          </footer>
        </div>
      ) : null}
    </section>
  );
}
window.ChatTab = ChatTab;
