/* ASSISTANT CHAT — free-form Q&A + draft generation. window.SCREENS.Chat */
(function () {
  const { useState, useRef, useEffect } = React;
  const I = window.ICONS;
  const { Btn } = window.UI;
  const { chatSeed } = window.DATA;

  const SUGGEST = [
    "What's the status on Maria?",
    "Draft a follow-up for the Johnson lead",
    "Which leads are about to go stale?",
    "Summarize today's queue",
  ];

  // canned, professional responses
  function respond(q) {
    const s = q.toLowerCase();
    if (s.includes("maria")) return { text: "Maria Delgado — Refinance, $640K, in Processing. She replied this morning ready to advance; a draft asking for her pay stubs and bank statement is in your approval queue. Source: Zillow. Last contact: today.", chip: "Status" };
    if (s.includes("johnson") || s.includes("draft")) return { text: "Here's a follow-up for Greg Johnson (Purchase, $815K, Application):", chip: "Draft · SMS", draft: "Hi Greg, Ray here — your agent's right that timing's good. Rather than text numbers back and forth, let's grab 10 minutes so I can tailor it to your scenario. Does tomorrow at 11 or 2:30 work?" };
    if (s.includes("stale") || s.includes("cold")) return { text: "Six leads are at or past 7 days of silence: Priya Young (14d), Renee Foster (12d), Dean Wallace (9d), Omar Hassan (8d), Marcus Cole (7d), and Sofia Diaz (5d, approaching). The March re-engagement batch already has nudges staged for them.", chip: "Pipeline" };
    if (s.includes("queue") || s.includes("today")) return { text: "Your queue has 8 drafts: 4 replies and 4 new-lead first touches. Two are hot — Maria (ready to advance) and Luis (clear-to-close). The rest are routine. Want me to prioritize the hot ones at the top?", chip: "Summary" };
    return { text: "I can pull a lead's status, draft a text or email, flag stale leads, or summarize your queue. Try asking about a specific lead by name.", chip: "Assistant" };
  }

  function Chat() {
    const [msgs, setMsgs] = useState(() => chatSeed.map(m => ({ ...m })));
    const [input, setInput] = useState("");
    const [typing, setTyping] = useState(false);
    const bodyRef = useRef(null);

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

    const send = (text) => {
      const q = (text ?? input).trim();
      if (!q) return;
      setMsgs(prev => [...prev, { from: "me", text: q }]);
      setInput("");
      setTyping(true);
      setTimeout(() => {
        setTyping(false);
        setMsgs(prev => [...prev, { from: "ai", ...respond(q) }]);
      }, 900);
    };

    return (
      <div className="page narrow" style={{ height: "100%", display: "flex", flexDirection: "column", paddingBottom: 24 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 16 }}>
          <div style={{ width: 36, height: 36, display: "grid", placeItems: "center", border: "1px solid var(--gold-line)", color: "var(--green-lift)" }}><I.chat width={18} height={18} /></div>
          <div>
            <h1 className="display" style={{ fontSize: 30 }}>Ask the assistant</h1>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-faint)", letterSpacing: "0.08em" }}><span className="live-dot" style={{ display: "inline-block", verticalAlign: "middle", marginRight: 6 }}></span>Online · sees your full pipeline</div>
          </div>
        </div>

        {/* messages */}
        <div ref={bodyRef} className="panel hide-scroll" style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 14, minHeight: 0 }}>
          {msgs.map((m, i) => (
            <div key={i} className="slide-in" style={{ display: "flex", justifyContent: m.from === "me" ? "flex-end" : "flex-start" }}>
              <div style={{ maxWidth: "82%" }}>
                {m.from === "ai" && m.chip && <div className="eyebrow" style={{ marginBottom: 6, color: "var(--green-lift)" }}>◆ {m.chip}</div>}
                <div style={{ padding: "11px 15px", fontSize: 14.5, lineHeight: 1.55,
                  background: m.from === "me" ? "var(--green)" : "var(--bg-2)", border: "1px solid var(--line)" }}>{m.text}</div>
                {m.draft && (
                  <div style={{ marginTop: 8, padding: "11px 14px", border: "1px dashed var(--gold-line)", background: "var(--bg-1)", fontSize: 14, lineHeight: 1.55 }}>
                    {m.draft}
                    <div style={{ display: "flex", gap: 8, marginTop: 11, justifyContent: "flex-end" }}>
                      <Btn sm icon={I.edit}>Edit</Btn>
                      <Btn sm kind="primary" icon={I.send}>Queue it</Btn>
                    </div>
                  </div>
                )}
              </div>
            </div>
          ))}
          {typing && (
            <div style={{ display: "flex", gap: 6, alignItems: "center", color: "var(--ink-faint)" }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase" }}>Thinking</span>
              <span className="live-dot"></span>
            </div>
          )}
        </div>

        {/* suggestions */}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", margin: "14px 0 12px" }}>
          {SUGGEST.map(s => (
            <button key={s} className="btn sm" onClick={() => send(s)} style={{ letterSpacing: "0.04em", textTransform: "none", fontSize: 11.5 }}>{s}</button>
          ))}
        </div>

        {/* input */}
        <div style={{ display: "flex", gap: 10 }}>
          <input className="field" placeholder="Ask about a lead, or request a draft…" value={input}
            onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === "Enter" && send()} style={{ flex: 1 }} />
          <Btn kind="primary" icon={I.send} onClick={() => send()}>Send</Btn>
        </div>
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.Chat = Chat;
})();
