function ChatFab({ onClick, open }) {
  if (open) return null;
  return (
    <button className="chat-fab" onClick={onClick} aria-label="Ask the assistant">
      <span className="fab-glyph" aria-hidden="true">
        <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="fabGrad" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
              <stop offset="0" stopColor="#F5C8A8"/>
              <stop offset="0.55" stopColor="#E07A4E"/>
              <stop offset="1" stopColor="#8A2E1A"/>
            </linearGradient>
          </defs>
          <path d="M16 3 L19.2 12.8 L29 16 L19.2 19.2 L16 29 L12.8 19.2 L3 16 L12.8 12.8 Z" fill="url(#fabGrad)"/>
        </svg>
      </span>
      <span className="fab-pulse" aria-hidden="true"/>
    </button>
  );
}

function ChatPanel({ open, onClose, project }) {
  const [messages, setMessages] = useState([
    { role: "bot", text: `Hi — I'm looking at ${project.client} with you. Ask me about budget, binders, team workload, or anything in the engagement.` },
  ]);
  const [draft, setDraft] = useState("");
  const [typing, setTyping] = useState(false);
  const bodyRef = useRef(null);
  const scriptIdx = useRef(0);

  // Reset on project change
  useEffect(() => {
    setMessages([
      { role: "bot", text: `Hi — I'm looking at ${project.client} with you. Ask me about budget, binders, team workload, or anything in the engagement.` },
    ]);
    scriptIdx.current = 0;
  }, [project.id]);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, typing, open]);

  const suggestions = [
    "Why are we red on this project?",
    "What can we do to recover?",
    "Who's signed off on Binder B?",
    "Which projects are at risk right now?",
  ];

  const findScriptedReply = (userText) => {
    const t = userText.toLowerCase();
    const script = window.CHAT_SCRIPT;
    // Match to a scripted exchange by keyword overlap
    if (t.includes("red") || t.includes("budget") || t.includes("over")) return script[1].text;
    if (t.includes("recover") || t.includes("fix") || t.includes("optim")) return script[3].text;
    if (t.includes("sign") || t.includes("binder b")) return script[5].text;
    if (t.includes("risk") || t.includes("which project")) return script[7].text;
    // Default: cycle through bot replies
    const botReplies = script.filter(m => m.role === "bot");
    const reply = botReplies[scriptIdx.current % botReplies.length].text;
    scriptIdx.current++;
    return reply;
  };

  const send = (text) => {
    const t = (text ?? draft).trim();
    if (!t) return;
    setMessages(m => [...m, { role: "user", text: t }]);
    setDraft("");
    setTyping(true);
    const reply = findScriptedReply(t);
    const delay = Math.min(1600, 600 + reply.length * 8);
    setTimeout(() => {
      setTyping(false);
      setMessages(m => [...m, { role: "bot", text: reply }]);
    }, delay);
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
  };

  return (
    <aside className={`chat-panel ${open?'open':''}`} aria-hidden={!open}>
      <div className="chat-head">
        <div className="av">H</div>
        <div>
          <div className="tt">Harrington Assistant</div>
          <div className="sb">{project.client} · scoped to this engagement</div>
        </div>
        <button className="chat-close" onClick={onClose} aria-label="Close">×</button>
      </div>

      <div className="chat-body" ref={bodyRef}>
        {messages.map((m, i) => (
          <div key={i} className={`bubble ${m.role}`}>{m.text}</div>
        ))}
        {typing && (
          <div className="bubble bot typing">
            Thinking<span className="dots"><span/><span/><span/></span>
          </div>
        )}
      </div>

      <div className="chat-suggest">
        {suggestions.map(s => (
          <button key={s} onClick={() => send(s)}>{s}</button>
        ))}
      </div>

      <div className="chat-input">
        <textarea
          placeholder="Ask about this engagement…"
          value={draft}
          onChange={e => setDraft(e.target.value)}
          onKeyDown={onKey}
          rows={1}
        />
        <button className="chat-send" onClick={() => send()} disabled={!draft.trim()} aria-label="Send">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12h14M13 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </aside>
  );
}

Object.assign(window, { ChatFab, ChatPanel });
