// ─── New mobile-first flow: FitFinder, SetupsCarousel, ReviewCarousel, FAQ ──
const { useState: useFS, useRef: useFR, useEffect: useFE, useMemo: useFM } = React;

/* ════════════════════════════════════════════════════════════
   FIT FINDER — inline mini-wizard (3 taps → price band)
   This is the budget filter, made visible before the contact gate.
   ════════════════════════════════════════════════════════════ */
function FitFinder({ openWizard }) {
  const [occasion, setOccasion] = useFS("");
  const [guests, setGuests] = useFS(60);
  const [space, setSpace] = useFS("");

  const occasions = [
    { id:"birthday",  emoji:"🎂", label:"Birthday" },
    { id:"garden",    emoji:"🌿", label:"Garden party" },
    { id:"corporate", emoji:"🏢", label:"Corporate" },
    { id:"other",     emoji:"🎉", label:"Something else" },
  ];
  const spaces = [
    { id:"small",  label:"Small",  sub:"6×6m + room" },
    { id:"medium", label:"Medium", sub:"8×8m + room" },
    { id:"large",  label:"Large",  sub:"10m+" },
  ];

  const ready = occasion && space;
  const result = useFM(() => {
    if (!ready) return null;
    // Venue pick
    const venue =
      space === "small"  ? (guests <= 20 ? { name:"Rave in a Cave or Bubble Tent", from: 595 } : { name:"6m Inflatable Dome", from: 494 })
      : space === "medium" ? (guests <= 80 ? { name:"8m Inflatable Dome", from: 595 } : { name:"10m Inflatable Dome", from: 795 })
      : (guests <= 200 ? { name:"12m Inflatable Dome", from: 1190 } : { name:"15m Inflatable Dome", from: 1490 });
    // Package depends on occasion
    const pkgMult = occasion === "corporate" ? 1.7 : occasion === "birthday" ? 1.55 : 1.3;
    const low  = Math.round((venue.from * pkgMult) / 50) * 50;
    const high = Math.round((low * 1.35) / 50) * 50;
    return { venue, low, high };
  }, [occasion, guests, space, ready]);

  return (
    <section className="section ff-section" id="fit-finder">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="h-eyebrow">QUICK FIT-FINDER</div>
            <h2>See your <span className="txt-pink">price</span> in 30&nbsp;seconds.</h2>
          </div>
          <p>Three taps, no email. We'll show you the setup that fits and a real price band — so you know before you enquire.</p>
        </div>

        <div className="ff-card">
          {/* Step 1: Occasion */}
          <div className="ff-step">
            <div className="ff-step-head">
              <span className="ff-num">01</span>
              <span className="ff-q">What kind of night?</span>
            </div>
            <div className="ff-chips">
              {occasions.map(o => (
                <button
                  key={o.id}
                  className={"ff-chip " + (occasion === o.id ? "on" : "")}
                  onClick={() => setOccasion(o.id)}>
                  <span className="ff-chip-emo">{o.emoji}</span>
                  {o.label}
                </button>
              ))}
            </div>
          </div>

          {/* Step 2: Guests */}
          <div className="ff-step">
            <div className="ff-step-head">
              <span className="ff-num">02</span>
              <span className="ff-q">How many guests?</span>
              <span className="ff-pop">{guests}</span>
            </div>
            <input
              className="ff-range"
              type="range" min="10" max="230" step="5"
              value={guests} onChange={e => setGuests(+e.target.value)} />
            <div className="ff-range-ticks">
              <span>10</span><span>50</span><span>100</span><span>150</span><span>200</span><span>230</span>
            </div>
          </div>

          {/* Step 3: Space */}
          <div className="ff-step">
            <div className="ff-step-head">
              <span className="ff-num">03</span>
              <span className="ff-q">Your space?</span>
            </div>
            <div className="ff-space">
              {spaces.map(s => (
                <button
                  key={s.id}
                  className={"ff-space-tile " + (space === s.id ? "on" : "")}
                  onClick={() => setSpace(s.id)}>
                  <span className="ff-space-name">{s.label}</span>
                  <span className="ff-space-sub">{s.sub}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Result */}
          <div className={"ff-result " + (ready ? "on" : "")}>
            {!ready && (
              <div className="ff-result-empty">
                <span className="ff-pulse" />
                Pick an occasion and your space size to see your price band.
              </div>
            )}
            {ready && result && (
              <>
                <div className="ff-result-top">
                  <div>
                    <div className="h-eyebrow" style={{color:"var(--gold)"}}>YOUR ESTIMATE · ALL-IN</div>
                    <div className="ff-result-num">
                      £{result.low.toLocaleString()}<span className="ff-dash">–</span>£{result.high.toLocaleString()}
                    </div>
                    <div className="ff-result-sub">
                      Best fit: <strong>{result.venue.name}</strong> · {guests} guests · incl. setup &amp; collection
                    </div>
                  </div>
                </div>
                <div className="ff-result-cta">
                  <button className="btn btn-primary" onClick={openWizard}>
                    Check my date <Icon.Arrow />
                  </button>
                  <a href="#setups" className="btn btn-ghost">Browse setups</a>
                </div>
                <div className="ff-result-note">
                  Final quote depends on extras (LED dancefloor, photobooth, etc.) — we'll itemise everything in your email.
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ════════════════════════════════════════════════════════════
   SETUPS CAROUSEL — horizontal swipe of all 8 inflatables
   Replaces the separate Fits + Venues sections.
   ════════════════════════════════════════════════════════════ */
function SetupsCarousel({ openWizard }) {
  const D = window.PP_DATA;
  const ref = useFR(null);
  const [active, setActive] = useFS(0);
  const setups = D.products.filter(p => p.cat !== "extras");

  const scrollBy = (dir) => {
    if (!ref.current) return;
    const card = ref.current.querySelector(".setup-card");
    if (!card) return;
    const w = card.getBoundingClientRect().width + 14;
    ref.current.scrollBy({ left: dir * w, behavior: "smooth" });
  };

  useFE(() => {
    const el = ref.current;
    if (!el) return;
    const onScroll = () => {
      const card = el.querySelector(".setup-card");
      if (!card) return;
      const w = card.getBoundingClientRect().width + 14;
      setActive(Math.round(el.scrollLeft / w));
    };
    el.addEventListener("scroll", onScroll, { passive: true });
    return () => el.removeEventListener("scroll", onScroll);
  }, []);

  const tagFor = (p) =>
    p.cat === "rave" ? { label: "RAVE CAVE", cls: "cyan" }
    : p.cat === "bubble" ? { label: "BUBBLE", cls: "gold" }
    : p.capacity >= 150 ? { label: "FLAGSHIP", cls: "pink" }
    : { label: "VIP DOME", cls: "pink" };

  return (
    <section className="section setups-section" id="setups">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="h-eyebrow">BROWSE THE SETUPS</div>
            <h2>Swipe through every <span className="txt-gold">venue we hire.</span></h2>
          </div>
          <div className="setups-nav">
            <button aria-label="Previous" onClick={() => scrollBy(-1)}><Icon.Back/></button>
            <button aria-label="Next" onClick={() => scrollBy(1)}><Icon.Arrow/></button>
          </div>
        </div>

        <div className="setups-track" ref={ref}>
          {setups.map((p, i) => {
            const tag = tagFor(p);
            return (
              <a key={p.id} href={`product.html?id=${p.id}`} className="setup-card">
                <div className="setup-img">
                  <Img src={p.img} />
                  <span className={"pill setup-tag pill-" + tag.cls}>{tag.label}</span>
                  <span className="setup-cap"><Icon.Users width={12} height={12}/> up to {p.capacity}</span>
                </div>
                <div className="setup-body">
                  <div className="setup-name">{p.name}</div>
                  <div className="setup-tagline">{p.tagline}</div>
                  <div className="setup-foot">
                    <div className="setup-from">
                      <span className="label">From</span>
                      <span className="num">£{p.price}</span>
                    </div>
                    <span className="setup-cta">View details <Icon.Arrow/></span>
                  </div>
                </div>
              </a>
            );
          })}
          <div className="setup-spacer"/>
        </div>

        <div className="setups-dots">
          {setups.map((_, i) => (
            <span key={i} className={"setups-dot " + (i === active ? "on" : "")}/>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ════════════════════════════════════════════════════════════
   REVIEW CAROUSEL — one big quote at a time
   ════════════════════════════════════════════════════════════ */
function ReviewCarousel() {
  const D = window.PP_DATA;
  // Add a couple more reviews for richer carousel
  const reviews = [
    ...D.reviews,
    { name: "Tom & Rachel", date: "Jan 2026", stars: 5,
      text: "Wedding after-party in the 12m dome. The bridesmaids haven't stopped talking about the lasers." },
    { name: "Aaliyah B.", date: "Dec 2025", stars: 5,
      text: "Booked the rave cave for my 25th. Tiny garden, massive night. Worth every penny." },
  ];
  const [i, setI] = useFS(0);
  const next = () => setI(v => (v + 1) % reviews.length);
  const prev = () => setI(v => (v - 1 + reviews.length) % reviews.length);

  const photos = [
    "https://popupparties.uk/wp-content/uploads/2023/08/Skype_Picture_2022_05_18T06_13_37_837Z.jpg",
    "https://popupparties.uk/wp-content/uploads/2023/08/IMG_0729-1.jpg",
    "https://popupparties.uk/wp-content/uploads/2023/11/imgpsh_fullsize_anim.png",
    "https://popupparties.uk/wp-content/uploads/2023/08/IMG_2591-1.jpg",
  ];

  const r = reviews[i];
  return (
    <section className="section" id="reviews">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="h-eyebrow">REAL PARTIES, REAL REVIEWS</div>
            <h2>312 parties. <span className="txt-gold">4.8★ average.</span></h2>
          </div>
          <p>Every review verified through Google. Photos are real guests, real gardens.</p>
        </div>

        <div className="rev-stage">
          <div className="rev-card">
            <div className="rev-stars">
              {[0,1,2,3,4].map(j => <Icon.Star key={j} width={20} height={20} style={{opacity: j < r.stars ? 1 : 0.25}}/>)}
            </div>
            <p className="rev-quote">"{r.text}"</p>
            <div className="rev-meta">
              <strong>— {r.name}</strong>
              <span>{r.date} · Google review</span>
            </div>
          </div>
          <div className="rev-controls">
            <button aria-label="Previous review" onClick={prev}><Icon.Back/></button>
            <div className="rev-dots">
              {reviews.map((_, j) => (
                <button key={j} className={"rev-dot " + (j === i ? "on" : "")} onClick={() => setI(j)} aria-label={"Review " + (j+1)}/>
              ))}
            </div>
            <button aria-label="Next review" onClick={next}><Icon.Arrow/></button>
          </div>
        </div>

        <div className="rev-strip">
          {photos.map((p, j) => (
            <div key={j} className="rev-photo"><Img src={p}/></div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ════════════════════════════════════════════════════════════
   FAQ — accordion on desktop, pill-chips + bottom-sheet on mobile
   ════════════════════════════════════════════════════════════ */
function FAQ() {
  const items = [
    {
      q: "What's the lead time for booking?",
      shortQ: "Lead time",
      a: "Most weekends book out 4–6 weeks ahead in summer. Off-peak (Oct–Mar) we can often deliver within 7–10 days. Always worth asking — we'll be honest about availability."
    },
    {
      q: "How much is the deposit?",
      shortQ: "Deposit",
      a: "25% to secure your date. The remainder is due 14 days before delivery. We accept card, bank transfer, and invoice for corporate."
    },
    {
      q: "What if it rains?",
      shortQ: "Rain & weather",
      a: "Every inflatable is fully weatherproof — they're rated for sustained UK weather. We only postpone for severe winds (40mph+). Free reschedule if we ever have to call it."
    },
    {
      q: "Do I need to provide power?",
      shortQ: "Power",
      a: "A single 13A domestic socket is enough for most setups. We bring all extension cables and a small generator's available if you're going off-grid."
    },
    {
      q: "How much space do I actually need?",
      shortQ: "Space needed",
      a: "Add 1m clearance on every side of the inflatable. So a 6m dome needs about 8×8m. We do a free virtual survey from a photo of your garden before you commit."
    },
    {
      q: "Are you insured?",
      shortQ: "Insurance",
      a: "Yes — £5m public liability, fully PAT-tested kit, certified setup crew. We'll send the certs with your contract."
    },
    {
      q: "Can I cancel or reschedule?",
      shortQ: "Cancel / reschedule",
      a: "Free reschedule up to 14 days before — pick any future date in the next 12 months. Inside 14 days we hold 50% of the package; weather-related calls from us are always free to reschedule."
    },
  ];
  const [open, setOpen] = useFS(-1);

  // Close sheet on Esc
  useFE(() => {
    if (open < 0) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(-1); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  return (
    <section className="section faq-section" id="faq">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="h-eyebrow">BEFORE YOU ASK</div>
            <h2>The honest <span className="txt-pink">answers.</span></h2>
          </div>
          <p>Seven things people ask before enquiring. If we missed one, WhatsApp us — we'll reply faster than you expect.</p>
        </div>

        {/* Desktop: accordion */}
        <div className="faq-list">
          {items.map((it, idx) => {
            const isOpen = open === idx;
            return (
              <div key={idx} className={"faq-item " + (isOpen ? "open" : "")}>
                <button className="faq-q" onClick={() => setOpen(isOpen ? -1 : idx)} aria-expanded={isOpen}>
                  <span>{it.q}</span>
                  <span className="faq-plus" aria-hidden="true">
                    <span/><span/>
                  </span>
                </button>
                <div className="faq-a-wrap">
                  <p className="faq-a">{it.a}</p>
                </div>
              </div>
            );
          })}
        </div>

        {/* Mobile: pill-chips that open a bottom sheet */}
        <div className="faq-chips" role="list">
          {items.map((it, idx) => (
            <button
              key={idx}
              className={"faq-chip " + (open === idx ? "on" : "")}
              onClick={() => setOpen(idx)}
              aria-haspopup="dialog"
            >
              {it.shortQ}
              <Icon.Arrow width={12} height={12} />
            </button>
          ))}
        </div>

        {/* Mobile bottom sheet */}
        <div
          className={"faq-sheet-shroud " + (open >= 0 ? "open" : "")}
          onClick={() => setOpen(-1)}
          aria-hidden={open < 0}
        >
          <div className="faq-sheet" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
            <div className="faq-sheet-grip" aria-hidden="true" />
            {open >= 0 && (
              <>
                <div className="faq-sheet-eyebrow">
                  <span className="h-eyebrow pink">{items[open].shortQ}</span>
                  <button className="faq-sheet-close" onClick={() => setOpen(-1)} aria-label="Close">×</button>
                </div>
                <h3 className="faq-sheet-q">{items[open].q}</h3>
                <p className="faq-sheet-a">{items[open].a}</p>
                <div className="faq-sheet-nav">
                  <button
                    onClick={() => setOpen((open - 1 + items.length) % items.length)}
                    aria-label="Previous question"
                  >
                    <Icon.Back width={14} height={14}/> Prev
                  </button>
                  <span className="faq-sheet-count">{open + 1} / {items.length}</span>
                  <button
                    onClick={() => setOpen((open + 1) % items.length)}
                    aria-label="Next question"
                  >
                    Next <Icon.Arrow width={14} height={14}/>
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FitFinder, SetupsCarousel, ReviewCarousel, FAQ });
