/* Home, Collection grid, Vehicle Detail */
const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP } = React;

/* ============================================================
   HOME
   ============================================================ */
function Home({ navigate, openEnquire }) {
  const featured = INVENTORY.filter(v => v.status === "available").slice(0, 6);
  return (
    <div className="page">
      {/* HERO */}
      <section className="hero">
        <div className="bg" style={{ backgroundImage: "url('media/hero-home-banner.webp')" }} />
        <div className="scrim" />
        <div className="content">
          <div className="eyebrow">Dubai · Since 2014</div>
          <h1 className="display">
            A gallery of classic cars<br/>
            <em className="italic-serif" style={{ color: "var(--brass-light)" }}>born from pure passion</em><br/>
            for timeless beauty.
          </h1>
          <div className="cta-row">
            <button className="btn btn-solid" onClick={() => navigate("collection")}>
              <span className="label">Explore the Collection</span>
            </button>
            <button className="btn btn-ghost" onClick={() => openEnquire({ kind: "general" })}>
              <span className="label">Enquire</span>
            </button>
          </div>
        </div>
        <div className="scroll-hint">
          <span>Scroll</span><span className="bar"></span>
        </div>
      </section>

      {/* INTRO */}
      <section className="section noir">
        <div className="shell">
          <div className="editorial-two">
            <div>
              <div className="eyebrow" style={{ color: "var(--brass-light)" }}>01 — Who we are</div>
              <div className="rule" style={{ marginTop: 18 }}></div>
              <h2 className="display">Tomini Classics is no common car dealership.</h2>
            </div>
            <div>
              <p className="provenance" style={{ color: "#d5d2cc" }}>
                A curated, passion-led gallery of post-war European sportscars — from the 1930s
                through to the future modern classics — alongside a small selection of automobilia
                and timepieces. The collection began privately in 2010 with a 1967 Jaguar E-Type;
                Tomini Classics was established as the automotive division of the Tomini Group in 2014.
                We buy, we hold, and we sell with radical transparency. Relationships always come before sales.
              </p>
              <div style={{ marginTop: 28 }}>
                <button className="btn-link" onClick={() => navigate("about")}>The full story →</button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* FEATURED COLLECTION */}
      <section className="section">
        <div className="shell">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 56, gap: 24, flexWrap: "wrap" }}>
            <div>
              <div className="eyebrow" style={{ opacity: 0.55 }}>02 — Currently on display</div>
              <h2 className="display" style={{ marginTop: 14, maxWidth: "18ch" }}>From the gallery floor.</h2>
            </div>
            <button className="btn-link" onClick={() => navigate("collection")}>View the full collection →</button>
          </div>
          <div className="v-grid">
            {featured.map(v => <VehicleCard key={v.id} v={v} navigate={navigate} />)}
          </div>
        </div>
      </section>

      {/* VALUES */}
      <section className="section noir">
        <div className="shell">
          <div style={{ marginBottom: 48 }}>
            <div className="eyebrow" style={{ color: "var(--brass-light)" }}>03 — Our philosophy</div>
            <h2 className="display" style={{ marginTop: 14, maxWidth: "18ch" }}>Three principles we will not bend.</h2>
          </div>
          <div className="value-list">
            <div>
              <div className="n">/ 01</div>
              <h3>Authenticity</h3>
              <p>Every car is inspected in-house — from paint readings to a comprehensive test drive — and described faithfully. We disclose negatives openly.</p>
            </div>
            <div>
              <div className="n">/ 02</div>
              <h3>Passion</h3>
              <p>The collection began for love, and it is still run that way. We hold the cars we love long enough to know them deeply.</p>
            </div>
            <div>
              <div className="n">/ 03</div>
              <h3>Diversity</h3>
              <p>From a Patent-Motorwagen tribute to a future modern classic — almost a century of curated European craft, in one room.</p>
            </div>
          </div>
        </div>
      </section>

      {/* SERVICES TEASER */}
      <section className="section">
        <div className="shell">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32 }} className="services-grid">
            {[
              { title: "Storage", img: "media/services-banner.webp", desc: "White-glove, climate-controlled, dust-free. Minimum one month. Twenty-four-hour access by prior arrangement." },
              { title: "Valuation", img: "media/services-assessment.webp", desc: "Fair, unbiased valuation reports for insurance or resale — weighing originality, provenance and condition." },
              { title: "Consulting", img: "media/services-consulting.webp", desc: "Collection-building advice tailored to taste, needs and budget. Market opinion, not market hype." }
            ].map(s => (
              <div key={s.title} className="service-card" style={{ cursor: "pointer" }} onClick={() => navigate("services")}>
                <div style={{ aspectRatio: "4/3", overflow: "hidden", marginBottom: 18, background: "var(--ink)" }}>
                  <img src={s.img} alt={s.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </div>
                <h3 className="display" style={{ fontSize: 28, margin: "8px 0" }}>{s.title}</h3>
                <p className="muted" style={{ margin: 0, maxWidth: "36ch" }}>{s.desc}</p>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 56, textAlign: "center" }}>
            <button className="btn-link" onClick={() => navigate("services")}>All services →</button>
          </div>
        </div>
      </section>

      {/* WANTED TEASER */}
      <section className="section" style={{ background: "var(--stone)" }}>
        <div className="shell">
          <div className="editorial-two">
            <div>
              <div className="eyebrow" style={{ opacity: 0.6 }}>04 — We are buyers, too</div>
              <h2 className="display" style={{ marginTop: 14 }}>Have a car we should know about?</h2>
              <p className="muted" style={{ maxWidth: "46ch" }}>
                We actively buy and trade selective post-war collectible sportscars. If yours fits the profile,
                we'd genuinely like to hear from you — and we'll tell you straight if it doesn't.
              </p>
              <div style={{ display: "flex", gap: 14, marginTop: 32, flexWrap: "wrap" }}>
                <button className="btn btn-solid" onClick={() => openEnquire({ kind: "sell" })}>
                  <span className="label">Sell us your car</span>
                </button>
                <button className="btn btn-link" onClick={() => navigate("wanted")}>
                  <span className="label">See the Wanted list →</span>
                </button>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--ink2)" }}>
              {WANTED.slice(0, 4).map((w, i) => (
                <div key={i} style={{ padding: 24, background: "var(--paper)" }}>
                  <div className="eyebrow" style={{ color: "var(--accent)", marginBottom: 8 }}>{w.year}</div>
                  <div className="display" style={{ fontSize: 22, lineHeight: 1.15 }}>{w.marque}<br/>{w.model}</div>
                  <p className="muted" style={{ fontSize: 13, marginTop: 8, marginBottom: 0 }}>{w.note}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* PRESS */}
      <section className="section-tight">
        <div className="shell">
          <div className="eyebrow" style={{ opacity: 0.5, textAlign: "center", marginBottom: 24 }}>As featured in</div>
          <PressStrip />
        </div>
      </section>

      {/* CONTACT BAND */}
      <section className="section noir">
        <div className="shell" style={{ textAlign: "center", maxWidth: 820, margin: "0 auto" }}>
          <div className="rule center"></div>
          <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)" }}>
            Visit us. Appointments<br/>are highly recommended.
          </h2>
          <p className="muted" style={{ marginTop: 24, fontSize: 16, maxWidth: 540, margin: "24px auto 0" }}>
            Sales by appointment, Monday to Friday, 09:00–17:00.<br/>
            Gallery open to enthusiasts daily, 09:00–22:00.
          </p>
          <div style={{ display: "flex", gap: 14, justifyContent: "center", marginTop: 36, flexWrap: "wrap" }}>
            <button className="btn btn-solid" onClick={() => openEnquire({ kind: "viewing" })}>
              <span className="label">Book a viewing</span>
            </button>
            <a className="btn btn-ghost" href="tel:+97143062032">
              <span className="label">+971 4 306 2032</span>
            </a>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ============================================================
   COLLECTION GRID
   ============================================================ */
function Collection({ navigate }) {
  const [make, setMake] = useStateP("All");
  const [era, setEra] = useStateP("All");
  const [body, setBody] = useStateP("All");
  const [status, setStatus] = useStateP("All");

  const makes = ["All", ...Array.from(new Set(INVENTORY.map(v => v.make)))];
  const eras = ["All", "Pre-war", "1950s", "1960s", "1970s"];
  const bodies = ["All", "Roadster", "Coupé", "Curiosity"];
  const statuses = ["All", "Available", "Reserved", "Sold"];

  const filtered = INVENTORY.filter(v =>
    (make === "All" || v.make === make) &&
    (era === "All" || v.era === era) &&
    (body === "All" || v.bodyType === body) &&
    (status === "All" || v.status === status.toLowerCase())
  );

  return (
    <div className="page" style={{ paddingTop: 120 }}>
      <section style={{ padding: "80px 0 40px" }}>
        <div className="shell">
          <div className="eyebrow" style={{ opacity: 0.55 }}>The Collection</div>
          <h1 className="display" style={{ marginTop: 16, maxWidth: "20ch" }}>
            Dubai's finest selection of post-war European sportscars.
          </h1>
          <p className="muted" style={{ maxWidth: "60ch", fontSize: 17, marginTop: 18 }}>
            A volatile, curated portfolio of roughly sixty examples on the gallery floor — and a wider
            collection in the private vault. Inventory rotates. Prices are quoted in US dollars on enquiry.
          </p>
        </div>
      </section>

      <section style={{ padding: "20px 0 80px" }}>
        <div className="shell">
          <FilterRow label="Make"   options={makes}    value={make}   onChange={setMake} />
          <FilterRow label="Era"    options={eras}     value={era}    onChange={setEra} />
          <FilterRow label="Body"   options={bodies}   value={body}   onChange={setBody} />
          <FilterRow label="Status" options={statuses} value={status} onChange={setStatus}
                     extra={<span className="results-count">{filtered.length} of {INVENTORY.length}</span>} />

          <div style={{ marginTop: 56 }} className="v-grid">
            {filtered.map(v => <VehicleCard key={v.id} v={v} navigate={navigate} />)}
            {filtered.length === 0 && (
              <div style={{ gridColumn: "1 / -1", textAlign: "center", padding: "80px 0", color: "var(--muted)" }}>
                <p className="italic-serif" style={{ fontSize: 22 }}>Nothing in stock matches these filters at the moment.</p>
                <button className="btn-link" onClick={() => { setMake("All"); setEra("All"); setBody("All"); setStatus("All"); }}>Reset filters →</button>
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}

function FilterRow({ label, options, value, onChange, extra }) {
  return (
    <div className="filter-bar" style={{ borderTop: "none" }}>
      <span className="filter-label">{label}</span>
      {options.map(o => (
        <button key={o} className={`chip ${value === o ? "active" : ""}`} onClick={() => onChange(o)}>{o}</button>
      ))}
      <div className="spacer" />
      {extra}
    </div>
  );
}

/* ============================================================
   VEHICLE DETAIL — the differentiator
   ============================================================ */
function VehicleDetail({ id, navigate, openEnquire, whatsappOn }) {
  const v = INVENTORY.find(x => x.id === id) || INVENTORY[0];
  const [lbIdx, setLbIdx] = useStateP(null);

  useEffectP(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [id]);
  useEffectP(() => {
    if (lbIdx === null) return;
    const onKey = e => {
      if (e.key === "Escape") setLbIdx(null);
      if (e.key === "ArrowRight") setLbIdx((lbIdx + 1) % v.images.length);
      if (e.key === "ArrowLeft") setLbIdx((lbIdx - 1 + v.images.length) % v.images.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [lbIdx, v]);

  const related = INVENTORY.filter(x => x.id !== v.id && x.make === v.make).slice(0, 3);
  const fillers = INVENTORY.filter(x => x.id !== v.id && x.make !== v.make).slice(0, 3 - related.length);
  const youMayLike = [...related, ...fillers].slice(0, 3);

  return (
    <div className="page">
      {/* CINEMATIC HERO */}
      <div className="vd-hero">
        <img src={v.hero} alt={`${v.year} ${v.make} ${v.model}`} />
        <div className="crumb mono" style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase" }}>
          <a onClick={() => navigate("home")}>Tomini Classics</a>
          <span className="sep">/</span>
          <a onClick={() => navigate("collection")}>Collection</a>
          <span className="sep">/</span>
          <span style={{ opacity: 0.85 }}>{v.year} {v.make} {v.model}</span>
        </div>
      </div>

      <section className="shell">
        <div className="vd-layout">
          {/* LEFT */}
          <div>
            <div className="vd-title">
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <span className={`badge ${v.status}`} style={{ position: "static" }}>{v.status === "available" ? "Available" : v.status === "sold" ? "Sold" : "Reserved"}</span>
                <span className="eyebrow muted">{v.bodyType} · {v.era}</span>
              </div>
              <h1 className="display">{v.year} {v.make}<br/>{v.model}</h1>
              <p className="deck">{v.sub}</p>
            </div>

            <div className="specs">
              <Spec k="Designed by" v={v.designer} />
              <Spec k="Body" v={v.bodyType} />
              <Spec k="Exterior" v={v.colorExt} />
              <Spec k="Interior" v={v.colorInt} />
              <Spec k="Mileage" v={v.mileage} />
              <Spec k="Transmission" v={v.transmission} />
              <Spec k="Location" v={v.location} alone />
            </div>

            <div className="provenance">
              {v.provenance.map((para, i) => (
                <p key={i} className={i === 0 ? "dropcap" : ""}>{para}</p>
              ))}
            </div>

            {/* Gallery */}
            <div className="gallery">
              {v.images.slice(0, 5).map((src, i) => (
                <div key={i} className="g-item" onClick={() => setLbIdx(i)}>
                  <img src={src} alt={`${v.make} ${v.model} #${i + 1}`} loading="lazy" />
                </div>
              ))}
            </div>

            {/* Honesty footer */}
            <div style={{ marginTop: 60, padding: "32px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
              <div className="eyebrow muted" style={{ marginBottom: 12 }}>Our honesty policy</div>
              <p className="italic-serif" style={{ fontSize: 22, color: "var(--ink2)", maxWidth: "60ch", margin: 0 }}>
                Every car is inspected in-house — from measuring paint thickness to a comprehensive test drive.
                If we know something about this car you should know, it's already in the description above.
              </p>
            </div>
          </div>

          {/* RIGHT — sticky panel */}
          <aside>
            <div className="enquire-panel">
              <div className="price-row">
                <span className="p">{v.status === "sold" ? "Sold" : "POA"}</span>
                <span className="poa-note">{v.status === "sold" ? "Archive" : "Price on enquiry, USD"}</span>
              </div>
              <div className="actions">
                <button className="btn btn-solid" disabled={v.status === "sold"} onClick={() => openEnquire({ kind: "vehicle", vehicle: v, defaultTab: "enquire" })}>
                  <span className="label">Enquire about this car</span>
                </button>
                <button className="btn btn-light" disabled={v.status === "sold"} onClick={() => openEnquire({ kind: "vehicle", vehicle: v, defaultTab: "details" })}>
                  <span className="label">Request details & condition report</span>
                </button>
                <button className="btn btn-light" disabled={v.status === "sold"} onClick={() => openEnquire({ kind: "vehicle", vehicle: v, defaultTab: "viewing" })}>
                  <span className="label">Book a viewing</span>
                </button>
                {whatsappOn && (
                  <button className="btn btn-light" disabled={v.status === "sold"} onClick={() => alert("WhatsApp deep-link — once client number is supplied")}>
                    <span className="label">WhatsApp</span>
                  </button>
                )}
              </div>
              <p className="secondary">
                We answer in person — usually within one business day. Multilingual team:
                English, Spanish, Italian, French, Catalan, Urdu, Tagalog.
              </p>
              <div className="contact-line">
                <a href="tel:+97143062032">+971 4 306 2032</a>
                <a href="mailto:contact@tominiclassics.com">contact@tominiclassics.com</a>
              </div>
            </div>
          </aside>
        </div>
      </section>

      {/* You may also like */}
      <section className="section" style={{ background: "var(--stone)" }}>
        <div className="shell">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 56, flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow" style={{ opacity: 0.55 }}>You may also like</div>
              <h2 className="display" style={{ marginTop: 14 }}>From the same gallery floor.</h2>
            </div>
            <button className="btn-link" onClick={() => navigate("collection")}>Browse all →</button>
          </div>
          <div className="v-grid">
            {youMayLike.map(x => <VehicleCard key={x.id} v={x} navigate={navigate} />)}
          </div>
        </div>
      </section>

      {/* Lightbox */}
      {lbIdx !== null && (
        <div className="lightbox" onClick={() => setLbIdx(null)}>
          <img className="lb-img" src={v.images[lbIdx]} onClick={e => e.stopPropagation()} alt="" />
          <button className="lb-close" onClick={() => setLbIdx(null)}>✕</button>
          {v.images.length > 1 && (
            <Fragment>
              <button className="lb-prev" onClick={e => { e.stopPropagation(); setLbIdx((lbIdx - 1 + v.images.length) % v.images.length); }}>‹</button>
              <button className="lb-next" onClick={e => { e.stopPropagation(); setLbIdx((lbIdx + 1) % v.images.length); }}>›</button>
              <div className="lb-counter">{lbIdx + 1} / {v.images.length}</div>
            </Fragment>
          )}
        </div>
      )}
    </div>
  );
}

function Spec({ k, v, alone }) {
  return (
    <div className={`row ${alone ? "alone" : ""}`}>
      <span className="k">{k}</span>
      <span className="v">{v}</span>
    </div>
  );
}

Object.assign(window, { Home, Collection, VehicleDetail });
