// bally.jsx — Bally & Co. Motors (Service & Maintenance view)
const { useRef: useBallyRef, useEffect: useBallyEffect } = React;

const BALLY_FEATURES = [
  "Over 20 years of automotive experience",
  "Domestic and import vehicle service",
  "Fleet maintenance and repair programs",
  "Advanced diagnostic capabilities",
  "OEM and quality aftermarket parts",
  "Honest recommendations and transparent communication",
];

// Cinematic, scroll-reactive video hero. The clip sits full-bleed behind the
// wordmark; as you scroll the footage slowly zooms + drifts (parallax), the
// scrim deepens, and the content rises and fades — a single continuous move.
function BallyHero({ onHome }) {
  const heroRef = useBallyRef(null);
  const vidRef = useBallyRef(null);
  const innerRef = useBallyRef(null);
  const scrimRef = useBallyRef(null);
  const cueRef = useBallyRef(null);

  // Keep the clip playing. Muted autoplay is usually allowed, but throttled /
  // gesture-gated contexts can defer it — so we retry on visibility + first
  // interaction. Honor a genuine reduced-motion preference by leaving it paused.
  useBallyEffect(() => {
    const v = vidRef.current;
    if (!v) return;
    const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduced) return;
    const tryPlay = () => { const p = v.play && v.play(); if (p && p.catch) p.catch(() => {}); };
    tryPlay();
    const io = "IntersectionObserver" in window
      ? new IntersectionObserver((es) => es.forEach((e) => e.isIntersecting && tryPlay()), { threshold: 0.05 })
      : null;
    if (io) io.observe(v);
    const onKick = () => tryPlay();
    window.addEventListener("pointerdown", onKick, { passive: true });
    window.addEventListener("scroll", onKick, { passive: true });
    document.addEventListener("visibilitychange", onKick);
    return () => {
      if (io) io.disconnect();
      window.removeEventListener("pointerdown", onKick);
      window.removeEventListener("scroll", onKick);
      document.removeEventListener("visibilitychange", onKick);
    };
  }, []);

  useBallyEffect(() => {
    const hero = heroRef.current;
    if (!hero) return;
    // Respect throttled/offscreen/reduced-motion: leave a tasteful static frame.
    if (document.documentElement.classList.contains("anim-off")) return;
    let raf = 0;
    const apply = () => {
      const h = hero.offsetHeight || window.innerHeight || 1;
      const y = window.scrollY || 0;
      const p = Math.max(0, Math.min(1, y / h));
      if (vidRef.current)
        vidRef.current.style.transform = `scale(${(1.06 + 0.18 * p).toFixed(3)}) translateY(${(y * 0.12).toFixed(1)}px)`;
      if (innerRef.current) {
        innerRef.current.style.transform = `translateY(${(-y * 0.14).toFixed(1)}px)`;
        innerRef.current.style.opacity = (Math.max(0, 1 - p * 1.3)).toFixed(3);
      }
      if (scrimRef.current) scrimRef.current.style.opacity = (0.7 + 0.3 * p).toFixed(3);
      if (cueRef.current) cueRef.current.style.opacity = (Math.max(0, 1 - p * 4)).toFixed(3);
    };
    const onScroll = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(apply); };
    apply();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <section className="bally-hero bally-hero--video" ref={heroRef}>
      <div className="bally-hero-bg" />
      <div className="bally-hero-stage">
        <video ref={vidRef} className="bally-hero-video" src="assets/lambo.mp4"
          autoPlay muted loop playsInline preload="auto" />
      </div>
      <div className="bally-hero-tint" />
      <div className="bally-hero-scrim" ref={scrimRef} />
      <div className="bally-hero-grain" />
      <div className="container bally-hero-inner" ref={innerRef}>
        <Reveal className="bally-hero-content">
          <div className="eyebrow eyebrow-chrome"><span className="eyebrow-tick" />The Standard Behind the Fleet</div>
          <img src="assets/bally-logo-v3.png" alt="Bally &amp; Co. Motors" className="bally-logo" />
          <h1 className="bally-title">Bally &amp; Co. Motors</h1>
          <p className="bally-sub">
            Every Chairman’s Reserve vehicle is maintained by Bally &amp; Co. Motors — so what arrives
            at your door is nothing short of immaculate.
          </p>
          <button className="text-link chrome-link" onClick={onHome}>← Back to Chairman’s Reserve</button>
        </Reveal>
      </div>
      <div className="bally-hero-scroll" ref={cueRef}><span>Scroll</span><i /></div>
    </section>
  );
}

function Bally({ onReserve, onHome }) {
  return (
    <main className="bally">
      <BallyHero onHome={onHome} />

      <section className="section bally-maint">
        <div className="container">
          <div className="bally-grid">
            <Reveal className="bally-maint-copy">
              <Eyebrow>Service Bay</Eyebrow>
              <h2 className="section-title">Maintenance &amp; Repair</h2>
              <p className="bally-tagline">Elevated Standards. Every Time.</p>
              <p className="section-intro">
                From business fleets to family vehicles, Bally &amp; Co. Motors provides dependable
                maintenance and repair services backed by more than two decades of industry experience.
                We understand that every vehicle serves a purpose, which is why we focus on accurate
                diagnostics, quality repairs, and clear communication throughout the process.
              </p>
              <p className="section-intro">
                Whether you’re responsible for a fleet of vehicles or simply need a trusted shop for your
                daily driver, our commitment remains the same: deliver reliable service, minimize downtime,
                and help you get the most from your investment.
              </p>
            </Reveal>
            <Reveal delay={120} className="bally-caps">
              <span className="bally-caps-label">What Sets the Standard</span>
              <ul className="bally-features">
                {BALLY_FEATURES.map((f, i) => (
                  <li key={f} style={{ transitionDelay: `${i * 70}ms` }}>
                    <span className="tick">
                      <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 6.5" /></svg>
                    </span>
                    <span className="feat-text">{f}</span>
                  </li>
                ))}
              </ul>
            </Reveal>
          </div>
        </div>
      </section>

      <section className="section bally-cta-sec">
        <div className="container bally-cta">
          <Reveal>
            <p className="bally-cta-line">Professional Service Without the Dealership Runaround.</p>
            <GoldButton size="lg" onClick={() => scrollToInquiry("bally-service")}>Begin a Conversation</GoldButton>
          </Reveal>
        </div>
      </section>

      <InquiryForm
        id="bally-service"
        eyebrow="Service Bay"
        title="Schedule Maintenance or Service"
        intro="Book your vehicle in with Bally & Co. Motors. Share a few details and our service team will confirm timing and bring it in for the attention it deserves."
        interestLabel="Service Type"
        interestPlaceholder="Select a service…"
        interestOptions={["Routine Maintenance", "Diagnostics & Repair", "Detailing", "Pre-Purchase Inspection", "Other"]}
        datesLabel="Preferred Date"
        datesPlaceholder="Select a date…"
        dateMode="single"
        submitText="Request Service"
        sentTitle="Request Received"
        messagePlaceholder="Vehicle make/model, mileage, and what you'd like done…"
        contactPhone="(832) 977-6477"
        contactHours="8:00am – 6:00pm"
      />
    </main>
  );
}

Object.assign(window, { Bally });
