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 = {
    cars: <><path d="M3 13l2-5a2 2 0 0 1 2-1h10a2 2 0 0 1 2 1l2 5" /><path d="M3 13h18v5a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1v-1H7v1a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-5z" /><circle cx="7" cy="16" r="1" /><circle cx="17" cy="16" r="1" /></>,
    star: <path d="M12 3l2.7 5.5 6 .9-4.4 4.2 1 6-5.3-2.8L6.7 19.6l1-6L3.3 9.4l6-.9L12 3z" fill="currentColor" />,
    pin: <><path d="M12 21s-7-6.5-7-12a7 7 0 0 1 14 0c0 5.5-7 12-7 12z" /><circle cx="12" cy="9" r="2.5" /></>,
    cal: <><rect x="3" y="5" width="18" height="16" rx="1" /><path d="M3 9h18M8 3v4M16 3v4" /></>,
    interior: <><rect x="3" y="8" width="18" height="11" rx="1" /><path d="M7 8V5h10v3M3 13h18" /></>,
    paint: <><path d="M4 7l8-4 8 4-8 4-8-4z" /><path d="M4 12l8 4 8-4M4 17l8 4 8-4" /></>,
    droplet: <path d="M12 3s-6 7-6 11a6 6 0 0 0 12 0c0-4-6-11-6-11z" />,
    shield: <><path d="M12 3l8 3v6c0 4.5-3.5 8.5-8 9.5-4.5-1-8-5-8-9.5V6l8-3z" /><path d="M9 12l2 2 4-4" /></>,
    quote: <><path d="M3 14h4l2-2v-5H4v5l1 2zM14 14h4l2-2v-5h-5v5l1 2z" /></>,
    arrow: <><path d="M5 12h14M13 6l6 6-6 6" /></>,
    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="#top" className="nav-logo" onClick={close}>
        <img src="assets/logo.png" alt="JP Detailing" />
      </a>
      <div className="nav-links">
        <a href="#top">Home</a>
        <a href="#services">Services</a>
        <a href="#pricing">Pricing</a>
        <a href="#gallery">Gallery</a>
        <a href="#about">About</a>
      </div>
      <div className="nav-right">
        <a href="tel:7866578123" className="nav-phone">786 · 657 · 8123</a>
        <a href="#book" className="btn btn-primary btn-small nav-book" style={{ fontWeight: "700" }}>
          Book Now <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="#top" onClick={close}>Home</a>
        <a href="#services" onClick={close}>Services</a>
        <a href="#pricing" onClick={close}>Pricing</a>
        <a href="#gallery" onClick={close}>Gallery</a>
        <a href="#about" onClick={close}>About</a>
        <a href="tel:7866578123" onClick={close} className="nav-mobile-phone">786 · 657 · 8123</a>
        <a href="#book" onClick={close} className="btn btn-primary nav-mobile-cta">
          Book Now <span className="btn-arrow">→</span>
        </a>
      </div>
    </nav>);

}

/* ============ HERO ============ */
function Hero() {
  const words = ["Your", "Car", "Deserves"];
  return (
    <section className="hero" id="top" data-screen-label="Hero">
      <div className="hero-bg">
        <img src="assets/hero-car.png" alt="" />
      </div>
      <div className="hero-overlay" />
      <div className="hero-content">
        <div className="hero-text">
          <div className="hero-eyebrow eyebrow eyebrow-orange">
            <span className="dot" /> Fast · Premium · Reliable
          </div>
          <h1 className="hero-title display">
            {words.map((w, i) =>
            <span key={i} style={{ animationDelay: `${0.1 + i * 0.12}s` }}>{w}&nbsp;</span>
            )}
            <span className="accent" style={{ animationDelay: `0.5s` }}>the Best.</span>
          </h1>
          <p className="hero-sub">Luxury detailing delivered directly to your driveway. No drop-off. No waiting room. Just the kind of finish your car earned the day you bought it.

          </p>
          <div className="hero-ctas">
            <a href="#book" className="btn btn-primary">Book Now <span className="btn-arrow">→</span></a>
            <a href="#services" className="btn btn-ghost">See Services</a>
          </div>
        </div>
        <div />
      </div>
      <div className="scroll-indicator">
        <span>Scroll</span>
        <div className="chev" />
      </div>
    </section>);

}

/* ============ TRUST ============ */
function CountUp({ to, suffix = "", duration = 1600 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min((now - start) / duration, 1);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.floor(eased * to));
            if (t < 1) requestAnimationFrame(tick);else
            setVal(to);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{val}{suffix}</span>;
}

function TrustBar() {
  const items = [
  { icon: "cars", value: <><CountUp to={20} />+</>, label: "Cars Detailed" },
  { icon: "star", value: <><CountUp to={5} />★</>, label: "Average Rating" },
  { icon: "pin", value: "We  Come", label: "To You" },
  { icon: "cal", value: "Same Week", label: "Booking" }];

  return (
    <section className="trust" data-screen-label="Trust Bar">
      <div className="trust-inner">
        {items.map((it, i) =>
        <div className="trust-item" key={i}>
            <div className="trust-icon"><Icon name={it.icon} size={32} /></div>
            <div>
              <div className="trust-num">{it.value}</div>
              <div className="trust-label">{it.label}</div>
            </div>
          </div>
        )}
      </div>
    </section>);

}

/* ============ 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;
}

/* ============ SERVICES ============ */
function Services() {
  const services = [
  { tier: "detail", tag: "Detailing", name: "Interior Detail", icon: "interior", desc: "Deep clean, steam treatment, surface dressing. Every seam, every vent, restored." },
  { tier: "detail", tag: "Detailing", name: "Exterior Detail", icon: "paint", desc: "Paint decontamination, machine polish, sealed protection that lasts months not weeks." },
  { tier: "wash", tag: "Maintenance", name: "Maintenance Wash", icon: "droplet", desc: "Weekly or bi-weekly upkeep. Inside vacuumed, outside hand-washed. Keep the showroom finish." },
  { tier: "detail", tag: "Detailing", name: "Clay Bar + Sealcoat", icon: "shield", desc: "Paint prep and long-lasting hydrophobic protection. Water beads off for nine months plus." }];

  const ref = useReveal();
  return (
    <section className="section" id="services" data-screen-label="Services">
      <div className="section-head reveal" ref={ref}>
        <span className="eyebrow eyebrow-orange"></span>
        <h2 className="section-title display">What we do, <span className="accent">in detail.</span></h2>
      </div>
      <div className="services-grid">
        {services.map((s, i) =>
        <div key={i} className={"service-card " + s.tier}>
            <div className="service-icon"><Icon name={s.icon} size={36} stroke={1.25} /></div>
            <div className="service-tag">{s.tag}</div>
            <h3 className="service-name">{s.name}</h3>
            <p className="service-desc">{s.desc}</p>
            <a href="#pricing" className="service-link">Learn More <span>→</span></a>
          </div>
        )}
      </div>
    </section>);

}

/* ============ LEAD MAGNET ============ */
function LeadBanner() {
  return (
    <section className="lead" data-screen-label="Lead Magnet">
      <div className="lead-inner">
        <div>
          <div className="lead-eyebrow">First-Time Customer Offer</div>
          <h3 className="lead-title">Free Sealcoat with<br />your first detail.</h3>
          <p className="lead-sub">Available for new customers. Mention this offer when you book, we'll handle the rest.</p>
        </div>
        <a href="#book" className="btn btn-dark">Claim Offer <span className="btn-arrow">→</span></a>
      </div>
    </section>);

}

/* ============ HOW IT WORKS ============ */
function HowItWorks() {
  const steps = [
  { n: "01", title: "Get a Quote", desc: "Text or call us with a few photos of your vehicle and its details, and we'll provide a personalized quote the same day." },
  { n: "02", title: "Schedule a Time", desc: "Pick a date that works. Mornings, afternoons, weekends. We confirm by text and show up on time." },
  { n: "03", title: "We Come to You", desc: "Driveway, office lot, anywhere with water access. Two to four hours, and you don't move a thing." }];

  const ref = useReveal();
  return (
    <section className="section" data-screen-label="How It Works">
      <div className="section-head reveal" ref={ref}>
        <span className="eyebrow"></span>
        <h2 className="section-title display">How it works.</h2>
      </div>
      <div className="how-grid">
        {steps.map((s, i) =>
        <React.Fragment key={i}>
          <div className="how-step">
            <div className="how-num">{s.n}</div>
            <h4 className="how-title">{s.title}</h4>
            <p className="how-desc">{s.desc}</p>
          </div>
          {i < steps.length - 1 &&
          <div className="how-arrow" aria-hidden="true">
            <svg viewBox="0 0 80 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <line x1="2" y1="12" x2="62" y2="12" strokeDasharray="4 6" />
              <path d="M56 4 L72 12 L56 20" />
            </svg>
          </div>
          }
        </React.Fragment>
        )}
      </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" }];


  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" id="gallery" data-screen-label="Before/After" 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>);

}

/* ============ PRICING ============ */
function Pricing() {
  const [vt, setVt] = useState("Coupe / Sedan");
  const types = ["Coupe / Sedan", "SUV / Crossover", "Truck"];
  const prices = {
    "Coupe / Sedan": { detail: 249, wash: 79 },
    "SUV / Crossover": { detail: 299, wash: 99 },
    "Truck": { detail: 329, wash: 109 }
  };
  const p = prices[vt];
  const ref = useReveal();
  return (
    <section className="section" id="pricing" data-screen-label="Pricing">
      <div className="section-head reveal" ref={ref}>
        <span className="eyebrow"></span>
        <h2 className="section-title display">Honest prices.<br />No surprises.</h2>
      </div>
      <div className="pricing-tabs">
        {types.map((t) =>
        <button key={t} className={"pricing-tab" + (vt === t ? " active" : "")} onClick={() => setVt(t)}>{t}</button>
        )}
      </div>
      <div className="pricing-cols">
        <div className="price-card detail">
          <div className="price-tier">Detailing</div>
          <h3 className="price-name">Full Detail</h3>
          <div className="price-amount">
            <span className="price-from">From</span>
            <span className="price-value">${p.detail}</span>
          </div>
          <ul className="price-list">
            <li>Interior deep clean & steam</li>
            <li>Exterior hand wash & polish</li>
            <li>Tire, trim & wheel dressing</li>
            <li>Window & glass treatment</li>
          </ul>
          <a href="#book" className="btn btn-primary">Book a Detail <span className="btn-arrow">→</span></a>
        </div>
        <div className="price-card wash">
          <div className="price-tier">Maintenance</div>
          <h3 className="price-name">Maintenance Wash</h3>
          <div className="price-amount">
            <span className="price-from">From</span>
            <span className="price-value">${p.wash}</span>
            <span className="price-unit">/ visit</span>
          </div>
          <ul className="price-list">
            <li>Exterior hand wash & dry</li>
            <li>Interior vacuum & wipe</li>
            <li>Window clean inside + out</li>
            <li>Best paired with a monthly plan</li>
          </ul>
          <a href="#plans" className="btn btn-ghost">Set Up a Plan <span className="btn-arrow">→</span></a>
        </div>
      </div>
      <p className="price-foot" style={{ marginTop: 32, color: "var(--text-dim)", fontSize: 13 }}>
        Pricing varies by vehicle condition and size. Contact us for an exact quote.
      </p>
    </section>);

}

/* ============ PLANS ============ */
function Plans() {
  const ref = useReveal();
  const plans = [
  { name: "Weekly", tag: "Most Frequent", price: 269, sub: "/ month · 4 visits", featured: false,
    list: ["Hand wash + interior touchup", "Wheels, glass, dressings", "Priority scheduling", "Cancel anytime"] },
  { name: "Bi-Weekly", tag: "Best Value", price: 149, sub: "/ month · 2 visits", featured: true,
    list: ["Hand wash + interior touchup", "Quarterly clay bar included", "Priority scheduling", "Save vs. one-off pricing"] },
  { name: "Monthly", tag: "Starter", price: 79, sub: "/ month · 1 visit", featured: false,
    list: ["Hand wash + interior touchup", "Reminder texts", "Locked-in pricing", "No commitment"] }];

  return (
    <section className="section" id="plans" data-screen-label="Plans" style={{ padding: "50px 24px 80px" }}>
      <div className="section-head reveal" ref={ref}>
        <span className="eyebrow eyebrow-blue"></span>
        <h2 className="section-title display">Stay clean<br />on autopilot.</h2>
      </div>
      <div className="plans-grid">
        {plans.map((pl, i) =>
        <div key={i} className={"plan-card" + (pl.featured ? " featured" : "")}>
            {pl.featured && <div className="plan-badge">Best Value</div>}
            <h3 className="plan-freq">{pl.name}</h3>
            <div className="plan-tag">{pl.tag}</div>
            <div className="plan-price">${pl.price}</div>
            <div className="plan-price-sub">{pl.sub}</div>
            <ul className="plan-list">
              {pl.list.map((it, j) => <li key={j}>{it}</li>)}
            </ul>
            <a href="#book" className="btn btn-plan">Get Started <span className="btn-arrow">→</span></a>
          </div>
        )}
      </div>
    </section>);

}

/* ============ TESTIMONIALS ============ */
function Testimonials() {
  const quotes = [
  { q: "Showed up on time, left my G-Wagon looking like it just rolled off the lot. Won't go anywhere else.", name: "Marcus T.", car: "2023 Mercedes GLS" },
  { q: "Booked it Tuesday, detailed by Saturday — in my driveway. The interior smells better than when I bought the car.", name: "Priya R.", car: "2021 Lexus RX" },
  { q: "JP found scratches the dealer told me couldn't come out. They came out. I tipped him double.", name: "Andre L.", car: "2020 BMW M340i" },
  { q: "Bi-weekly plan is the move. I forget when he comes — car's just always clean.", name: "Sofia M.", car: "2022 Tesla Model Y" },
  { q: "Most thorough detail I've ever paid for, and I've paid for a lot. The clay bar work is unreal.", name: "Jordan K.", car: "2019 Audi S5" },
  { q: "Old Tahoe looked tired. After his exterior detail it looked like a fresh trade-in. Money well spent.", name: "Derrick W.", car: "2017 Chevy Tahoe" }];

  const ref = useReveal();
  // duplicate for seamless loop
  const all = [...quotes, ...quotes];
  return (
    <section className="testimonials">
      <div className="section" data-screen-label="Testimonials">
        <div className="section-head reveal" ref={ref}>
          <span className="eyebrow"></span>
          <h2 className="section-title display">Real owners.<br />Real reviews.</h2>
        </div>
      </div>
      <div className="t-track-wrap">
        <div className="t-track">
          {all.map((t, i) =>
          <div className="t-card" key={i}>
              <div className="t-stars">★ ★ ★ ★ ★</div>
              <p className="t-quote">"{t.q}"</p>
              <div className="t-author"><strong>{t.name}</strong> · {t.car}</div>
            </div>
          )}
        </div>
      </div>
      <div style={{ height: 60 }} />
    </section>);

}

/* ============ FINAL CTA ============ */
function FinalCTA() {
  return (
    <section className="final" id="book" data-screen-label="Final CTA">
      <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="#" className="btn btn-primary">Book Online <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="#services">Services</a>
          <a href="#pricing">Pricing</a>
          <a href="#gallery">Gallery</a>
          <a href="#about">About</a>
          <a href="#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>);

}

/* ============ APP ============ */
function App() {
  return (
    <>
      <Nav />
      <Hero />
      <TrustBar />
      <Services />
      <LeadBanner />
      <HowItWorks />
      <BeforeAfter />
      <Pricing />
      <Plans />
      <Testimonials />
      <FinalCTA />
      <Footer />
    </>);

}

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