const { useState, useEffect, useRef } = React;

/* ============ ICONS ============ */
const Icon = ({ name, size = 24, stroke = 1.5 }) => {
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    text: <><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M7 10h10M7 14h6" /></>
  };
  return <svg {...common}>{paths[name]}</svg>;
};

/* ============ NAV ============ */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
  }, [open]);
  const close = () => setOpen(false);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "") + (open ? " open" : "")}>
      <a href="index.html" className="nav-logo" onClick={close}>
        <img src="assets/logo.png" alt="JP Detailing" />
      </a>
      <div className="nav-links">
        <a href="index.html">Home</a>
        <a href="index.html#services">Services</a>
        <a href="index.html#pricing">Pricing</a>
        <a href="gallery.html" style={{ color: "var(--accent-detail)" }}>Gallery</a>
        <a href="index.html#about">About</a>
      </div>
      <div className="nav-right">
        <a href="tel:7866578123" className="nav-phone">786 · 657 · 8123</a>
        <a href="tel:7866578123" className="btn btn-primary btn-small nav-book" style={{ fontWeight: "700" }}>
          Call Us <span className="btn-arrow">→</span>
        </a>
        <button
          className="nav-burger"
          aria-label={open ? "Close menu" : "Open menu"}
          aria-expanded={open}
          onClick={() => setOpen(o => !o)}
        >
          <span /><span /><span />
        </button>
      </div>
      <div className={"nav-mobile" + (open ? " open" : "")}>
        <a href="index.html" onClick={close}>Home</a>
        <a href="index.html#services" onClick={close}>Services</a>
        <a href="index.html#pricing" onClick={close}>Pricing</a>
        <a href="gallery.html" onClick={close}>Gallery</a>
        <a href="index.html#about" onClick={close}>About</a>
        <a href="tel:7866578123" onClick={close} className="nav-mobile-phone">786 · 657 · 8123</a>
        <a href="tel:7866578123" onClick={close} className="btn btn-primary nav-mobile-cta">
          Call Us · 786-657-8123 <span className="btn-arrow">→</span>
        </a>
      </div>
    </nav>
  );
}

/* ============ REVEAL HOOK ============ */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

/* ============ GALLERY PAGE HERO ============ */
function GalleryHero() {
  return (
    <section className="gal-hero">
      <div className="gal-hero-inner">
        <div className="eyebrow eyebrow-orange" style={{ marginBottom: 16 }}>JP Detailing · Our Work</div>
        <h1 className="display gal-hero-title">
          Every car. <span className="accent">Every detail.</span>
        </h1>
        <p className="gal-hero-sub">
          Real vehicles. Real results. Browse by make and see what a proper detail actually looks like.
        </p>
      </div>
    </section>
  );
}

/* ============ GALLERY CAROUSELS ============ */
function GalleryRow({ images, reverse }) {
  const doubled = [...images, ...images];
  return (
    <div className="gal-track-wrap">
      <div className={"gal-track" + (reverse ? " gal-track-rev" : "")}>
        {doubled.map((src, i) =>
          <div key={i} className="gal-item">
            <img src={src} alt="" loading="lazy" />
          </div>
        )}
      </div>
    </div>
  );
}

function Gallery() {
  const cats = [
    { label: "Mercedes-Benz", images: [
      "assets/gallery/mercedes/1.jpg","assets/gallery/mercedes/2.jpg",
      "assets/gallery/mercedes/3.jpg","assets/gallery/mercedes/4.jpg",
      "assets/gallery/mercedes/5.jpg","assets/gallery/mercedes/6.jpg",
      "assets/gallery/mercedes/7.jpg","assets/gallery/mercedes/8.jpg"] },
    { label: "BMW", images: [
      "assets/gallery/bmw/1.jpg","assets/gallery/bmw/2.jpg",
      "assets/gallery/bmw/3.jpg","assets/gallery/bmw/4.jpg",
      "assets/gallery/bmw/5.jpg","assets/gallery/bmw/6.jpg",
      "assets/gallery/bmw/7.jpg","assets/gallery/bmw/8.jpg"] },
    { label: "Tesla", images: [
      "assets/gallery/tesla/1.jpg","assets/gallery/tesla/2.jpg",
      "assets/gallery/tesla/3.jpg","assets/gallery/tesla/4.jpg",
      "assets/gallery/tesla/5.jpg","assets/gallery/tesla/6.jpg",
      "assets/gallery/tesla/7.jpg","assets/gallery/tesla/8.jpg"] },
    { label: "Toyota", images: [
      "assets/gallery/toyota/1.jpg","assets/gallery/toyota/2.jpg",
      "assets/gallery/toyota/3.jpg","assets/gallery/toyota/4.jpg",
      "assets/gallery/toyota/5.jpg","assets/gallery/toyota/6.jpg"] },
    { label: "Ram", images: [
      "assets/gallery/ram/1.jpg","assets/gallery/ram/2.jpg",
      "assets/gallery/ram/3.jpg","assets/gallery/ram/4.jpg",
      "assets/gallery/ram/5.jpg"] },
  ];
  const ref = useReveal();
  return (
    <section className="gal-section" style={{ paddingTop: 48 }}>
      {cats.map((cat, i) =>
        <div key={i} className="gal-category">
          <div className="gal-cat-label">{cat.label}</div>
          <GalleryRow images={cat.images} reverse={i % 2 !== 0} />
        </div>
      )}
    </section>
  );
}

/* ============ BEFORE / AFTER ============ */
function BeforeAfter() {
  const [pos, setPos] = useState(50);
  const [idx, setIdx] = useState(0);
  const wrap = useRef(null);
  const dragging = useRef(false);
  const items = [
    { label: "Exterior Hand Wash", car: "Alfa Romeo Spider", before: "assets/ba/red-before.jpg", after: "assets/ba/red-after.jpg" },
    { label: "Cargo Bay Deep Clean", car: "BMW X3 M", before: "assets/ba/trunk-before.jpg", after: "assets/ba/trunk-after.jpg" },
    { label: "Wheel Detail", car: "Mercedes-Benz GLE", before: "assets/ba/mb-wheel-before.jpg", after: "assets/ba/mb-wheel-after.jpg" },
    { label: "Brake Dust Removal", car: "BMW M4", before: "assets/ba/bmw-wheel-before.jpg", after: "assets/ba/bmw-wheel-after.jpg" },
    { label: "Full Exterior Wash", car: "Tesla Model X", before: "assets/ba/tesla-wash-before.jpg", after: "assets/ba/tesla-wash-after.jpg" },
    { label: "Interior Detail", car: "Toyota Prius Prime", before: "assets/ba/prius-int-before.jpg", after: "assets/ba/prius-int-after.jpg" },
    { label: "Floor Mat Restoration", car: "Ram 1500 Limited", before: "assets/ba/ram-floor-before.jpg", after: "assets/ba/ram-floor-after.jpg" },
    { label: "Interior Deep Clean", car: "Tesla Model Y", before: "assets/ba/tesla-int-before.jpg", after: "assets/ba/tesla-int-after.jpg" },
  ];

  useEffect(() => {
    const t1 = setTimeout(() => setPos(78), 800);
    const t2 = setTimeout(() => setPos(50), 1800);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [idx]);

  const move = (clientX) => {
    if (!wrap.current) return;
    const r = wrap.current.getBoundingClientRect();
    const p = Math.max(2, Math.min(98, (clientX - r.left) / r.width * 100));
    setPos(p);
  };
  const onDown = (e) => { dragging.current = true; move(e.clientX || e.touches?.[0]?.clientX); };
  const onMove = (e) => { if (dragging.current) move(e.clientX || e.touches?.[0]?.clientX); };
  const onUp = () => { dragging.current = false; };

  useEffect(() => {
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  const ref = useReveal();
  return (
    <section className="section" style={{ padding: "80px 24px" }}>
      <div className="section-head reveal" ref={ref}>
        <span className="eyebrow eyebrow-orange"></span>
        <h2 className="section-title display">Before. <span className="accent">After.</span><br />Always honest.</h2>
      </div>
      <div className="ba-wrap" ref={wrap} onMouseDown={onDown} onTouchStart={onDown}>
        <img className="ba-before ba-img" src={items[idx].before} alt="Before" />
        <img className="ba-after ba-img" src={items[idx].after} alt="After" style={{ clipPath: `inset(0 0 0 ${pos}%)` }} />
        <div className="ba-label ba-label-before">Before</div>
        <div className="ba-label ba-label-after">After</div>
        <div className="ba-handle" style={{ left: `${pos}%` }}>
          <div className="ba-handle-grip" />
        </div>
      </div>
      <div className="ba-caption">
        <div className="ba-caption-text">
          <strong>{items[idx].label}</strong> &nbsp;·&nbsp; {items[idx].car}
        </div>
        <div className="ba-dots">
          {items.map((_, i) =>
            <button key={i} className={"ba-dot" + (i === idx ? " active" : "")} onClick={() => { setIdx(i); setPos(50); }} />
          )}
        </div>
      </div>
    </section>
  );
}

/* ============ FINAL CTA ============ */
function FinalCTA() {
  return (
    <section className="final" id="book">
      <div className="final-orb" aria-hidden="true"></div>
      <div className="final-inner">
        <span className="eyebrow eyebrow-orange" style={{ fontSize: "17px", fontWeight: "700" }}>Ready to Book?</span>
        <h2 className="final-title">
          Your car is <span className="accent">waiting.</span>
        </h2>
        <div className="final-ctas">
          <a href="tel:7866578123" className="btn btn-primary">Call Us · 786-657-8123 <span className="btn-arrow">→</span></a>
          <a href="sms:7866578123" className="btn btn-text">
            <Icon name="text" size={18} /> &nbsp; Or text us · (786) 657-8123
          </a>
        </div>
      </div>
    </section>
  );
}

/* ============ FOOTER ============ */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-brand">
          <img src="assets/logo.png" alt="JP Detailing" />
          <div className="footer-meta">Mobile detailing — South Florida<br />786 · 657 · 8123 · hello@jpdetailing.co</div>
        </div>
        <div className="footer-links">
          <a href="index.html#services">Services</a>
          <a href="index.html#pricing">Pricing</a>
          <a href="gallery.html">Gallery</a>
          <a href="index.html#about">About</a>
          <a href="index.html#book">Book</a>
        </div>
      </div>
      <div className="footer-base">
        <span>© 2026 JP Detailing. All rights reserved.</span>
        <span>Built for owners who care.</span>
      </div>
    </footer>
  );
}

/* ============ GALLERY PAGE APP ============ */
function App() {
  return (
    <>
      <Nav />
      <GalleryHero />
      <Gallery />
      <BeforeAfter />
      <FinalCTA />
      <Footer />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<App />);
