/* global React, I, UI */
// =============== แชทภายในทีม — หลายห้อง + ตอบกลับ + อีโมจิ + วาดภาพ (iPad) ===============
const { useState: useStateTC, useEffect: useEffectTC, useRef: useRefTC, useMemo: useMemoTC } = React;

const TC_KEY = "sss-chat";
const TC_READ_KEY = "sss-chat-read-ts";
const tcRoomKey = (roomId) => !roomId || roomId === "general" ? TC_KEY : TC_KEY + ":" + roomId;
const tcReadKey = (roomId) => !roomId || roomId === "general" ? TC_READ_KEY : TC_READ_KEY + ":" + roomId;

// ไม่มี seed — ห้องว่างจนกว่าจะมีข้อความจริง
const TC_SEEDS = { general: [], "r-tech": [], "r-delivery": [] };

function tcLoad(roomId) {
  const rid = roomId || "general";
  const d = window.SSSData;
  if (d && d.ChatMessages && d.ChatMessages[rid]) {
    // กรอง seed เก่า (ts=0) ที่หลุดเข้า Supabase ออก
    return d.ChatMessages[rid].filter(m => (m.ts || 0) > 0);
  }
  try { return JSON.parse(localStorage.getItem(tcRoomKey(rid)) || "null")?.filter(m => (m.ts || 0) > 0) || []; }
  catch { return []; }
}
function tcSave(roomId, list) {
  const rid = roomId || "general";
  const d = window.SSSData;
  if (d) {
    if (!d.ChatMessages) d.ChatMessages = {};
    d.ChatMessages[rid] = list.slice(-200);
  }
  try { localStorage.setItem(tcRoomKey(rid), JSON.stringify(list.slice(-200))); } catch {}
  window.dispatchEvent(new Event("sss-chat-changed"));
}
function tcReadTs(roomId) { return parseInt(localStorage.getItem(tcReadKey(roomId)) || "0", 10); }
function tcMarkRead(roomId, msgs) {
  const max = msgs.reduce((m, x) => Math.max(m, x.ts || 0), 0);
  localStorage.setItem(tcReadKey(roomId), String(max));
  window.dispatchEvent(new Event("sss-chat-read"));
}
function tcUnreadRoom(roomId, meName) {
  const rt = tcReadTs(roomId);
  return tcLoad(roomId).filter(m => (m.ts || 0) > rt && m.name !== meName);
}
function tcUnreadAll(meName) {
  const rooms = window.ChatRooms ? window.ChatRooms.visible(meName) : [{ id: "general" }];
  let total = 0, tagged = 0;
  rooms.forEach(r => {
    const un = tcUnreadRoom(r.id, meName);
    total += un.length;
    tagged += un.filter(m => m.text && m.text.includes("@" + meName)).length;
  });
  return { total, tagged };
}

// fallback ถ้าหน้า users-perms ยังไม่โหลด
function tcProfile(name) {
  if (window.ChatProfiles) return window.ChatProfiles.get(name);
  return { role: "", color: "var(--ink-2)", emoji: "", avatar: null };
}
function TCAvatar({ name, size = 26 }) {
  if (window.RankAvatar) return <window.RankAvatar name={name} size={size}/>;
  return <span className="avatar" style={{width: size, height: size, fontSize: size * 0.36}}>{String(name || "?").slice(0, 2)}</span>;
}

// แสดงข้อความพร้อมไฮไลท์ @แท็ก + #เอกสาร (กดเด้งไปหน้าเอกสาร)
function TCText({ text, me }) {
  const parts = String(text || "").split(/(@[^\s@,.!?]+(?:\s[^\s@,.!?]+)?|#[^\s#,!?]+)/g);
  return (
    <span>
      {parts.map((p, i) => {
        if (p.startsWith("@")) {
          return <b key={i} style={{color: me ? "inherit" : "var(--info)", fontWeight: 600, background: me ? "rgba(255,255,255,0.18)" : "var(--info-bg)", borderRadius: 4, padding: "0 3px"}}>{p}</b>;
        }
        if (p.startsWith("#")) {
          const doc = window.SSSSearch ? window.SSSSearch.findByNo(p.slice(1)) : null;
          if (doc) {
            return (
              <span key={i} onClick={(e) => { e.stopPropagation(); window.location.hash = "#/" + doc.route; }}
                title={`เปิด ${doc.type} ${doc.no}${doc.status ? " · " + doc.status : ""}`}
                style={{display: "inline-flex", alignItems: "center", gap: 4, cursor: "pointer", fontWeight: 600,
                  background: me ? "rgba(255,255,255,0.2)" : "var(--surface)", border: me ? "1px solid rgba(255,255,255,0.35)" : "1px solid var(--line-strong)",
                  color: "inherit", borderRadius: 5, padding: "0 6px", margin: "0 1px", fontSize: "0.92em", whiteSpace: "nowrap"}}>
                📄 <span className="mono">{doc.no}</span>
                {doc.status && <span style={{fontSize: "0.82em", opacity: 0.75}}>· {doc.status}</span>}
              </span>
            );
          }
          return <b key={i} style={{fontWeight: 600}}>{p}</b>;
        }
        return <React.Fragment key={i}>{p}</React.Fragment>;
      })}
    </span>
  );
}

const TC_REACTS = ["👍", "❤️", "😂", "😮", "🙏", "✅"];
const TC_EMOJIS = ["😀", "😄", "😂", "🤣", "😉", "😍", "🤔", "😅", "😭", "😡", "🥳", "😴", "👍", "👎", "👌", "🙏", "💪", "👏", "🔥", "⭐", "✅", "❌", "⚠️", "❗", "🚚", "📦", "🛠️", "💰", "📄", "☕"];

// =============== แกนแชท (ผูกกับห้อง — ใช้ทั้งหน้า activity และ popup) ===============
function ChatCore({ roomId = "general", bodyHeight = 380, active = true }) {
  const D = window.SSSData;
  const { Btn } = window.UI;
  // ใช้ Session แทน Company.currentUser เพื่อให้แต่ละ device ส่งในชื่อตัวเอง
  const _sess = window.Session ? window.Session.get() : null;
  const me = _sess
    ? { name: _sess.name, role: _sess.role, initials: (_sess.name || "??").slice(0, 2) }
    : D.Company.currentUser;
  const [msgs, setMsgs] = useStateTC(() => tcLoad(roomId));
  const [text, setText] = useStateTC("");
  const [pending, setPending] = useStateTC([]);
  const [mentionQ, setMentionQ] = useStateTC(null);
  const [docQ, setDocQ] = useStateTC(null);
  const [viewer, setViewer] = useStateTC(null);
  const [replyTo, setReplyTo] = useStateTC(null);     // {id, name, text}
  const [emojiOpen, setEmojiOpen] = useStateTC(false);
  const [drawOpen, setDrawOpen] = useStateTC(false);
  const [hoverId, setHoverId] = useStateTC(null);
  const [reactFor, setReactFor] = useStateTC(null);
  const bodyRef = useRefTC(null);
  const inputRef = useRefTC(null);

  // เปลี่ยนห้อง = โหลดข้อความห้องนั้น + เคลียร์สถานะร่าง
  useEffectTC(() => {
    setMsgs(tcLoad(roomId));
    setReplyTo(null); setReactFor(null); setHoverId(null); setEmojiOpen(false);
  }, [roomId]);

  useEffectTC(() => {
    const h = () => setMsgs(tcLoad(roomId));
    window.addEventListener("sss-chat-changed", h);
    window.addEventListener("sss-chat-polled", h);
    return () => {
      window.removeEventListener("sss-chat-changed", h);
      window.removeEventListener("sss-chat-polled", h);
    };
  }, [roomId]);

  const scrollDown = () => {
    setTimeout(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, 60);
  };
  useEffectTC(() => { scrollDown(); }, [msgs.length, roomId]);

  // เปิดอยู่ = อ่านแล้ว
  useEffectTC(() => { if (active) tcMarkRead(roomId, msgs); }, [active, msgs.length, roomId]);

  // ---- @ mention + # doc pickers ----
  const onType = (v) => {
    setText(v);
    const am = /@([^\s@]*)$/.exec(v);
    const dm = /#([^\s#]*)$/.exec(v);
    if (am && dm) {
      if (v.lastIndexOf("@") > v.lastIndexOf("#")) { setMentionQ(am[1]); setDocQ(null); }
      else { setDocQ(dm[1]); setMentionQ(null); }
    } else if (am) { setMentionQ(am[1]); setDocQ(null); }
    else if (dm) { setDocQ(dm[1]); setMentionQ(null); }
    else { setMentionQ(null); setDocQ(null); }
  };
  const mentionList = useMemoTC(() => {
    if (mentionQ === null) return [];
    return D.Employees.filter(e => e.name.includes(mentionQ) || e.role.includes(mentionQ)).slice(0, 6);
  }, [mentionQ]);
  const pickMention = (emp) => {
    setText(t => t.replace(/@[^\s@]*$/, "@" + emp.name + " "));
    setMentionQ(null);
    inputRef.current && inputRef.current.focus();
  };
  const docList = useMemoTC(() => {
    if (docQ === null || !window.SSSSearch) return [];
    if (!docQ) return window.SSSSearch.buildIndex().filter(d => /ใบ|50 ทวิ|ค่าใช้จ่าย|เบิก/.test(d.type)).slice(0, 6);
    return window.SSSSearch.search(docQ, 6);
  }, [docQ]);
  const pickDoc = (doc) => {
    setText(t => t.replace(/#[^\s#]*$/, "#" + doc.no + " "));
    setDocQ(null);
    inputRef.current && inputRef.current.focus();
  };

  // ---- attach images ----
  const pickImages = async (e) => {
    const files = [...e.target.files];
    e.target.value = "";
    const loaded = [];
    for (const f of files) {
      const url = await window.DeliveryStore.resizeImage(f, 800);
      if (url) loaded.push({ url, name: f.name });
    }
    setPending(p => [...p, ...loaded]);
  };

  // ---- emoji reaction บนข้อความ ----
  const toggleReact = (msgId, emo) => {
    const next = msgs.map(m => {
      if (m.id !== msgId) return m;
      const r = { ...(m.reacts || {}) };
      const arr = r[emo] || [];
      if (arr.includes(me.name)) {
        const left = arr.filter(n => n !== me.name);
        if (left.length) r[emo] = left; else delete r[emo];
      } else r[emo] = [...arr, me.name];
      return { ...m, reacts: r };
    });
    setMsgs(next); tcSave(roomId, next);
    setReactFor(null);
  };

  const startReply = (m) => {
    setReplyTo({ id: m.id, name: m.name, text: m.text ? m.text.slice(0, 90) : `[รูปภาพ ${(m.images || []).length} รูป]` });
    setHoverId(null); setReactFor(null);
    inputRef.current && inputRef.current.focus();
  };

  // ---- send ----
  const send = () => {
    const t = text.trim();
    if (!t && pending.length === 0) return;
    const tags = [];
    D.Employees.forEach(e => { if (t.includes("@" + e.name)) tags.push(e.name); });
    const now = new Date();
    const time = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
    const next = [...msgs, {
      id: "m" + Date.now(), ts: Date.now(), who: me.initials, name: me.name, time,
      text: t, images: pending, tags, replyTo: replyTo || undefined
    }];
    setMsgs(next); tcSave(roomId, next); tcMarkRead(roomId, next);
    setText(""); setPending([]); setMentionQ(null); setDocQ(null); setReplyTo(null); setEmojiOpen(false);
    if (tags.length) window.toast && window.toast("แท็กถึง " + tags.join(", ") + " แล้ว");
    window.logActivity && window.logActivity("ส่งข้อความในแชท", t.slice(0, 40) || `รูปภาพ ${pending.length} รูป`, "comment");
    scrollDown();
  };

  return (
    <>
      <div ref={bodyRef} style={{padding: 12, display: "flex", flexDirection: "column", gap: 10, fontSize: 13,
        height: bodyHeight || undefined, flex: bodyHeight ? undefined : 1, minHeight: bodyHeight ? undefined : 0,
        overflowY: "auto"}}>
        {msgs.length === 0 && <div style={{textAlign: "center", color: "var(--ink-3)", fontSize: 12, padding: 20}}>ยังไม่มีข้อความ — เริ่มคุยกันเลย</div>}
        {msgs.map(m => {
          const isMe = m.name === me.name;
          const prof = tcProfile(m.name);
          const taggedMe = !isMe && m.text && m.text.includes("@" + me.name);
          const showActs = hoverId === m.id || reactFor === m.id;
          return (
            <div key={m.id} style={{display: "flex", gap: 8, flexDirection: isMe ? "row-reverse" : "row"}}
              onMouseEnter={() => setHoverId(m.id)} onMouseLeave={() => { setHoverId(h => h === m.id ? null : h); }}>
              {!isMe && <TCAvatar name={m.name} size={28}/>}
              <div style={{maxWidth: "74%", display: "flex", flexDirection: "column", alignItems: isMe ? "flex-end" : "flex-start"}}>
                <div style={{fontSize: 11, marginBottom: 2, display: "flex", gap: 6, alignItems: "center", flexDirection: isMe ? "row-reverse" : "row"}}>
                  {!isMe && <b style={{color: prof.color, fontSize: 11.5}}>{m.name} {prof.emoji}</b>}
                  {!isMe && prof.role && <span style={{color: "var(--ink-4)", fontSize: 10}}>{prof.role}</span>}
                  <span style={{color: "var(--ink-3)"}}>{m.time}</span>
                </div>
                {taggedMe && (
                  <div style={{fontSize: 10, fontWeight: 700, color: "var(--warning)", marginBottom: 2, display: "flex", alignItems: "center", gap: 3}}>
                    <I.bell size={10}/> มีคนแท็กถึงคุณ
                  </div>
                )}
                {(m.text || m.replyTo) && (
                  <div onClick={() => setHoverId(h => h === m.id ? null : m.id)}
                    style={{padding: "6px 10px",
                    background: isMe ? "var(--accent)" : "var(--surface-2)",
                    color: isMe ? "var(--accent-ink)" : "var(--ink-1)",
                    border: taggedMe ? "1.5px solid var(--warning)" : "1px solid transparent",
                    boxShadow: taggedMe ? "0 0 0 3px var(--warning-bg)" : "none",
                    borderRadius: isMe ? "10px 10px 2px 10px" : "10px 10px 10px 2px"}}>
                    {m.replyTo && (
                      <div style={{fontSize: 11, lineHeight: 1.4, marginBottom: 4, padding: "3px 8px", borderRadius: 6,
                        borderLeft: `2.5px solid ${isMe ? "rgba(255,255,255,0.55)" : "var(--accent)"}`,
                        background: isMe ? "rgba(255,255,255,0.14)" : "var(--surface)", opacity: 0.92}}>
                        <b style={{display: "block", fontSize: 10.5}}>↩ {m.replyTo.name}</b>
                        <span style={{opacity: 0.85, display: "block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 260}}>{m.replyTo.text}</span>
                      </div>
                    )}
                    {m.text && <TCText text={m.text} me={isMe}/>}
                  </div>
                )}
                {(m.images || []).length > 0 && (
                  <div style={{display: "flex", gap: 4, flexWrap: "wrap", marginTop: 4, justifyContent: isMe ? "flex-end" : "flex-start"}}>
                    {m.images.map((p, i) => (
                      <img key={i} src={p.url} alt={p.name || "img"} onClick={() => setViewer(p.url)} style={{width: 110, height: 82, objectFit: "cover", borderRadius: 8, border: "1px solid var(--line)", cursor: "zoom-in", background: "white"}}/>
                    ))}
                  </div>
                )}
                {/* reactions ที่มีอยู่ */}
                {m.reacts && Object.keys(m.reacts).length > 0 && (
                  <div style={{display: "flex", gap: 4, flexWrap: "wrap", marginTop: 3}}>
                    {Object.entries(m.reacts).map(([emo, names]) => {
                      const mine = names.includes(me.name);
                      return (
                        <button key={emo} onClick={() => toggleReact(m.id, emo)} title={names.join(", ")}
                          style={{display: "inline-flex", alignItems: "center", gap: 3, padding: "1px 7px", borderRadius: 999, cursor: "pointer",
                            fontSize: 12, lineHeight: "18px",
                            border: mine ? "1.5px solid var(--accent)" : "1px solid var(--line-strong)",
                            background: mine ? "var(--info-bg)" : "var(--surface)"}}>
                          <span>{emo}</span><b style={{fontSize: 10.5, color: "var(--ink-2)"}}>{names.length}</b>
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
              {/* ปุ่ม react + ตอบกลับ (โผล่ตอน hover / แตะข้อความ) */}
              <div style={{alignSelf: "center", position: "relative", display: "flex", gap: 2,
                opacity: showActs ? 1 : 0, pointerEvents: showActs ? "auto" : "none", transition: "opacity .12s"}}>
                <button className="icon-btn" title="ใส่อีโมจิ" style={{width: 24, height: 24, fontSize: 13}}
                  onClick={() => setReactFor(r => r === m.id ? null : m.id)}>🙂</button>
                <button className="icon-btn" title="ตอบกลับ" style={{width: 24, height: 24, fontSize: 13}}
                  onClick={() => startReply(m)}>↩</button>
                {reactFor === m.id && (
                  <div style={{position: "absolute", bottom: "calc(100% + 4px)", [isMe ? "right" : "left"]: 0, display: "flex", gap: 2,
                    background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 999, padding: "3px 6px", boxShadow: "var(--shadow-lg)", zIndex: 8}}>
                    {TC_REACTS.map(emo => (
                      <button key={emo} onClick={() => toggleReact(m.id, emo)}
                        style={{border: 0, background: "transparent", fontSize: 16, cursor: "pointer", padding: "1px 3px", borderRadius: 6}}
                        onMouseOver={ev => ev.currentTarget.style.background = "var(--surface-2)"}
                        onMouseOut={ev => ev.currentTarget.style.background = "transparent"}>{emo}</button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* pending images */}
      {pending.length > 0 && (
        <div style={{borderTop: "1px solid var(--line)", padding: "8px 10px", display: "flex", gap: 6, flexWrap: "wrap", background: "var(--surface-2)"}}>
          {pending.map((p, i) => (
            <div key={i} style={{position: "relative", width: 52, height: 52}}>
              <img src={p.url} alt="" style={{width: 52, height: 52, objectFit: "cover", borderRadius: 6, border: "1px solid var(--line)", background: "white"}}/>
              <button onClick={() => setPending(ph => ph.filter((_, j) => j !== i))} style={{position: "absolute", top: 1, right: 1, width: 16, height: 16, borderRadius: "50%", background: "rgba(0,0,0,0.72)", color: "white", border: 0, cursor: "pointer", fontSize: 10, lineHeight: "14px", padding: 0}}>×</button>
            </div>
          ))}
          <span style={{fontSize: 11, color: "var(--ink-3)", alignSelf: "center"}}>รอส่ง {pending.length} รูป</span>
        </div>
      )}

      {/* แถบตอบกลับ */}
      {replyTo && (
        <div style={{borderTop: "1px solid var(--line)", padding: "6px 12px", display: "flex", alignItems: "center", gap: 8, background: "var(--surface-2)", fontSize: 12}}>
          <span style={{color: "var(--accent)", fontWeight: 700, flexShrink: 0}}>↩ ตอบกลับ {replyTo.name}</span>
          <span style={{color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1}}>{replyTo.text}</span>
          <button className="icon-btn" style={{width: 20, height: 20}} onClick={() => setReplyTo(null)}><I.close size={11}/></button>
        </div>
      )}

      {/* composer */}
      <div style={{borderTop: "1px solid var(--line)", padding: 8, position: "relative"}}>
        {mentionQ !== null && mentionList.length > 0 && (
          <div style={{position: "absolute", bottom: "calc(100% + 4px)", left: 8, right: 8, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 8, boxShadow: "var(--shadow-lg)", overflow: "hidden", zIndex: 5}}>
            <div style={{padding: "6px 10px", fontSize: 10.5, color: "var(--ink-3)", borderBottom: "1px solid var(--line-soft)"}}>แท็กเพื่อนร่วมงาน</div>
            {mentionList.map(e => {
              const prof = tcProfile(e.name);
              return (
                <div key={e.id} onClick={() => pickMention(e)} style={{display: "flex", alignItems: "center", gap: 8, padding: "6px 10px", cursor: "pointer"}}
                  onMouseOver={ev => ev.currentTarget.style.background = "var(--surface-2)"}
                  onMouseOut={ev => ev.currentTarget.style.background = "transparent"}>
                  <TCAvatar name={e.name} size={22}/>
                  <span style={{fontSize: 12.5}}><b style={{color: prof.color}}>{e.name} {prof.emoji}</b> · <span style={{color: "var(--ink-3)"}}>{e.role}</span></span>
                </div>
              );
            })}
          </div>
        )}
        {docQ !== null && docList.length > 0 && (
          <div style={{position: "absolute", bottom: "calc(100% + 4px)", left: 8, right: 8, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 8, boxShadow: "var(--shadow-lg)", overflow: "hidden", zIndex: 5}}>
            <div style={{padding: "6px 10px", fontSize: 10.5, color: "var(--ink-3)", borderBottom: "1px solid var(--line-soft)"}}>แท็กเอกสาร — พิมพ์เลขที่หรือชื่อลูกค้าต่อจาก #</div>
            {docList.map((d, i) => (
              <div key={d.type + d.no + i} onClick={() => pickDoc(d)} style={{display: "flex", alignItems: "center", gap: 8, padding: "6px 10px", cursor: "pointer"}}
                onMouseOver={ev => ev.currentTarget.style.background = "var(--surface-2)"}
                onMouseOut={ev => ev.currentTarget.style.background = "transparent"}>
                <span className="badge outline" style={{fontSize: 9, flexShrink: 0, minWidth: 58, justifyContent: "center"}}>{d.type}</span>
                <span style={{fontSize: 12.5, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>
                  <b className="mono">{d.no}</b> · {d.title}
                </span>
                {d.status && <span style={{fontSize: 10.5, color: "var(--ink-3)", flexShrink: 0}}>{d.status}</span>}
              </div>
            ))}
          </div>
        )}
        {emojiOpen && (
          <div style={{position: "absolute", bottom: "calc(100% + 4px)", left: 8, right: 8, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 10, boxShadow: "var(--shadow-lg)", zIndex: 5, padding: 8}}>
            <div style={{fontSize: 10.5, color: "var(--ink-3)", marginBottom: 5}}>ใส่อีโมจิในข้อความ</div>
            <div style={{display: "grid", gridTemplateColumns: "repeat(10, 1fr)", gap: 2}}>
              {TC_EMOJIS.map(emo => (
                <button key={emo} onClick={() => { setText(t => t + emo); inputRef.current && inputRef.current.focus(); }}
                  style={{border: 0, background: "transparent", fontSize: 18, cursor: "pointer", padding: "3px 0", borderRadius: 6}}
                  onMouseOver={ev => ev.currentTarget.style.background = "var(--surface-2)"}
                  onMouseOut={ev => ev.currentTarget.style.background = "transparent"}>{emo}</button>
              ))}
            </div>
          </div>
        )}
        <div style={{display: "flex", gap: 6, alignItems: "center"}}>
          <label className="icon-btn" title="แนบรูป" style={{cursor: "pointer"}}>
            <input type="file" accept="image/*" multiple style={{display: "none"}} onChange={pickImages}></input>
            <I.camera size={14}/>
          </label>
          <button className="icon-btn" title="วาดภาพส่งในแชท (รองรับ Apple Pencil)" onClick={() => setDrawOpen(true)}>
            <I.edit size={14}/>
          </button>
          <button className="icon-btn" title="ใส่อีโมจิ" onClick={() => setEmojiOpen(v => !v)} style={{fontSize: 14, fontWeight: 400}}>🙂</button>
          <button className="icon-btn" title="แท็กเพื่อนร่วมงาน (@)" onClick={() => { onType(text + (text.endsWith(" ") || !text ? "@" : " @")); inputRef.current && inputRef.current.focus(); }}>
            <I.user size={14}/>
          </button>
          <button className="icon-btn" title="แท็กเอกสาร (#) เช่น ใบส่งของ ใบแจ้งหนี้" onClick={() => { onType(text + (text.endsWith(" ") || !text ? "#" : " #")); inputRef.current && inputRef.current.focus(); }}>
            <I.doc size={14}/>
          </button>
          <input ref={inputRef} className="input" placeholder="พิมพ์ข้อความ… @ แท็กคน · # แท็กเอกสาร" value={text}
            onChange={e => onType(e.target.value)}
            onKeyDown={e => {
              if (e.key === "Enter" && mentionQ !== null && mentionList.length > 0) { e.preventDefault(); pickMention(mentionList[0]); }
              else if (e.key === "Enter" && docQ !== null && docList.length > 0) { e.preventDefault(); pickDoc(docList[0]); }
              else if (e.key === "Enter") send();
              if (e.key === "Escape") { setMentionQ(null); setDocQ(null); setEmojiOpen(false); setReplyTo(null); }
            }}
            style={{height: 32, flex: 1}}></input>
          <Btn size="sm" kind="primary" icon={I.send} onClick={send}>ส่ง</Btn>
        </div>
      </div>

      {drawOpen && window.ChatDrawModal && (
        <window.ChatDrawModal onClose={() => setDrawOpen(false)}
          onDone={(url) => { setPending(p => [...p, { url, name: "ภาพวาด" }]); }}/>
      )}

      {viewer && (
        <div onClick={() => setViewer(null)} style={{position: "fixed", inset: 0, zIndex: 300, background: "rgba(0,0,0,0.8)", display: "flex", alignItems: "center", justifyContent: "center", padding: 30, cursor: "zoom-out"}}>
          <img src={viewer} alt="preview" style={{maxWidth: "92%", maxHeight: "92%", borderRadius: 8, background: "white"}}/>
        </div>
      )}
    </>
  );
}

window.ChatCore = ChatCore;
