/* global React */
/* CryoEmpress Wellness — editorial concierge chatbot
   Uses the built-in window.claude.complete() helper. */

const { useState, useRef, useEffect, useCallback } = React;

// ============================================================
// Brand knowledge — kept in source so the chatbot answers with
// the same facts that appear on the site itself.
// ============================================================

const CONCIERGE_SYSTEM = `
You are the CryoEmpress Wellness concierge — a warm, refined, editorial voice for a boutique cryotherapy and body-sculpting studio in Pearland, Texas. You answer guest questions about the studio with the same calm care a five-star spa hostess would.

VOICE & STYLE
- Refined, intimate, never salesy. Short paragraphs. Plain language.
- You may use one elegant flourish (an italic phrase, a gentle metaphor) but never overdo it.
- Address the guest directly. Use "we" when speaking for the studio.
- Never invent prices, promotions, medical claims, or specifics you do not know.
- If asked about a price, tell the guest pricing is shared during their consultation or on Vagaro.
- If asked anything medical, gently defer: "We are a wellness studio, not a clinic — for that, please consult your physician."
- Always close by offering the next step: book, consult online, or call.

STUDIO FACTS
- Name: CryoEmpress Wellness
- Tagline: Refined Wellness. Real Results. The Empress Method.
- Address: Salon by JC, 2650 Pearland Parkway, Ste #23, Pearland, TX 77581
- Phone: 832 · 336 · 3680
- Email: info@cryoempresswellness.com
- Instagram: @cryoempresswellness — https://www.instagram.com/cryoempresswellness/
- Booking: https://www.vagaro.com/cryoempresswellness/services
- Hours: Monday–Thursday 6:00 PM – 9:30 PM, Saturday 9:00 AM – 8:00 PM, Friday and Sunday closed. By appointment only.
- Nurse-owned. Non-clinical. Insured by Elite Beauty Society. Member of the International Association of Professional Weight Loss Center Owners (IAPO).

OUR SIGNATURE PROTOCOLS (six)
1. Laser Lipo — non-invasive light therapy that melts inches from waist, arms, and thighs. Zero downtime. ~50 min.
2. Radio Frequency — skin-tightening warmth that stimulates collagen and lifts naturally, neck to knees. ~45 min.
3. Cavitation — sonic waves dissolve fat cells so the body can flush them out, for smoother, slimmer lines. ~60 min.
4. Wood Therapy / Sculpting — hand-sculpted lymphatic drainage with anatomical wood tools — drain, tone, refine. ~60 min.
5. CryoEmpress Treatment — signature cryotherapy protocol; targeted sub-zero therapy that destroys stubborn fat without surgery. ~45 min.
6. CryoEmpress Facial — a cooling, lifting facial that tightens, brightens, and reduces puffiness in a single session. ~45 min.

OFFERS
- The Empress Intro Experience: a curated 90-minute introduction — private consultation, body assessment, and a signature treatment of your choice. Reserved for first-time guests. (Do not state a price.)
- The Online Consultation: a 45-minute private video call with our specialist. Body goals assessment, a personalized written plan, and priority booking. Available evenings and Saturdays. (Suitable for guests outside Pearland or those considering their first visit.)

POLICIES (summary)
- All packages, sessions, memberships, and promotional offers are final sale and non-refundable.
- Packages are non-transferable. Results vary. Multiple sessions are recommended.
- We do not diagnose, treat, or cure medical conditions. Nurse-owned but non-clinical.
- All services are by appointment. Intake and consent forms required before service.
- Client data is collected only for service delivery and never sold.

WHEN TO SUGGEST WHAT
- "Book / appointment / reserve / first visit" → direct them to https://www.vagaro.com/cryoempresswellness/services and mention the Empress Intro Experience.
- "From far away / out of town / can't visit yet / not sure" → suggest the Online Consultation.
- "Talk to someone / questions / concerns" → suggest calling 832 · 336 · 3680 or emailing info@cryoempresswellness.com.
- Off-topic questions (weather, news, etc.) → politely steer back to CryoEmpress.

FORMATTING
- Keep replies under 120 words unless asked for detail.
- Do not use markdown headings or asterisks. Use plain prose with short paragraphs.
- When listing things, use simple line breaks with "—" or short clauses, not bullet syntax.
`.trim();

const GREETING = {
  role: "assistant",
  content:
    "Welcome. I'm the CryoEmpress concierge — ask me about treatments, what to expect, or how to begin.",
};

const SUGGESTED = [
  "What is the Empress Method?",
  "Which treatment is right for me?",
  "How do I book my first visit?",
  "What are your hours?",
];

// ============================================================
// Conversation helpers
// ============================================================

async function askConcierge(messages) {
  // window.claude.complete is provided by the host environment.
  try {
    const text = await window.claude.complete({
      messages: [
        { role: "system", content: CONCIERGE_SYSTEM },
        ...messages.map((m) => ({ role: m.role, content: m.content })),
      ],
    });
    return text;
  } catch (err) {
    return (
      "I'm having trouble reaching the studio just now. Please call us at " +
      "832 · 336 · 3680 or book directly at vagaro.com/cryoempresswellness."
    );
  }
}

// ============================================================
// Chatbot component
// ============================================================

function Chatbot() {
  const [open, setOpen] = useState(false);
  const [thinking, setThinking] = useState(false);
  const [messages, setMessages] = useState([GREETING]);
  const [draft, setDraft] = useState("");
  const scrollRef = useRef(null);
  const inputRef = useRef(null);

  const send = useCallback(
    async (text) => {
      const trimmed = (text || "").trim();
      if (!trimmed || thinking) return;
      const next = [...messages, { role: "user", content: trimmed }];
      setMessages(next);
      setDraft("");
      setThinking(true);
      const reply = await askConcierge(next);
      setMessages([...next, { role: "assistant", content: reply }]);
      setThinking(false);
    },
    [messages, thinking]
  );

  // Auto-scroll to newest message
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
  }, [messages, thinking, open]);

  // Focus input when opened
  useEffect(() => {
    if (open) {
      const t = setTimeout(() => inputRef.current?.focus(), 200);
      return () => clearTimeout(t);
    }
  }, [open]);

  // Esc to close
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  return (
    <>
      <button
        className={`cb-launcher ${open ? "is-open" : ""}`}
        onClick={() => setOpen((v) => !v)}
        aria-label={open ? "Close concierge" : "Open concierge"}
        title="Concierge"
      >
        {open ? (
          <span className="cb-launcher-x">✕</span>
        ) : (
          <>
            <span className="cb-launcher-mark">CE</span>
            <span className="cb-launcher-pulse" />
          </>
        )}
      </button>

      <div className={`cb-panel ${open ? "is-open" : ""}`} role="dialog" aria-label="CryoEmpress concierge">
        <header className="cb-head">
          <div className="cb-head-mark">
            <span>CE</span>
          </div>
          <div className="cb-head-text">
            <span className="cb-head-eyebrow">The CryoEmpress Concierge</span>
            <span className="cb-head-name">Ask the Studio</span>
          </div>
          <button className="cb-head-close" onClick={() => setOpen(false)} aria-label="Close">✕</button>
        </header>

        <div className="cb-scroll" ref={scrollRef}>
          {messages.map((m, i) => (
            <div key={i} className={`cb-msg cb-msg-${m.role}`}>
              {m.role === "assistant" && <span className="cb-msg-rule" />}
              <p>{m.content}</p>
            </div>
          ))}
          {thinking && (
            <div className="cb-msg cb-msg-assistant cb-thinking">
              <span className="cb-msg-rule" />
              <p><span className="dot" /><span className="dot" /><span className="dot" /></p>
            </div>
          )}

          {messages.length <= 1 && !thinking && (
            <div className="cb-suggested">
              <span className="cb-suggested-label">Begin with —</span>
              <div className="cb-suggested-grid">
                {SUGGESTED.map((q) => (
                  <button key={q} className="cb-chip" onClick={() => send(q)}>
                    {q}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        <form
          className="cb-input"
          onSubmit={(e) => { e.preventDefault(); send(draft); }}
        >
          <input
            ref={inputRef}
            type="text"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="Ask a question…"
            disabled={thinking}
            aria-label="Your message"
          />
          <button type="submit" className="cb-send" disabled={!draft.trim() || thinking} aria-label="Send">
            <span>Send</span>
            <span className="cb-send-arrow">→</span>
          </button>
        </form>

        <div className="cb-foot">
          <span>Replies are AI-assisted · For urgent matters call 832 · 336 · 3680</span>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { Chatbot });
