// Ask AI drawer for the prototype — reactive "pull" Q&A with a scripted (or LLM) answer.
const ASK_RP = window.RP;

function AskAiDrawer({ open, onClose }) {
  const { Icon } = ASK_RP;
  const D = window.RC_DATA;
  const [msgs, setMsgs] = React.useState([]);
  const [text, setText] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const bodyRef = React.useRef(null);

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

  async function ask(q) {
    if (!q.trim() || busy) return;
    setMsgs((m) => [...m, { role: "user", text: q }]);
    setText("");
    setBusy(true);
    let answer = D.askAiAnswer;
    // Optional live LLM via window.RP_LLM(prompt) if wired at deploy; falls back to scripted.
    try {
      if (typeof window.RP_LLM === "function") {
        const r = await window.RP_LLM(q);
        if (r) answer = r;
      } else {
        await new Promise((res) => setTimeout(res, 700));
      }
    } catch (e) { /* keep scripted */ }
    setBusy(false);
    setMsgs((m) => [...m, { role: "ai", text: answer }]);
  }

  const empty = msgs.length === 0 && !busy;

  return (
    <>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(15,16,53,.18)", opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity var(--dur-base) var(--ease-standard)", zIndex: 40 }} />
      <aside style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: 440, zIndex: 41, background: "#fff", boxShadow: "var(--rp-shadow-ai)", transform: open ? "translateX(0)" : "translateX(110%)", transition: "transform var(--dur-slow) var(--ease-standard)", display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--rp-border)" }}>
          <Icon name="WandSparkles" size={20} color="var(--rp-ai-indigo)" stroke={2.2} />
          <span style={{ fontSize: 16, fontWeight: 700 }}>Ask AI</span>
          <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".06em", color: "var(--rp-ai-indigo)", background: "var(--rp-ai-soft)", padding: "2px 7px", borderRadius: 9999 }}>BETA</span>
          <span style={{ flex: 1 }} />
          <button onClick={() => setMsgs([])} style={{ background: "none", border: "none", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4, color: "var(--rp-ai-indigo)", fontWeight: 700, fontSize: 13 }}><Icon name="Plus" size={16} color="var(--rp-ai-indigo)" />New Chat</button>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer" }}><Icon name="X" size={20} color="var(--rp-muted)" /></button>
        </div>

        <div ref={bodyRef} style={{ flex: 1, overflowY: "auto", padding: 20 }}>
          {empty && (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
              <div style={{ width: 84, height: 84, borderRadius: "50%", background: "var(--rp-ai-soft)", display: "grid", placeItems: "center", margin: "8px 0 16px" }}>
                <Icon name="WandSparkles" size={36} color="var(--rp-ai-indigo)" stroke={2} />
              </div>
              <div style={{ fontSize: 22, fontWeight: 700, textAlign: "center" }}>Hello! How can I assist you?</div>
              <div style={{ fontSize: 14, color: "var(--rp-muted)", textAlign: "center", marginTop: 6, maxWidth: 320 }}>Get instant answers about your workforce, payroll, or knowledge base</div>
              <div style={{ width: "100%", display: "flex", flexDirection: "column", gap: 10, marginTop: 22 }}>
                {D.askAiSuggestions.map((s, i) => (
                  <button key={i} onClick={() => ask(s.text)} style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--rp-ai-soft)", border: "none", borderRadius: 8, padding: "14px 16px", cursor: "pointer", textAlign: "left", fontFamily: "var(--font-sans)" }}>
                    <Icon name={s.icon} size={18} color="var(--rp-ai-indigo)" />
                    <span style={{ fontSize: 14, color: "var(--rp-ink)" }}>{s.text}</span>
                  </button>
                ))}
              </div>
            </div>
          )}
          {msgs.map((m, i) => (
            <div key={i} style={{ display: "flex", justifyContent: m.role === "user" ? "flex-end" : "flex-start", marginBottom: 12 }}>
              <div style={{ maxWidth: "85%", whiteSpace: "pre-wrap", fontSize: 14, lineHeight: 1.5, padding: "11px 14px", borderRadius: 12, background: m.role === "user" ? "var(--rp-blue)" : "var(--rp-ai-soft)", color: m.role === "user" ? "#fff" : "var(--rp-ink)" }}>{m.text}</div>
            </div>
          ))}
          {busy && <div style={{ fontSize: 13, color: "var(--rp-ai-indigo)", fontWeight: 700 }}>Thinking…</div>}
        </div>

        <div style={{ padding: 20, borderTop: "1px solid var(--rp-border)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, border: "1px solid var(--rp-border-strong)", borderRadius: 8, padding: "4px 6px 4px 14px" }}>
            <input value={text} onChange={(e) => setText(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") ask(text); }} placeholder="Type your question here…" style={{ flex: 1, border: "none", outline: "none", fontFamily: "var(--font-sans)", fontSize: 14, padding: "10px 0" }} />
            <button onClick={() => ask(text)} style={{ width: 38, height: 38, borderRadius: 8, border: "none", background: "var(--rp-ai-gradient)", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="ArrowUp" size={18} color="#fff" stroke={2.4} /></button>
          </div>
          <div style={{ fontSize: 11.5, color: "var(--rp-muted)", textAlign: "center", marginTop: 12 }}>AI Assistant is in beta. Responses may not always be accurate.</div>
        </div>
      </aside>
    </>
  );
}

window.AskAiDrawer = AskAiDrawer;
