// Floating AI chat widget — answers questions from the site's verified info.
const { useState: useStateChat, useRef: useRefChat, useEffect: useEffectChat } = React;

const PR_SUGGESTIONS = ["What are your hours?", "Happy hour deals?", "Where are you located?", "What cocktails do you have?"];

const PR_WELCOME = {
  role: "assistant",
  text: "Aloha! 🍍🤖 I'm the Pineapple Robot bot. Ask me about our hours, drinks, menu, happy hour, karaoke, or how to find us.",
};

const Chatbot = () => {
  const [open, setOpen] = useStateChat(false);
  const [messages, setMessages] = useStateChat([PR_WELCOME]);
  const [input, setInput] = useStateChat("");
  const [loading, setLoading] = useStateChat(false);
  // Track the *visible* viewport so the mobile panel fits above the keyboard.
  const readViewport = () => {
    const vv = window.visualViewport;
    return {
      w: window.innerWidth,
      h: vv ? vv.height : window.innerHeight,
      bottomInset: vv ? Math.max(0, window.innerHeight - vv.height - vv.offsetTop) : 0,
    };
  };
  const [vp, setVp] = useStateChat(readViewport);
  const scrollRef = useRefChat(null);
  const inputRef = useRefChat(null);

  useEffectChat(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading, open]);

  useEffectChat(() => {
    const onResize = () => setVp(readViewport());
    window.addEventListener("resize", onResize);
    const vv = window.visualViewport;
    if (vv) { vv.addEventListener("resize", onResize); vv.addEventListener("scroll", onResize); }
    return () => {
      window.removeEventListener("resize", onResize);
      if (vv) { vv.removeEventListener("resize", onResize); vv.removeEventListener("scroll", onResize); }
    };
  }, []);

  // Only auto-focus on desktop — on mobile it forces the keyboard open and
  // shoves the panel off-screen.
  useEffectChat(() => {
    if (open && inputRef.current && window.innerWidth > 860) inputRef.current.focus();
  }, [open]);

  const isMobile = vp.w <= 860;

  const send = async (text) => {
    const trimmed = (text != null ? text : input).trim();
    if (!trimmed || loading) return;
    const next = [...messages, { role: "user", text: trimmed }];
    setMessages(next);
    setInput("");
    setLoading(true);
    try {
      const resp = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: next.filter((m) => m !== PR_WELCOME) }),
      });
      const data = await resp.json();
      const reply = resp.ok && data.reply
        ? data.reply
        : (data.error || "Sorry, I'm having trouble right now. Give us a call at (808) 667-2929.");
      setMessages((m) => [...m, { role: "assistant", text: reply }]);
    } catch (e) {
      setMessages((m) => [...m, { role: "assistant", text: "Hmm, I couldn't connect. Please try again, or call (808) 667-2929." }]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Launcher */}
      <button
        className="pr-chat-launcher"
        aria-label={open ? "Close chat" : "Open chat"}
        onClick={() => setOpen((o) => !o)}
        style={{
          position: "fixed", right: 24, bottom: 24, zIndex: 1000,
          width: 64, height: 64, borderRadius: 999,
          background: "var(--accent-2)", border: "3px solid var(--ink)",
          boxShadow: "4px 4px 0 var(--ink)", cursor: "pointer",
          display: "grid", placeItems: "center", padding: 0,
          transition: "transform .15s",
        }}
        onMouseEnter={(e) => (e.currentTarget.style.transform = "translateY(-2px)")}
        onMouseLeave={(e) => (e.currentTarget.style.transform = "none")}
      >
        {open ? (
          <span style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: 26, color: "var(--ink)", lineHeight: 1 }}>×</span>
        ) : (
          <img src="assets/mascot.png" alt="" style={{ width: 42, height: 42, objectFit: "contain" }} />
        )}
      </button>

      {/* Panel */}
      {open && (
        <div
          className="pr-chat-panel"
          role="dialog"
          aria-label="Pineapple Robot chat"
          style={{
            position: "fixed", zIndex: 1000,
            display: "flex", flexDirection: "column",
            background: "var(--cream)", color: "var(--ink)",
            border: "3px solid var(--ink)", borderRadius: "var(--radius-md)",
            boxShadow: "6px 6px 0 var(--ink)", overflow: "hidden",
            fontFamily: "var(--sans)",
            ...(isMobile
              ? {
                  left: 12, right: 12,
                  bottom: vp.bottomInset + 12,
                  // Fit within the visible viewport, leaving a gap at the top
                  // so the header (and its × close) is always clear.
                  height: Math.max(300, vp.h - 84),
                }
              : {
                  right: 24, bottom: 100,
                  width: 360, maxWidth: "calc(100vw - 32px)",
                  height: 520, maxHeight: "calc(100vh - 140px)",
                }),
          }}
        >
          {/* Header */}
          <div style={{ background: "var(--espresso)", color: "var(--cream)", padding: "14px 18px", display: "flex", alignItems: "center", gap: 12, borderBottom: "3px solid var(--ink)" }}>
            <img src="assets/mascot.png" alt="" style={{ width: 32, height: 32, objectFit: "contain" }} />
            <div style={{ flex: 1 }}>
              <div className="display" style={{ fontSize: 18, lineHeight: 1, color: "var(--accent-2)" }}>Pineapple Robot</div>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".06em", opacity: 0.75, textTransform: "uppercase" }}>Ask me anything</div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="Close" style={{ background: "transparent", border: "none", color: "var(--cream)", fontSize: 22, fontWeight: 800, cursor: "pointer", lineHeight: 1 }}>×</button>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
            {messages.map((m, i) => (
              <div key={i} style={{ alignSelf: m.role === "user" ? "flex-end" : "flex-start", maxWidth: "85%" }}>
                <div style={{
                  padding: "10px 14px", borderRadius: 16, fontSize: 14, lineHeight: 1.5,
                  whiteSpace: "pre-wrap", border: "2px solid var(--ink)",
                  background: m.role === "user" ? "var(--accent-2)" : "#fff",
                  color: "var(--ink)",
                  borderBottomRightRadius: m.role === "user" ? 4 : 16,
                  borderBottomLeftRadius: m.role === "user" ? 16 : 4,
                }}>
                  {m.text}
                </div>
              </div>
            ))}

            {loading && (
              <div style={{ alignSelf: "flex-start" }}>
                <div style={{ padding: "12px 16px", borderRadius: 16, border: "2px solid var(--ink)", background: "#fff", display: "flex", gap: 5 }}>
                  {[0, 1, 2].map((d) => (
                    <span key={d} className="pr-chat-dot" style={{ animationDelay: `${d * 0.18}s` }} />
                  ))}
                </div>
              </div>
            )}

            {/* Suggestion chips (only before the first user message) */}
            {messages.length === 1 && !loading && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 4 }}>
                {PR_SUGGESTIONS.map((s) => (
                  <button key={s} onClick={() => send(s)} style={{
                    fontFamily: "var(--sans)", fontSize: 12, fontWeight: 600,
                    padding: "7px 12px", borderRadius: 999, cursor: "pointer",
                    background: "transparent", color: "var(--ink)", border: "2px solid var(--ink)",
                  }}>{s}</button>
                ))}
              </div>
            )}
          </div>

          {/* Input */}
          <form
            onSubmit={(e) => { e.preventDefault(); send(); }}
            style={{ display: "flex", gap: 8, padding: 12, borderTop: "3px solid var(--ink)", background: "var(--cream)" }}
          >
            <input
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Type a message…"
              style={{
                flex: 1, padding: "10px 14px", borderRadius: 999,
                border: "2px solid var(--ink)", fontFamily: "var(--sans)", fontSize: 14,
                background: "#fff", color: "var(--ink)", outline: "none",
              }}
            />
            <button type="submit" disabled={loading || !input.trim()} aria-label="Send" style={{
              width: 44, height: 44, borderRadius: 999, flexShrink: 0,
              background: "var(--accent)", border: "2px solid var(--ink)", cursor: "pointer",
              color: "var(--cream)", fontSize: 18, fontWeight: 800,
              opacity: loading || !input.trim() ? 0.5 : 1,
            }}>↑</button>
          </form>
        </div>
      )}
    </>
  );
};

window.Chatbot = Chatbot;
