/* ============================================================
   PRESTIGE BIMMER — Public chrome: Nav, Hero, About, Contact, Footer
   ============================================================ */

/* ---------------- Logo mark ---------------- */
function Logo({ size = 34 }) {
  return (
    <div className="pb-logo" aria-label="Prestige Bimmer">
      <svg width={size} height={size} viewBox="0 0 40 40" fill="none">
        <circle cx="20" cy="20" r="18.5" stroke="url(#lg)" strokeWidth="1.4" />
        <path d="M20 1.5 A18.5 18.5 0 0 1 38.5 20 L20 20 Z" fill="rgba(31,109,255,0.16)" />
        <path d="M20 38.5 A18.5 18.5 0 0 1 1.5 20 L20 20 Z" fill="rgba(31,109,255,0.16)" />
        <line x1="20" y1="1.5" x2="20" y2="38.5" stroke="url(#lg)" strokeWidth="1.1" />
        <line x1="1.5" y1="20" x2="38.5" y2="20" stroke="url(#lg)" strokeWidth="1.1" />
        <defs>
          <linearGradient id="lg" x1="0" y1="0" x2="40" y2="40">
            <stop stopColor="#4d8bff" /><stop offset="1" stopColor="#0a44c4" />
          </linearGradient>
        </defs>
      </svg>
      <div className="pb-logo-txt">
        <span className="pb-logo-name">PRESTIGE</span>
        <span className="pb-logo-sub">BIMMER</span>
      </div>
    </div>
  );
}

/* ---------------- Nav ---------------- */
function Nav({ route }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const h = () => setScrolled(window.scrollY > 24);
    h(); window.addEventListener("scroll", h, { passive: true });
    return () => window.removeEventListener("scroll", h);
  }, []);
  useEffect(() => { setOpen(false); }, [route.raw]);

  const links = [
    ["Home", "/"], ["Inventory", "/inventory"], ["About", "/about"], ["Contact", "/contact"],
  ];
  const isActive = (p) => (p === "/" ? route.name === "home" : route.raw.startsWith(p.slice(1)));

  return (
    <header className={"nav " + (scrolled ? "nav-scrolled " : "") + (open ? "nav-open" : "")}>
      <div className="nav-inner wrap">
        <a href="#/" className="nav-brand"><Logo /></a>
        <nav className="nav-links">
          {links.map(([label, path]) => (
            <a key={path} href={"#" + path} className={"nav-link " + (isActive(path) ? "active" : "")}>
              <span>{label}</span>
            </a>
          ))}
        </nav>
        <div className="nav-cta">
          <a href="#/contact" className="btn btn-primary nav-book">Book a Viewing <Icon name="arrow" size={16} /></a>
          <a href="#/admin" className="nav-admin" title="Admin"><Icon name="lock" size={17} /></a>
          <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="Menu">
            <Icon name={open ? "x" : "menu"} size={22} />
          </button>
        </div>
      </div>
      <div className="nav-mobile">
        {links.map(([label, path]) => (
          <a key={path} href={"#" + path} className="nav-mobile-link">{label}</a>
        ))}
        <a href="#/contact" className="btn btn-primary btn-block" style={{ marginTop: 12 }}>Book a Viewing</a>
        <a href="#/admin" className="nav-mobile-link" style={{ opacity: .6 }}>Admin</a>
      </div>
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero() {
  const ref = useRef(null);
  const [my, setMy] = useState({ x: 0, y: 0 });
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      const el = ref.current; if (!el) return;
      el.style.setProperty("--sy", y + "px");
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const onMove = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    setMy({ x: (e.clientX - r.left) / r.width - 0.5, y: (e.clientY - r.top) / r.height - 0.5 });
  };

  const featured = useInventory().filter(v => v.featured).slice(0, 1)[0];

  return (
    <section className="hero" ref={ref} onMouseMove={onMove} onMouseLeave={() => setMy({ x: 0, y: 0 })}>
      <div className="hero-stage" style={{ transform: `translate3d(${my.x * -14}px, ${my.y * -14}px, 0)` }}>
        <Photo className="hero-photo" label="HERO — BMW M5 in motion, low cinematic angle"
          src={(featured && featured.heroImg) || "uploads/8273aca3674d4478abf5d4d8ec4df682.webp"} />
        <div className="hero-vignette" />
      </div>

      <div className="hero-content wrap">
        <div className="hero-kicker-row">
          <span className="kicker">Specialist Pre-Owned BMW</span>
          <span className="hero-loc mono"><Icon name="pin" size={13} /> By appointment · Miami</span>
        </div>

        <h1 className="hero-title display-xl">
          <span className="hl" style={{ "--i": 0 }}>Drive the</span>
          <span className="hl hero-accent" style={{ "--i": 1 }}>extraordinary.</span>
        </h1>

        <p className="hero-lede lede">
          A hand-selected collection of the finest pre-owned BMWs. Every car inspected to
          150 points, fully documented, and ready to be driven home.
        </p>

        <div className="hero-actions">
          <a href="#/inventory" className="btn btn-primary btn-lg">Explore the Collection <Icon name="arrow" size={17} /></a>
          <a href="#/contact" className="btn btn-ghost btn-lg">Book a Private Viewing</a>
        </div>

        <div className="hero-stats">
          <HeroStat n={150} suffix="-pt" label="Inspection on every car" />
          <HeroStat n={100} suffix="%" label="Provenance documented" />
          <HeroStat n={48} suffix="h" label="Home delivery, nationwide" />
        </div>
      </div>

      <div className="hero-scroll mono">
        <span>SCROLL</span>
        <span className="hero-scroll-line" />
      </div>
    </section>
  );
}

function HeroStat({ n, suffix, label }) {
  const ref = useRef(null);
  const [run, setRun] = useState(false);
  useEffect(() => {
    const io = new IntersectionObserver(([e]) => e.isIntersecting && setRun(true), { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const v = useCountUp(n, run);
  return (
    <div className="hero-stat" ref={ref}>
      <div className="hero-stat-n display-m tnum">{Math.round(v)}<span className="hero-stat-suf">{suffix}</span></div>
      <div className="hero-stat-l">{label}</div>
    </div>
  );
}

/* ---------------- Marquee ---------------- */
function Marquee() {
  const items = ["M5 COMPETITION", "X5 xDRIVE40i", "540i M SPORT", "i4 GRAN COUPÉ", "M340i", "740i", "X3 M40i", "330i M SPORT"];
  const row = [...items, ...items];
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {row.map((t, i) => (
          <span key={i} className="marquee-item mono">{t}<i className="marquee-dot" /></span>
        ))}
      </div>
    </div>
  );
}

/* ---------------- Process / Why us ---------------- */
function Process() {
  useRevealObserver();
  const steps = [
    ["01", "shield", "150-point inspection", "Every vehicle is mechanically and cosmetically assessed by BMW-trained technicians before it earns a place in our collection."],
    ["02", "search", "Full provenance", "Complete service history, inspection records, and ownership trail — verified and presented to you in a digital dossier."],
    ["03", "spark", "Concierge handover", "Detailed, fuelled and delivered to your door within 48 hours, or enjoy an espresso at our Miami showroom."],
  ];
  return (
    <section className="section process" id="process">
      <div className="wrap">
        <div className="sec-head">
          <span className="kicker" data-reveal>The Prestige standard</span>
          <h2 className="display-l" data-reveal style={{ "--d": "60ms" }}>
            Buying pre-owned,<br />without the compromise.
          </h2>
        </div>
        <div className="process-grid">
          {steps.map(([n, icon, title, body], i) => (
            <article className="process-card card" data-reveal style={{ "--d": `${i * 110}ms` }} key={n}>
              <div className="process-top">
                <span className="process-num mono">{n}</span>
                <span className="process-icon"><Icon name={icon} size={22} /></span>
              </div>
              <h3 className="process-title">{title}</h3>
              <p className="process-body text-dim">{body}</p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- About ---------------- */
function AboutSection() {
  useRevealObserver();
  return (
    <section className="section about" id="about">
      <div className="wrap about-grid">
        <div className="about-copy">
          <span className="kicker" data-reveal>Our story</span>
          <h2 className="display-l" data-reveal style={{ "--d": "60ms" }}>
            Obsessed with<br />the marque.
          </h2>
          <p className="lede" data-reveal style={{ "--d": "120ms" }}>
            Prestige Bimmer was founded on a single belief: that buying a pre-owned BMW
            should feel as considered as the engineering itself. We don't trade volume —
            we curate.
          </p>
          <p className="text-dim" data-reveal style={{ "--d": "180ms", marginTop: 18 }}>
            Each car in our collection is chosen by enthusiasts, for enthusiasts. We turn
            away nine cars for every one we accept. What remains is a tightly-held selection
            of the cleanest, best-documented examples on the market.
          </p>
          <div className="about-stats" data-reveal style={{ "--d": "240ms" }}>
            <div><strong className="display-m">12</strong><span>years specialising</span></div>
            <div><strong className="display-m">2,400+</strong><span>cars delivered</span></div>
            <div><strong className="display-m">4.9</strong><span>avg. owner rating</span></div>
          </div>
        </div>
        <div className="about-media" data-reveal="right">
          <Photo className="about-photo" label="Showroom — Miami, BMWs under warm light" ratio="3 / 4" />
          <div className="about-badge card">
            <Icon name="star" size={18} fill />
            <div><strong>Specialist of the Year</strong><span className="mono">PRE-OWNED · 2025</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Contact / Booking ---------------- */
function ContactSection() {
  useRevealObserver();
  const [form, setForm] = useState({ name: "", email: "", phone: "", interest: "", date: "", msg: "" });
  const [sent, setSent] = useState(false);
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const submit = (e) => { e.preventDefault(); setSent(true); };

  const inv = useInventory().filter(v => v.status !== "sold");

  return (
    <section className="section contact" id="contact">
      <div className="wrap contact-grid">
        <div className="contact-intro">
          <span className="kicker" data-reveal>Book a viewing</span>
          <h2 className="display-l" data-reveal style={{ "--d": "60ms" }}>
            Come and<br />feel the difference.
          </h2>
          <p className="lede" data-reveal style={{ "--d": "120ms" }}>
            Reserve a private appointment at our Miami showroom, or request a video
            walk-around. No pressure, no sales theatre — just the car and the facts.
          </p>
          <div className="contact-details" data-reveal style={{ "--d": "180ms" }}>
            <ContactRow icon="pin"   label="Showroom"  value="140 NE 39th Street, Design District, Miami, FL 33137" />
            <ContactRow icon="phone" label="Telephone" value="+1 (305) 555-0142" />
            <ContactRow icon="mail"  label="Email"     value="hello@prestigebimmer.com" />
            <ContactRow icon="clock" label="Hours"     value="Mon–Sat · 9:00–18:00 · By appointment" />
          </div>
        </div>

        <div className="contact-form-wrap card" data-reveal="right">
          {sent ? (
            <div className="contact-sent">
              <div className="contact-sent-ic"><Icon name="check" size={34} /></div>
              <h3 className="display-m">Request received.</h3>
              <p className="text-dim">Thank you, {form.name || "there"}. A specialist will be in touch within one business hour to confirm your appointment.</p>
              <button className="btn btn-ghost" onClick={() => { setSent(false); setForm({ name:"",email:"",phone:"",interest:"",date:"",msg:"" }); }}>Send another</button>
            </div>
          ) : (
            <form onSubmit={submit} className="contact-form">
              <h3 className="contact-form-title">Request an appointment</h3>
              <Field label="Full name"><input required value={form.name} onChange={set("name")} placeholder="Jane Doe" /></Field>
              <div className="field-row">
                <Field label="Email"><input required type="email" value={form.email} onChange={set("email")} placeholder="jane@email.com" /></Field>
                <Field label="Phone"><input value={form.phone} onChange={set("phone")} placeholder="+1…" /></Field>
              </div>
              <div className="field-row">
                <Field label="Vehicle of interest">
                  <select value={form.interest} onChange={set("interest")}>
                    <option value="">Any / not sure yet</option>
                    {inv.map(v => <option key={v.id} value={v.model}>{v.year} {v.model}</option>)}
                  </select>
                </Field>
                <Field label="Preferred date"><input type="date" value={form.date} onChange={set("date")} /></Field>
              </div>
              <Field label="Message (optional)"><textarea rows="3" value={form.msg} onChange={set("msg")} placeholder="Anything we should know?" /></Field>
              <button className="btn btn-primary btn-block btn-lg" type="submit">Request Appointment <Icon name="arrow" size={17} /></button>
              <p className="contact-fineprint mono">Typical response · under 60 minutes</p>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

function ContactRow({ icon, label, value }) {
  return (
    <div className="contact-row">
      <span className="contact-row-ic"><Icon name={icon} size={18} /></span>
      <div><span className="contact-row-l mono">{label}</span><span className="contact-row-v">{value}</span></div>
    </div>
  );
}

function Field({ label, children }) {
  return <label className="field"><span className="field-label mono">{label}</span>{children}</label>;
}

/* ---------------- Banner (full-bleed image + overlay) ---------------- */
function Banner() {
  useRevealObserver();
  const ref = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const el = ref.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const prog = (window.innerHeight - r.top) / (window.innerHeight + r.height); // 0→1 across viewport
      const shift = (prog - 0.5) * 70; // px parallax
      el.style.setProperty("--py", shift.toFixed(1) + "px");
    };
    onScroll(); window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section className="banner" id="banner">
      <div className="banner-media" ref={ref}>
        <image-slot id="home-banner" shape="rect" fit="cover"
          src="uploads/2020-BMW-M5-Driving-Down-Highway.avif"
          placeholder="Drop a wide BMW banner photo here"></image-slot>
        <div className="banner-overlay"></div>
        <div className="banner-grain"></div>
      </div>
      <div className="banner-content wrap">
        <span className="kicker" data-reveal>The drive awaits</span>
        <h2 className="display-l banner-title" data-reveal style={{ "--d": "80ms" }}>
          Engineered<br />to move you.
        </h2>
        <p className="lede banner-lede" data-reveal style={{ "--d": "160ms" }}>
          From the first turn of the key to the last mile home — every BMW in our
          collection is chosen to be driven, not just owned.
        </p>
        <a href="#/inventory" className="btn btn-primary btn-lg banner-cta" data-reveal style={{ "--d": "240ms" }}>
          Explore the collection <Icon name="arrow" size={17} />
        </a>
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-brand">
            <Logo size={40} />
            <p className="text-dim" style={{ maxWidth: "34ch", marginTop: 18 }}>
              Specialist pre-owned BMW, curated for the driver who knows the difference.
            </p>
          </div>
          <div className="footer-cols">
            <FooterCol title="Explore" links={[["Inventory","/inventory"],["About us","/about"],["Book a viewing","/contact"]]} />
            <FooterCol title="Models" links={[["3 Series","/inventory"],["5 Series","/inventory"],["X Models","/inventory"],["M Division","/inventory"]]} />
            <FooterCol title="Company" links={[["Finance","/contact"],["Trade-in","/contact"],["Admin","/admin"]]} />
          </div>
        </div>
        <div className="footer-bottom">
          <span className="mono">© {new Date().getFullYear()} PRESTIGE BIMMER LLC · Miami, FL</span>
          <span className="mono text-dim">Not affiliated with BMW AG. Independent specialist dealer.</span>
        </div>
      </div>
    </footer>
  );
}
function FooterCol({ title, links }) {
  return (
    <div className="footer-col">
      <h4 className="footer-col-title mono">{title}</h4>
      {links.map(([l, p]) => <a key={l + p} href={"#" + p} className="footer-link">{l}</a>)}
    </div>
  );
}

Object.assign(window, {
  Logo, Nav, Hero, Marquee, Process, AboutSection, ContactSection, Banner, Footer, Field, ContactRow,
});
