/* ============================================================
   IRONLOG — Floating AI coach chat
   ============================================================ */

function ChatDock({ onSendChat }) {
  const [open, setOpen] = useState(false);
  const [msgs, setMsgs] = useState(IRONLOG.chatSeed);
  const [text, setText] = useState("");
  const [images, setImages] = useState([]); // [{name, dataUrl}]
  const [typing, setTyping] = useState(false);
  const listRef = useRef(null);

  useEffect(() => {
    if (listRef.current) listRef.current.scrollTo({ top: listRef.current.scrollHeight, behavior: "smooth" });
  }, [msgs, typing, open]);

  const send = useCallback((preset) => {
    const body = (preset != null ? preset : text).trim();
    if ((!body && images.length === 0) || typing) return;
    const sentImages = images.slice();
    const userMsg = { id: Date.now(), role: "user", text: body, images: sentImages.map(i => ({ name: i.name, dataUrl: i.dataUrl })) };
    setMsgs((m) => [...m, userMsg]);
    setText(""); setImages([]);
    setTyping(true);

    // Build a short rolling history (text only) for continuity.
    const history = msgs.slice(-8).map(m => ({ role: m.role, text: m.text }));

    const run = async () => {
      try {
        let reply;
        if (onSendChat) {
          reply = await onSendChat(body, sentImages);
        } else {
          const r = await API.chat(body, sentImages.map(i => i.dataUrl).filter(Boolean), history);
          reply = r.reply;
        }
        setTyping(false);
        setMsgs((m) => [...m, { id: Date.now() + 1, role: "ai", text: typeof reply === "string" ? reply : (reply && reply.text) || "" }]);
      } catch (ex) {
        setTyping(false);
        setMsgs((m) => [...m, { id: Date.now() + 1, role: "ai", text: (ex && ex.message) || "Coach is unavailable right now. Try again in a moment." }]);
      }
    };
    run();
  }, [text, images, onSendChat, msgs, typing]);

  async function attach() {
    const picked = await pickImageFile();
    if (!picked) return;
    setImages((im) => [...im, { name: picked.name, dataUrl: picked.dataUrl }]);
  }

  return (
    <>
      <button className={"chat-fab" + (open ? " is-open" : "")} onClick={() => setOpen(o => !o)} aria-label={open ? "Close coach chat" : "Open coach chat"} aria-expanded={open}>
        {open ? <Icons.Close size={22}/> : <Icons.Chat size={22}/>}
        {!open && <span className="chat-fab-pulse" aria-hidden="true" />}
      </button>

      <div className={"chat-panel" + (open ? " open" : "")} role="dialog" aria-label="BrotherVader coach" aria-hidden={!open}>
        <div className="chat-header">
          <div className="chat-id">
            <span className="chat-avatar display">AI</span>
            <div>
              <div className="chat-name head">BROTHERVADER COACH</div>
              <div className="chat-status"><span className="chat-dot" /> Reading your ledger</div>
            </div>
          </div>
          <button className="pen" onClick={() => setOpen(false)} aria-label="Close"><Icons.Close /></button>
        </div>

        <div className="chat-list" ref={listRef}>
          {msgs.map((mm) => <Bubble key={mm.id} m={mm} />)}
          {typing && (
            <div className="chat-row ai">
              <div className="bubble bubble-ai typing"><span/><span/><span/></div>
            </div>
          )}
        </div>

        <div className="chat-chips">
          {IRONLOG.chatChips.map((c, i) => (
            <button key={i} className="chip" onClick={() => send(c)}>{c}</button>
          ))}
        </div>

        {images.length > 0 && (
          <div className="chat-attachments">
            {images.map((im, i) => (
              <span key={i} className="chat-attach">
                <Icons.Image size={13}/> {im.name}
                <button onClick={() => setImages(images.filter((_, idx) => idx !== i))} aria-label="Remove"><Icons.Close size={12}/></button>
              </span>
            ))}
          </div>
        )}

        <form className="chat-input" onSubmit={(e) => { e.preventDefault(); send(); }}>
          <button type="button" className="pen" onClick={attach} aria-label="Attach image"><Icons.Image /></button>
          <input className="chat-text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Ask your coach…" aria-label="Message" />
          <button type="submit" className="chat-send" disabled={!text.trim() && images.length === 0} aria-label="Send"><Icons.Send size={17}/></button>
        </form>
      </div>
    </>
  );
}

function Bubble({ m }) {
  return (
    <div className={"chat-row " + m.role}>
      <div className={"bubble bubble-" + m.role}>
        {m.images && m.images.length > 0 && (
          <div className="bubble-imgs">
            {m.images.map((n, i) => {
              const url = typeof n === "string" ? null : n.dataUrl;
              const label = typeof n === "string" ? n : n.name;
              return url
                ? <span key={i} className="bubble-img"><img src={url} alt={label} style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: 6 }} /></span>
                : <span key={i} className="bubble-img ph"><span className="ph-label" style={{fontSize:9}}>{label}</span></span>;
            })}
          </div>
        )}
        {m.text && (m.role === "ai" ? <RichText text={m.text} /> : <p>{m.text}</p>)}
      </div>
    </div>
  );
}

Object.assign(window, { ChatDock });
