// Pretty Rare Boutique — Chat widget
// Warm, on-brand assistant. Responds to common questions about treatments, booking, location.

const RESPONSES = {
  greeting: {
    text: "Hello. Welcome to Pretty Rare Boutique. How can I help you today?",
    quick: ["Treatments & pricing", "How to book", "Our location & hours", "What to expect"],
  },
  treatments: {
    text: "We offer cosmetic treatments, skin treatments, lymphatic drainage, IV infusions, and ritual appointments. All begin with a complimentary 20-minute consultation — no obligation to proceed the same day.",
    quick: ["Cosmetic treatments", "Skin treatments", "Lymphatic drainage", "Book a consultation"],
  },
  lymph: {
    text: "Brazilian lymphatic drainage massage is 45 minutes, from $180. A gentle, sculpting treatment that supports circulation, reduces fluid retention, and leaves you feeling light.",
    quick: ["Book a consultation", "Treatments & pricing", "How to book"],
  },
  cosmetic: {
    text: "Our cosmetic treatments include wrinkle treatment (from $390), lip consult + treatment (from $690), and volumising consult + treatment (from $790). Every treatment is shaped around enhancement, not transformation.",
    quick: ["Book a consultation", "What to expect", "How to book"],
  },
  skin: {
    text: "Skin treatments include Rejuran (from $590) and collagen stimulator treatment (from $890). Both include a complimentary review at two to four weeks.",
    quick: ["Book a consultation", "Cosmetic treatments", "IV infusions"],
  },
  iv: {
    text: "Our Restorative IV infusion starts from $280 and takes around 40 minutes. It's a gentle, wellness-led treatment designed to restore energy and support overall wellbeing.",
    quick: ["Book a consultation", "How to book", "What to expect"],
  },
  booking: {
    text: "Booking is by appointment only. You can book online at prettyrareboutique.gettimely.com or text us on 0450 466 052.",
    quick: ["Book now", "Our location & hours", "What to expect"],
  },
  location: {
    text: "We're at Shop 3 / 21-25 Palm Beach Avenue, Palm Beach, Gold Coast. Open Wednesday to Saturday, 9:00 to 19:30.",
    quick: ["How to book", "Treatments & pricing", "What to expect"],
  },
  experience: {
    text: "You arrive to a quiet, private suite. We listen before anything else. Silk robes, complimentary tea, and no rush. Every treatment includes a complimentary follow-up at two to four weeks.",
    quick: ["Treatments & pricing", "How to book", "Our location & hours"],
  },
  bookNow: {
    text: "I'll take you to our booking page now. You can choose your treatment, date, and time there.",
    quick: [],
    action: "openBook",
  },
  fallback: {
    text: "Thank you for your question. For anything specific, our team is happy to help at hello@prettyrareboutique.com — or you're welcome to book a complimentary consultation and we can answer everything in person.",
    quick: ["Treatments & pricing", "How to book", "Our location & hours"],
  },
};

const KEY_MAP = {
  "treatments & pricing": "treatments",
  "cosmetic treatments": "cosmetic",
  "skin treatments": "skin",
  "iv infusions": "iv",
  "lymphatic drainage": "lymph",
  "how to book": "booking",
  "our location & hours": "location",
  "what to expect": "experience",
  "book a consultation": "bookNow",
  "book now": "bookNow",
};

function matchResponse(text) {
  const lower = text.toLowerCase().trim();
  if (KEY_MAP[lower]) return KEY_MAP[lower];
  if (lower.includes("price") || lower.includes("cost") || lower.includes("how much")) return "treatments";
  if (lower.includes("lip") || lower.includes("wrinkle") || lower.includes("filler") || lower.includes("cosmetic")) return "cosmetic";
  if (lower.includes("skin") || lower.includes("rejuran") || lower.includes("collagen")) return "skin";
  if (lower.includes("iv") || lower.includes("infusion") || lower.includes("drip")) return "iv";
  if (lower.includes("lymph") || lower.includes("drainage") || lower.includes("massage")) return "lymph";
  if (lower.includes("book") || lower.includes("appointment") || lower.includes("schedule")) return "booking";
  if (lower.includes("location") || lower.includes("address") || lower.includes("where") || lower.includes("hour") || lower.includes("open")) return "location";
  if (lower.includes("expect") || lower.includes("experience") || lower.includes("feel") || lower.includes("what happen")) return "experience";
  return "fallback";
}

function SiteChat({ onBook }) {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { from: "bot", text: RESPONSES.greeting.text, quick: RESPONSES.greeting.quick },
  ]);
  const [input, setInput] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const bottomRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const mobile = useMobile();

  React.useEffect(() => {
    if (open) {
      setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: "smooth" }), 60);
      setTimeout(() => inputRef.current?.focus(), 120);
    }
  }, [open, messages]);

  function sendMessage(text) {
    if (!text.trim()) return;
    const userMsg = { from: "user", text };
    setMessages((m) => [...m, userMsg]);
    setInput("");
    setTyping(true);

    const key = matchResponse(text);
    const resp = RESPONSES[key];

    setTimeout(() => {
      setTyping(false);
      if (resp.action === "openBook") {
        setMessages((m) => [...m, { from: "bot", text: resp.text, quick: [] }]);
        window.open('https://prettyrareboutique.gettimely.com', '_blank'); setOpen(false);
      } else {
        setMessages((m) => [...m, { from: "bot", text: resp.text, quick: resp.quick || [] }]);
      }
    }, 820);
  }

  const panelStyle = {
    position: "fixed",
    bottom: mobile ? 0 : 96,
    right: mobile ? 0 : 28,
    left: mobile ? 0 : "auto",
    width: mobile ? "100%" : 360,
    height: mobile ? "85vh" : 520,
    background: "var(--bg)",
    borderRadius: mobile ? "24px 24px 0 0" : 20,
    boxShadow: "var(--shadow-lg)",
    border: "1px solid var(--border)",
    display: "flex",
    flexDirection: "column",
    overflow: "hidden",
    zIndex: 110,
    opacity: open ? 1 : 0,
    transform: open ? "translateY(0)" : "translateY(16px)",
    pointerEvents: open ? "auto" : "none",
    transition: "opacity 280ms var(--ease-soft), transform 280ms var(--ease-soft)",
  };

  return (
    <>
      {/* Chat panel */}
      <div style={panelStyle}>
        {/* Header */}
        <div style={{
          padding: "20px 20px 16px",
          borderBottom: "1px solid var(--border)",
          display: "flex", justifyContent: "space-between", alignItems: "center",
          background: "var(--bg)",
          flexShrink: 0,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{
              width: 8, height: 8, borderRadius: "50%",
              background: "var(--accent)", flexShrink: 0,
            }} />
            <div>
              <div style={{
                fontFamily: "var(--font-sans)", fontWeight: 600,
                fontSize: 13, letterSpacing: "-0.01em", color: "var(--fg)",
              }}>Pretty Rare</div>
              <div style={{
                fontFamily: "var(--font-sans)", fontWeight: 400,
                fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
                color: "var(--fg-muted)", marginTop: 1,
              }}>We usually reply instantly</div>
            </div>
          </div>
          <button onClick={() => setOpen(false)} style={{
            background: "transparent", border: 0, cursor: "pointer",
            fontFamily: "var(--font-sans)", fontSize: 10,
            letterSpacing: "0.22em", textTransform: "uppercase",
            color: "var(--fg-muted)", padding: "4px 8px",
          }}>Close</button>
        </div>

        {/* Messages */}
        <div style={{
          flex: 1, overflowY: "auto", padding: "20px 16px",
          display: "flex", flexDirection: "column", gap: 12,
        }}>
          {messages.map((msg, i) => (
            <div key={i}>
              <div style={{
                display: "flex",
                justifyContent: msg.from === "user" ? "flex-end" : "flex-start",
              }}>
                <div style={{
                  maxWidth: "82%",
                  padding: "11px 14px",
                  borderRadius: msg.from === "user" ? "16px 16px 4px 16px" : "4px 16px 16px 16px",
                  background: msg.from === "user" ? "var(--fg)" : "var(--surface)",
                  color: msg.from === "user" ? "var(--fg-on-dark)" : "var(--fg)",
                  border: msg.from === "user" ? "none" : "1px solid var(--border)",
                  fontFamily: "var(--font-sans)", fontWeight: 400,
                  fontSize: 14, lineHeight: 1.55,
                }}>{msg.text}</div>
              </div>

              {/* Quick replies */}
              {msg.quick && msg.quick.length > 0 && i === messages.length - 1 && (
                <div style={{
                  marginTop: 10, display: "flex", flexWrap: "wrap", gap: 6,
                }}>
                  {msg.quick.map((q) => (
                    <button key={q} onClick={() => sendMessage(q)} style={{
                      fontFamily: "var(--font-sans)", fontWeight: 500,
                      fontSize: 11, letterSpacing: "0.12em",
                      padding: "8px 14px", borderRadius: 999,
                      border: "1px solid var(--border-pink)",
                      background: "transparent",
                      color: "var(--accent)", cursor: "pointer",
                      transition: "background 220ms var(--ease-soft), color 220ms var(--ease-soft)",
                    }}
                    onMouseEnter={(e) => { e.currentTarget.style.background = "var(--accent)"; e.currentTarget.style.color = "#fff"; }}
                    onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--accent)"; }}
                    >{q}</button>
                  ))}
                </div>
              )}
            </div>
          ))}

          {/* Typing indicator */}
          {typing && (
            <div style={{ display: "flex", justifyContent: "flex-start" }}>
              <div style={{
                padding: "12px 16px",
                borderRadius: "4px 16px 16px 16px",
                background: "var(--surface)",
                border: "1px solid var(--border)",
                display: "flex", gap: 5, alignItems: "center",
              }}>
                {[0, 1, 2].map((d) => (
                  <span key={d} style={{
                    width: 5, height: 5, borderRadius: "50%",
                    background: "var(--accent)",
                    animation: `chatDot 1.2s ${d * 0.2}s infinite ease-in-out`,
                  }} />
                ))}
              </div>
            </div>
          )}

          <div ref={bottomRef} />
        </div>

        {/* Input */}
        <div style={{
          padding: "12px 16px 16px",
          borderTop: "1px solid var(--border)",
          display: "flex", gap: 8, alignItems: "center",
          background: "var(--bg)", flexShrink: 0,
        }}>
          <input
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && sendMessage(input)}
            placeholder="Send a message..."
            style={{
              flex: 1,
              fontFamily: "var(--font-sans)", fontSize: 14,
              padding: "11px 16px", borderRadius: 999,
              border: "1px solid var(--border)",
              background: "var(--surface)",
              color: "var(--fg)",
              outline: "none",
            }}
          />
          <button
            onClick={() => sendMessage(input)}
            disabled={!input.trim() || typing}
            style={{
              width: 40, height: 40, borderRadius: "50%",
              background: input.trim() && !typing ? "var(--fg)" : "var(--border)",
              border: 0, cursor: input.trim() && !typing ? "pointer" : "default",
              display: "flex", alignItems: "center", justifyContent: "center",
              transition: "background 220ms var(--ease-soft)", flexShrink: 0,
            }}
          >
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M1 7h12M7 1l6 6-6 6" stroke={input.trim() && !typing ? "var(--fg-on-dark)" : "var(--fg-muted)"} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>

      {/* Toggle button */}
      <button
        onClick={() => setOpen(!open)}
        style={{
          position: "fixed",
          bottom: 28, left: 28,
          zIndex: 110,
          background: open ? "var(--fg)" : "var(--bg)",
          color: open ? "var(--fg-on-dark)" : "var(--fg)",
          border: "1px solid var(--border)",
          borderRadius: 999,
          padding: "14px 22px",
          boxShadow: "var(--shadow-lg)",
          fontFamily: "var(--font-sans)",
          fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase",
          fontWeight: 500, cursor: "pointer",
          display: "flex", alignItems: "center", gap: 8,
          transition: "background 240ms var(--ease-soft), color 240ms var(--ease-soft), transform 240ms var(--ease-soft)",
        }}
        onMouseEnter={(e) => !open && (e.currentTarget.style.transform = "translateY(-2px)")}
        onMouseLeave={(e) => (e.currentTarget.style.transform = "translateY(0)")}
      >
        {open ? (
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M1 1l10 10M11 1L1 11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M1 2.5A1.5 1.5 0 012.5 1h9A1.5 1.5 0 0113 2.5v6A1.5 1.5 0 0111.5 10H8l-3 3v-3H2.5A1.5 1.5 0 011 8.5v-6z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/>
          </svg>
        )}
        {open ? "Close" : "Chat"}
      </button>

      <style>{`
        @keyframes chatDot {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
          30% { transform: translateY(-4px); opacity: 1; }
        }
      `}</style>
    </>
  );
}

window.SiteChat = SiteChat;
