/* BioReveal — AI chat sidekick.
 *
 * Floating button on the Reveal page → slides in a chat panel.
 * Each user message → POST /api/chat with the patient's full intake +
 * generated protocol as system context, plus the running conversation.
 * Claude (or rules engine) answers as a smart-friend-with-clinical-training.
 */

const SUGGESTED_QUESTIONS = [
  "Why did you pick this dose for me?",
  "What if I miss a dose?",
  "Can I stack creatine on top?",
  "What time of day should I inject?",
  "How will I know if it's not working?",
  "What's the cheapest version of this protocol?",
];

const ChatSidekick = ({ profile }) => {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { role: "assistant", content: "Hey — I'm the AI clinician for your protocol. Ask me anything: dosing, side effects, lifestyle adjustments, what to do if something feels off. I have your full intake + the analysis you just got." },
  ]);
  const [input, setInput] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const scrollRef = React.useRef(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, sending]);

  React.useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  const send = async (text) => {
    const t = (text ?? input).trim();
    if (!t || sending) return;
    setInput("");
    setSending(true);
    const newMessages = [...messages, { role: "user", content: t }];
    setMessages(newMessages);
    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          intake: profile.intake,
          protocol: profile.protocol,
          messages: newMessages.map(m => ({ role: m.role, content: m.content })),
        }),
      });
      const data = await res.json();
      const reply = data.reply || data.error || "(no response)";
      setMessages([...newMessages, { role: "assistant", content: reply, engine: data.engine }]);
    } catch (e) {
      setMessages([...newMessages, { role: "assistant", content: `Network error: ${e.message}. Try again.` }]);
    } finally {
      setSending(false);
    }
  };

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

  return (
    <>
      {/* Floating button */}
      {!open && (
        <button
          onClick={() => setOpen(true)}
          style={{
            position: "fixed", bottom: 24, right: 24, zIndex: 999,
            background: "var(--ink)", color: "var(--paper)", border: "none",
            borderRadius: 999, padding: "16px 22px", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15,
            boxShadow: "0 12px 36px rgba(0,0,0,0.18)", cursor: "pointer",
            display: "flex", alignItems: "center", gap: 10,
          }}
        >
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#10b981", boxShadow: "0 0 8px #10b981" }}/>
          Ask AI about your stack
        </button>
      )}

      {/* Slide-in panel */}
      {open && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 999, display: "flex", justifyContent: "flex-end",
          background: "rgba(0,0,0,0.45)", animation: "fade-in 0.2s ease",
        }} onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
          <div style={{
            width: "min(440px, 100vw)", height: "100vh", background: "var(--paper)",
            display: "flex", flexDirection: "column", boxShadow: "-12px 0 40px rgba(0,0,0,0.18)",
            animation: "slide-in 0.25s cubic-bezier(.2,.7,.3,1)",
          }}>
            {/* Header */}
            <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--paper-3)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--muted)", textTransform: "uppercase" }}>★ CLINICAL SIDEKICK</div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 18, marginTop: 3 }}>Ask about your stack</div>
              </div>
              <button onClick={() => setOpen(false)} style={{ background: "none", border: "none", fontSize: 24, cursor: "pointer", color: "var(--ink)", padding: 0, lineHeight: 1 }}>×</button>
            </div>

            {/* Messages */}
            <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: "16px 20px" }}>
              {messages.map((m, i) => (
                <div key={i} style={{ marginBottom: 14, display: "flex", flexDirection: "column", alignItems: m.role === "user" ? "flex-end" : "flex-start" }}>
                  <div style={{
                    maxWidth: "86%", padding: "11px 14px", borderRadius: 14,
                    background: m.role === "user" ? "var(--ink)" : "var(--paper-2)",
                    color: m.role === "user" ? "var(--paper)" : "var(--ink)",
                    fontSize: 14, lineHeight: 1.5, whiteSpace: "pre-wrap",
                  }}>
                    {m.content}
                  </div>
                  {m.role === "assistant" && m.engine && (
                    <div style={{ fontSize: 9, fontFamily: "var(--font-mono)", letterSpacing: "0.12em", color: "var(--muted)", marginTop: 4, paddingLeft: 4 }}>
                      {m.engine.toUpperCase()}
                    </div>
                  )}
                </div>
              ))}
              {sending && (
                <div style={{ display: "flex", gap: 6, padding: "8px 14px", background: "var(--paper-2)", borderRadius: 14, alignSelf: "flex-start", display: "inline-flex" }}>
                  <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--ink)", animation: "pulse-dot 1s ease-in-out infinite" }}/>
                  <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--ink)", animation: "pulse-dot 1s ease-in-out 0.2s infinite" }}/>
                  <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--ink)", animation: "pulse-dot 1s ease-in-out 0.4s infinite" }}/>
                </div>
              )}
            </div>

            {/* Suggested questions */}
            {messages.length <= 1 && !sending && (
              <div style={{ padding: "0 20px 14px" }}>
                <div style={{ fontSize: 10, fontFamily: "var(--font-mono)", letterSpacing: "0.16em", color: "var(--muted)", textTransform: "uppercase", marginBottom: 8 }}>TRY ASKING</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {SUGGESTED_QUESTIONS.map(q => (
                    <button key={q} onClick={() => send(q)} style={{
                      background: "var(--paper-2)", border: "1px solid var(--paper-3)",
                      borderRadius: 999, padding: "6px 12px", fontSize: 12,
                      cursor: "pointer", color: "var(--ink)", fontFamily: "inherit",
                    }}>{q}</button>
                  ))}
                </div>
              </div>
            )}

            {/* Input */}
            <div style={{ borderTop: "1px solid var(--paper-3)", padding: "14px 18px" }}>
              <div style={{ display: "flex", gap: 8, alignItems: "flex-end" }}>
                <textarea
                  ref={inputRef}
                  value={input}
                  onChange={e => setInput(e.target.value)}
                  onKeyDown={onKey}
                  placeholder="Ask anything about your protocol…"
                  rows={1}
                  style={{
                    flex: 1, resize: "none", padding: "10px 12px", border: "1.5px solid var(--paper-3)",
                    borderRadius: 10, fontFamily: "inherit", fontSize: 14, color: "var(--ink)",
                    background: "var(--paper)", maxHeight: 120, overflow: "auto",
                  }}
                />
                <button
                  onClick={() => send()}
                  disabled={sending || !input.trim()}
                  style={{
                    background: "var(--ink)", color: "var(--paper)", border: "none",
                    borderRadius: 10, padding: "10px 18px", cursor: sending || !input.trim() ? "default" : "pointer",
                    opacity: sending || !input.trim() ? 0.4 : 1, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 14,
                  }}
                >Send</button>
              </div>
              <div style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--muted)", marginTop: 8, letterSpacing: "0.04em" }}>
                ⓘ NOT MEDICAL ADVICE — your prescriber has final say. Use this to think out loud.
              </div>
            </div>
          </div>
        </div>
      )}

      <style>{`
        @keyframes fade-in { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slide-in { from { transform: translateX(100%) } to { transform: translateX(0) } }
        @keyframes pulse-dot { 0%, 100% { transform: scale(0.8); opacity: 0.4 } 50% { transform: scale(1.2); opacity: 1 } }
      `}</style>
    </>
  );
};

window.BR_CHAT = { ChatSidekick };
