const { Button, Select, Input, Icon } = window.FriendsCarsDesignSystem_f69f0e;

const HERO_SLIDES = ["gle", "thar", "e250", "520d", "crysta", "creta-new", "sonet", "fronx"].map((id) => window.FLEET.find((c) => c.id === id)).filter(Boolean);
const SLIDE_MS = 6400;
const splitName = (c) => {
  const model = c.name.replace(c.marque, "").replace(/[()]/g, "").trim();
  return [c.marque, model || c.name];
};

function HeroStage({ onNavigate, onBook }) {
  const [i, setI] = React.useState(0);
  const [hold, setHold] = React.useState(false);
  const [stageRef, o] = window.usePointerParallax(1);

  React.useEffect(() => {
    if (hold) return;
    const t = setTimeout(() => setI((n) => (n + 1) % HERO_SLIDES.length), SLIDE_MS);
    return () => clearTimeout(t);
  }, [i, hold]);

  /* Scroll parallax + cinematic fade-off. rAF-throttled, skipped for reduced motion. */
  React.useEffect(() => {
    const el = stageRef.current;
    if (!el || window.matchMedia("(prefers-reduced-motion:reduce)").matches) return;
    let raf = 0, last = -1;
    const paint = () => {
      raf = 0;
      const y = Math.min(window.scrollY, 900);
      if (y === last) return;
      last = y;
      el.style.setProperty("--sy", (y * 0.16).toFixed(1) + "px");
      el.style.setProperty("--fade", Math.max(0, 1 - y / 720).toFixed(3));
    };
    const on = () => { if (!raf) raf = requestAnimationFrame(paint); };
    window.addEventListener("scroll", on, { passive: true });
    paint();
    return () => { window.removeEventListener("scroll", on); if (raf) cancelAnimationFrame(raf); };
  }, [stageRef]);

  const car = HERO_SLIDES[i];
  const [marque, model] = splitName(car);
  const go = (n) => setI((n + HERO_SLIDES.length) % HERO_SLIDES.length);
  const queue = HERO_SLIDES.slice(i + 1).concat(HERO_SLIDES.slice(0, i));

  return (
    <section className="fc-hero" aria-label="Friends Car — self-drive rental in Mumbai">
      <div className="fc-hero-stage" ref={stageRef} style={{ "--px": o.x, "--py": o.y }}
        onMouseEnter={() => setHold(true)} onMouseLeave={() => setHold(false)}>
        <div className="fc-hero-media">
          <div className="fc-hero-plane">
            {HERO_SLIDES.map((c, n) => (
              <figure key={c.id} className="fc-hero-slide" data-on={n === i ? "1" : "0"} aria-hidden={n === i ? "false" : "true"}>
                <img src={c.img} alt={c.name + " on self-drive rent in Mumbai from Friends Car"} loading={n ? "lazy" : "eager"} decoding="async" style={{ "--pos-d": c.pos || "center 55%", "--pos-m": c.posm || "center 48%" }} />
              </figure>
            ))}
          </div>
          <span className="fc-hero-sweep" aria-hidden="true"></span>
        </div>

        <div className="fc-hero-inner">
          <div className="fc-hero-prog"><i key={i} aria-hidden="true"></i></div>

          <div className="fc-hero-lead">
            <div className="fc-hero-plate" key={car.id}>
              <h1 className="fc-hero-h1"><span>{"Self-drive car rental in " + window.BIZ.city + " · Since " + window.BIZ.since}</span></h1>
              <span className="fc-hero-word" aria-hidden="true"><b>{marque}</b><b>{model}</b></span>
              <div className="fc-hero-meta">
                <span>{car.fuel}</span><span>{car.gearbox}</span><span>{car.seats} seats</span><span>{window.BIZ.kmPerDay} km / day</span>
              </div>
              <p className="fc-hero-copy">Seventy cars, delivered to your door in {window.BIZ.city} and taken back from it.</p>
              <div className="fc-hero-rate-row">
                <span className="fc-hero-rate">{window.rupees(car.price)} <em>/ day</em></span>
                <Button variant="floating" size="lg" iconRight="arrow-right" onClick={() => onBook(car)}>Book this car</Button>
                <button className="fc-hero-link" onClick={() => onNavigate("Fleet")}><span>Explore all 27</span><Icon name="arrow-right" size={15} /></button>
              </div>
            </div>

            <div className="fc-hero-deck">
              <div className="fc-hero-cards" key={i} role="list" aria-label="Cars in the showreel">
                {queue.map((c) => (
                  <button key={c.id} className="fc-hero-card" onClick={() => go(HERO_SLIDES.indexOf(c))} aria-label={"Show " + c.name}>
                    <img src={window.thumb(c.img)} alt="" loading="lazy" decoding="async" width="520" height="693" style={{ objectPosition: c.pos || "center 55%" }} />
                    <span className="fc-hero-card-body">
                      <strong>{splitName(c)[1]}</strong>
                      <em>{window.rupees(c.price)} / day</em>
                    </span>
                  </button>
                ))}
              </div>
              <div className="fc-hero-ctrl">
                <span className="fc-hero-count"><b>{("0" + (i + 1)).slice(-2)}</b> / {("0" + HERO_SLIDES.length).slice(-2)}</span>
                <button className="fc-hero-arrow" aria-label="Previous car" onClick={() => go(i - 1)}><Icon name="arrow-left" size={17} /></button>
                <button className="fc-hero-arrow" aria-label="Next car" onClick={() => go(i + 1)}><Icon name="arrow-right" size={17} /></button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <BookingPanel onSubmit={onBook} />
    </section>
  );
}

function BookingPanel({ onSubmit }) {
  const today = new Date().toISOString().slice(0, 10);
  const [cat, setCat] = React.useState("");
  const [car, setCar] = React.useState("");
  const cars = window.FLEET.filter((c) => !cat || c.cat === cat);
  return (
    <div className="fc-book" data-reveal>
      <div className="fc-book-head">
        <span className="fc-eyebrow">Check availability</span>
        <span className="fc-book-note"><Icon name="phone" size={14} color="var(--accent)" /> or call {window.BIZ.phone1}</span>
      </div>
      <div className="fc-book-grid">
        <Select label="Category" placeholder="Any category" value={cat} onChange={(e) => { setCat(e.target.value); setCar(""); }}
          options={window.CATEGORIES.map((c) => ({ value: c.id, label: c.label }))} />
        <Select label="Car" placeholder="Any car" value={car} onChange={(e) => setCar(e.target.value)}
          options={cars.map((c) => ({ value: c.id, label: c.name }))} />
        <Input label="Pickup date" type="date" defaultValue={today} />
        <Input label="Pickup time" type="time" defaultValue="10:00" />
        <Input label="Return date" type="date" defaultValue={today} />
        <Input label="Return time" type="time" defaultValue="10:00" />
        <Button variant="primary" size="lg" fullWidth iconRight="arrow-right" onClick={() => onSubmit(car ? window.FLEET.find((c) => c.id === car) : null)}>Search</Button>
      </div>
    </div>
  );
}

Object.assign(window, { HeroStage, BookingPanel });
