const { ChatBubble, Tip, TypingDots, Avatar, Chip, TripCard, Button, StarRating } = window.GDVExpressDesignSystem_766357;

/* Scripted conversation. Each step: messages (rendered in order) + quick-reply chips. */
const FLOW = {
  start: {
    msgs: [
      { t: "text", h: "Hi Dana! 👋 Welcome back — I'm Gigi, your personal GDV Express travel guide." },
      { t: "text", h: "I can help you <b>find a trip</b>, show you <b>what your membership covers</b>, walk you through the <b>site</b>, or sort out <b>billing &amp; renewal</b>. What sounds good?" },
    ],
    chips: [
      { label: "Find me a trip", next: "mood", primary: true },
      { label: "Show me what I've got", next: "membership" },
      { label: "How do I use the site", next: "howto" },
      { label: "💳 Billing & renewal", next: "billing" },
      { label: "Something else", next: "more" },
    ],
  },
  howto: {
    msgs: [
      { t: "tip", h: "Here's how to get the most from your membership 👇" },
      { t: "text", h: "Up top you'll find <b>Condos</b>, <b>Cruises</b>, <b>Tours</b>, <b>Hotels</b>, <b>Cars</b> and <b>Flights</b> — every price you see is your member rate. Or skip the browsing and just tell me what you want; I'll pull it up for you." },
      { t: "text", h: "Want me to show you around, or find a trip now?" },
    ],
    chips: [
      { label: "Find me a trip", next: "mood", primary: true },
      { label: "Show me what I've got", next: "membership" },
    ],
  },
  more: {
    msgs: [{ t: "text", h: "Of course — I can help with a lot. Here are the things members ask me about most 👇" }],
    chips: [
      { label: "Renew my membership", next: "billing", primary: true },
      { label: "Leave a member review ⭐", next: "review" },
      { label: "Find me a trip", next: "mood" },
      { label: "Talk to a specialist", next: "human" },
    ],
  },
  membership: {
    msgs: [
      { t: "tip", h: "Here's the short version 👇" },
      { t: "text", h: "As a member you book at <b>member rates</b> — often well below public prices — across our resorts and travel network. I only ever show you what you can actually book." },
      { t: "text", h: "Think of me as the shortcut. Ready to find one?" },
    ],
    chips: [{ label: "Yes, find me a trip", next: "mood", primary: true }],
  },
  billing: {
    msgs: [
      { t: "text", h: "Happy to help. Your membership renews on <b>April 30</b> at $199/yr, and your card ending 4242 is on file — so you don't have to do a thing to stay covered." },
      { t: "text", h: "Want me to lock in your renewal now, or carry on planning a trip?" },
    ],
    chips: [
      { label: "Renew my membership", next: "renewed", primary: true },
      { label: "Find me a trip", next: "mood" },
      { label: "Open My Account", next: "account" },
    ],
  },
  renewed: {
    msgs: [
      { t: "tip", h: "Done — you're renewed through next April. You're all set. ✅" },
      { t: "text", h: "Now the fun part — want me to find you a trip to put it to use?" },
    ],
    chips: [{ label: "Yes, find me a trip", next: "mood", primary: true }],
  },
  account: {
    msgs: [{ t: "tip", h: "In the live version this opens My Account on the GDV Express site — profile, preferences and travel history all live there." }],
    chips: [{ label: "Back to planning", next: "mood", primary: true }],
  },
  mood: {
    msgs: [{ t: "text", h: "Love it. What kind of trip are you in the mood for?" }],
    chips: [
      { label: "Beach 🏖️", next: "who", set: "a beach trip" },
      { label: "City 🏙️", next: "who", set: "a city break" },
      { label: "Mountains 🏔️", next: "who", set: "a mountain escape" },
      { label: "Surprise me ✨", next: "who", set: "something new" },
    ],
  },
  who: {
    msgs: [{ t: "text", h: "Nice. Who's coming along?" }],
    chips: [
      { label: "Just me", next: "when", set: "just you" },
      { label: "A couple", next: "when", set: "the two of you" },
      { label: "The family", next: "when", set: "the whole family" },
    ],
  },
  when: {
    msgs: [{ t: "text", h: "And when are you thinking?" }],
    chips: [
      { label: "Next few weeks", next: "suggest", set: "in the next few weeks" },
      { label: "This season", next: "suggest", set: "this season" },
      { label: "I'm flexible", next: "suggest", set: "whenever works" },
    ],
  },
  suggest: {
    msgs: [
      { t: "text", h: "Perfect — here's what I've got you down for: {mood}, for {who}, {when}. Two member-rate stays I can book you right now 👇" },
      { t: "cards" },
      { t: "tip", h: "Everything here is included with your membership — the price you see is the price you pay." },
      { t: "text", h: "Like one? Tap <b>Book</b> to grab it. Want me to keep watching for more like these?" },
    ],
    chips: [
      { label: "Keep watching for me", next: "watch", primary: true },
      { label: "Talk to a specialist", next: "human" },
    ],
  },
  watch: {
    msgs: [
      { t: "watch" },
      { t: "text", h: "All set, Dana — I'm on the lookout. While you're here, a quick heads-up about something I noticed 👇" },
    ],    chips: [
      { label: "What's that?", next: "upgrade" },
      { label: "Sounds good — talk soon", next: "wrap" },
    ],
  },
  booked: {
    msgs: [
      { t: "confirm" },
      { t: "text", h: "You're all set, Dana! 🎉 Keep that confirmation email handy — and anytime you want to review or manage this trip, it's waiting in <b>My Account → Travel history</b>." },
      { t: "text", h: "Want me to keep watching for more stays like this one?" },
    ],
    chips: [
      { label: "Yes, keep watching", next: "watch", primary: true },
      { label: "Show me My Account", next: "account" },
    ],
  },
  account: {
    msgs: [
      { t: "text", h: "Here it is — your new booking is already under <b>Travel history</b>, alongside your past stays and member details. The link in your confirmation email brings you right here too." },
      { t: "tip", h: "Everything in one place: upcoming trips, receipts and your full travel history — manage any of it in a tap." },
    ],
    chips: [
      { label: "Great — keep watching too", next: "watch", primary: true },
      { label: "That's all for now", next: "wrap" },
    ],
  },
  upgrade: {
    msgs: [
      { t: "text", h: "A couple of spots you liked are part of our <b>GDX</b> collection — a step up from GDV Express, with more resorts and peak-season weeks. Members who travel like you often move up." },
      { t: "text", h: "Want a quick side-by-side? No pressure." },
    ],
    chips: [
      { label: "Show me the difference", next: "wrap", primary: true },
      { label: "Maybe later", next: "wrap" },
    ],
  },
  human: {
    msgs: [{ t: "tip", h: "On it — a GDV Express specialist will reach out by phone. A real person is always a tap away." }],
    chips: [{ label: "Thanks, Gigi", next: "wrap" }],
  },
  wrap: {
    msgs: [{ t: "text", h: "Anytime, Dana — I'll message you the moment something matches. Safe travels! ✈️" }],
    chips: [
      { label: "Leave a member review ⭐", next: "review" },
      { label: "Start over", next: "start" },
    ],
  },
  review: {
    msgs: [
      { t: "text", h: "I'd love that. How was your last GDV Express stay? A quick rating helps us make member trips even better." },
      { t: "review" },
    ],
    chips: [{ label: "Maybe later", next: "wrap" }],
  },
  reviewSent: {
    msgs: [
      { t: "tip", h: "Thank you, Dana! 🌟 I've forwarded your review straight to <b>Steve and the Member Experience team</b> — they read every one personally and follow up when it helps." },
      { t: "text", h: "Anything else I can do while I have you?" },
    ],
    chips: [
      { label: "Find me a trip", next: "mood", primary: true },
      { label: "That's all for now", next: "wrap" },
    ],
  },
};

const WATCH_CARD = (
  <div style={{ background: "var(--grad-navy)", color: "#fff", borderRadius: "16px", padding: "15px", position: "relative", overflow: "hidden", maxWidth: "86%", marginBottom: "9px", boxShadow: "var(--shadow-navy)" }}>
    <div style={{ fontSize: "10px", letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--gold-500)", fontWeight: 800 }}>Standing request · ON</div>
    <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "15px", margin: "6px 0 4px" }}>I'm watching for your trip</div>
    <div style={{ fontSize: "12.5px", color: "#cfe0f0", lineHeight: 1.4 }}>Beach week · the two of you · this season. I'll text or email you the moment a match opens up.</div>
  </div>
);

function ConfirmCard({ name }) {
  return (
    <div style={{ background: "#fff", border: "1px solid #d8e6db", borderLeft: "4px solid var(--green-500)", borderRadius: "14px", padding: "14px 15px", maxWidth: "88%", marginBottom: "9px", boxShadow: "var(--shadow-sm)" }}>
      <div style={{ fontSize: "10px", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--green-600)", fontWeight: 800 }}>Booked · Confirmation sent</div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "14.5px", color: "var(--navy-800)", margin: "5px 0 9px", lineHeight: 1.25 }}>{name}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: "7px", fontSize: "12.5px", color: "#46545f", lineHeight: 1.4 }}>
        <div style={{ display: "flex", gap: "8px" }}><span>📧</span><span>Confirmation emailed to <b style={{ color: "var(--navy-800)" }}>dana.m@email.com</b> — itinerary, dates &amp; your member rate.</span></div>
        <div style={{ display: "flex", gap: "8px" }}><span>🕘</span><span>Saved to <b style={{ color: "var(--navy-800)" }}>My Account → Travel history</b>, with every trip you book.</span></div>
      </div>
    </div>
  );
}

function Msg({ m, state, onBook, onReview }) {
  const fill = (s) => s.replace(/\{(\w+)\}/g, (_, k) => state[k] || "…");
  if (m.t === "text") return <div className="grow"><Avatar name="Gigi" size={26} /><ChatBubble from="gigi" html={fill(m.h)} /></div>;
  if (m.t === "tip") return <Tip label="Good to know"><span dangerouslySetInnerHTML={{ __html: fill(m.h) }} /></Tip>;
  if (m.t === "watch") return WATCH_CARD;
  if (m.t === "confirm") return <ConfirmCard name={state.booked || "Your member-rate stay"} />;
  if (m.t === "cards") return (
    <div style={{ display: "flex", flexDirection: "column", gap: "8px", marginBottom: "9px" }}>
      <TripCard title="Ocean Pointe Suites @ Key Largo" location="Tavernier, FL" meta="Sat 09/12 – 09/19/26 · 1 BR · sleeps 4" rating={3} availability="2 units left" lowAvailability preferred price="$1,219" onBook={() => onBook("Ocean Pointe Suites @ Key Largo")} />
      <TripCard title="Club Wyndham Royal Sea Cliff" location="Kailua, HI" meta="Fri 10/30 – 11/06/26 · 2 BR · sleeps 6" rating={4} availability="2 available" price="$2,219" onBook={() => onBook("Club Wyndham Royal Sea Cliff")} />
    </div>
  );
  if (m.t === "review") return (
    <div style={{ background: "#fff", border: "1px solid #e2e8f1", borderRadius: "14px", padding: "13px 14px", maxWidth: "90%", marginBottom: "9px", boxShadow: "var(--shadow-sm)" }}>
      <div style={{ fontSize: "10px", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--muted)", fontWeight: 800 }}>Your last stay</div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "14px", color: "var(--navy-800)", margin: "3px 0 7px" }}>Cabo Azul Resort · San José del Cabo</div>
      <StarRating value={5} size={20} />
      <button onClick={onReview} style={{ marginTop: "11px", width: "100%", background: "var(--gold-500)", color: "var(--navy-900)", fontFamily: "var(--font-sans)", fontWeight: 800, fontSize: "13px", border: "none", borderRadius: "var(--radius-pill)", padding: "10px 14px", cursor: "pointer" }}>Send review to our team →</button>
      <div style={{ fontSize: "11px", color: "var(--muted)", marginTop: "7px", textAlign: "center" }}>Goes straight to Steve &amp; the Member Experience team.</div>
    </div>
  );
  return null;
}

/* The embedded Gigi chat widget. Self-contained, click-through via quick replies. */
function GigiWidget({ onClose }) {
  const [step, setStep] = React.useState("start");
  const [state, setState] = React.useState({});
  const [shown, setShown] = React.useState(0);     // how many messages of current step are visible
  const [typing, setTyping] = React.useState(false);
  const [memberMsg, setMemberMsg] = React.useState(null);
  const logRef = React.useRef(null);
  const node = FLOW[step];

  // Reveal messages one at a time with a typing pause.
  React.useEffect(() => {
    setShown(0);
    let i = 0;
    let timer;
    const tick = () => {
      if (i >= node.msgs.length) return;
      setTyping(true);
      timer = setTimeout(() => {
        setTyping(false);
        i += 1;
        setShown(i);
        if (i < node.msgs.length) timer = setTimeout(tick, 220);
      }, 460);
    };
    tick();
    return () => clearTimeout(timer);
  }, [step]);

  React.useEffect(() => {
    if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
  }, [shown, typing, step]);

  const choose = (c) => {
    setMemberMsg(c.label);
    const ns = { ...state };
    if (c.set) {
      if (step === "mood") ns.mood = c.set;
      else if (step === "who") ns.who = c.set;
      else if (step === "when") ns.when = c.set;
    }
    setState(ns);
    setTimeout(() => { setMemberMsg(null); setStep(c.next); }, 280);
  };

  const onBook = (name) => { setMemberMsg(`Book ${name}`); setState((s) => ({ ...s, booked: name })); setTimeout(() => { setMemberMsg(null); setStep("booked"); }, 300); };
  const onReview = () => { setMemberMsg("Send my review ⭐"); setTimeout(() => { setMemberMsg(null); setStep("reviewSent"); }, 300); };
  const allShown = shown >= node.msgs.length && !typing;

  return (
    <div style={{
      width: "374px", maxWidth: "calc(100vw - 28px)", height: "600px", maxHeight: "calc(100vh - 36px)",
      background: "#eef2f6", borderRadius: "20px", overflow: "hidden", display: "flex", flexDirection: "column",
      boxShadow: "0 26px 60px rgba(42,72,136,.4)", border: "1px solid #cbd3dc", fontFamily: "var(--font-sans)",
    }}>
      <style>{`
        .grow{display:flex;align-items:flex-end;gap:8px;}
        .glog::-webkit-scrollbar{width:6px}.glog::-webkit-scrollbar-thumb{background:#cfd7e0;border-radius:6px}
      `}</style>
      <div style={{ background: "var(--grad-navy)", color: "#fff", padding: "13px 14px", display: "flex", alignItems: "center", gap: "11px" }}>
        <Avatar name="Gigi" size={38} />
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 800, fontSize: "15px", display: "flex", alignItems: "center", gap: "8px" }}>
            Gigi <span style={{ fontSize: "9px", background: "var(--gold-500)", color: "var(--navy-900)", borderRadius: "4px", padding: "2px 5px", fontWeight: 800 }}>TRAVEL GUIDE</span>
          </div>
          <div style={{ fontSize: "11.5px", color: "#9fd3a0", display: "flex", alignItems: "center", gap: "5px" }}>
            <span style={{ width: "7px", height: "7px", borderRadius: "50%", background: "var(--green-500)" }} /> Online · always here, even after hours
          </div>
        </div>
        <button onClick={onClose} aria-label="Minimize" style={{ background: "rgba(255,255,255,.12)", border: "none", color: "#fff", cursor: "pointer", fontSize: "18px", width: "30px", height: "30px", borderRadius: "50%" }}>–</button>
      </div>

      <div ref={logRef} className="glog" style={{ flex: 1, overflowY: "auto", padding: "15px 13px 8px", scrollBehavior: "smooth" }}>
        {node.msgs.slice(0, shown).map((m, idx) => <Msg key={step + idx} m={m} state={state} onBook={onBook} onReview={onReview} />)}
        {typing && <div className="grow"><Avatar name="Gigi" size={26} /><TypingDots /></div>}
        {memberMsg && <ChatBubble from="member">{memberMsg}</ChatBubble>}
      </div>

      <div style={{ display: "flex", gap: "8px", flexWrap: "wrap", padding: "10px 13px 14px", opacity: allShown && !memberMsg ? 1 : 0.35, pointerEvents: allShown && !memberMsg ? "auto" : "none", transition: "opacity .2s" }}>
        {node.chips.map((c) => (
          <Chip key={c.label} variant={c.primary ? "primary" : "default"} onClick={() => choose(c)}>{c.label}</Chip>
        ))}
      </div>
    </div>
  );
}
window.GigiWidget = GigiWidget;
