/* vehicle.jsx — cinematic vehicle detail page */

const { useState: useStateV, useEffect: useEffectV, useMemo: useMemoV } = React;

function Vehicle({ slug, onSelect, onEnquire, navigate }) {
  const v = useMemoV(() => INVENTORY.find((x) => x.slug === slug) || INVENTORY[0], [slug]);
  const [idx, setIdx] = useStateV(0);
  const [showSpecs, setShowSpecs] = useStateV(false);

  // Build a faux gallery from the available imagery + the vehicle's own
  const gallery = useMemoV(() => {
    return [
      { src: v.img, label: "Exterior · 3⁄4" },
      { src: "media/showroom-interior.webp", label: "On the floor" },
      { src: "media/hero-car-full.webp", label: "Profile" },
      { src: "media/showroom-building-night.webp", label: "Showroom" },
      { src: v.img, label: "Detail" },
    ];
  }, [v]);

  useEffectV(() => { setIdx(0); window.scrollTo({ top: 0 }); }, [slug]);

  useEffectV(() => {
    const f = (e) => {
      if (e.key === "ArrowRight") setIdx((i) => (i + 1) % gallery.length);
      if (e.key === "ArrowLeft") setIdx((i) => (i - 1 + gallery.length) % gallery.length);
    };
    window.addEventListener("keydown", f);
    return () => window.removeEventListener("keydown", f);
  }, [gallery.length]);

  const similar = useMemoV(() =>
    INVENTORY.filter((x) => x.slug !== v.slug && (x.brand === v.brand || x.body === v.body)).slice(0, 4),
    [v]);

  const specRows = useMemoV(() => {
    const s = v.spec || {};
    const order = [
      ["Year", v.year],
      ["Make", v.brand],
      ["Model", v.model],
      ["Body", v.body],
      ["Engine", s.engine],
      ["Power", s.power],
      ["Torque", s.torque],
      ["Drivetrain", s.drive],
      ["Transmission", s.trans],
      ["Exterior", s.exterior],
      ["Interior", s.interior],
      ["Mileage", s.mileage],
    ];
    // Only render the rows that have a value — brief: omit unknown fields, never fill them.
    return order.filter(([, val]) => val != null && val !== "—" && val !== "");
  }, [v]);

  return (
    <main>
      {/* ─── Top breadcrumb / title bar ─── */}
      <section style={{ paddingTop: 96, paddingBottom: 0, background: "var(--noir)" }}>
        <div className="wrap" style={{ paddingTop: 24 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--mute)", fontSize: 12, marginBottom: 24 }}>
            <button onClick={() => navigate({ page: "inventory" })} className="ul-link" style={{ background: "transparent", border: 0, color: "var(--silver)", padding: 0, cursor: "pointer", fontSize: 12 }}>← Back to inventory</button>
            <span style={{ color: "var(--line)" }}>·</span>
            <span className="mono" style={{ letterSpacing: "0.06em", textTransform: "uppercase" }}>{v.brand} / {v.model}</span>
          </div>

          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 24, marginBottom: 28 }}>
            <div>
              <div className="mono" style={{ fontSize: 11, color: "var(--mute)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 12 }}>
                {v.brand} · {v.body} · {v.tag}
              </div>
              <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 112px)", margin: 0, lineHeight: 0.92, letterSpacing: "-0.04em" }}>
                <span className="num" style={{ color: "var(--mute-dark)", fontSize: "0.55em", verticalAlign: "top" }}>{v.year}</span>{" "}
                {v.model}
              </h1>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 14px", borderRadius: 999, border: "1px solid " + (v.status === "available" ? "rgba(124,224,168,0.4)" : "rgba(225,29,42,0.4)") }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: v.status === "available" ? "#7CE0A8" : "var(--accent)" }} />
                <span className="mono" style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--silver)" }}>{v.status === "available" ? "Available · in showroom" : "Sold · recently"}</span>
              </span>
              <DemoBadge>Demo data</DemoBadge>
            </div>
          </div>
        </div>
      </section>

      {/* ─── Hero gallery ─── */}
      <section style={{ background: "var(--noir)", paddingBottom: 24 }}>
        <div className="wrap">
          <div className="veh-hero" style={{ borderRadius: 12, overflow: "hidden", position: "relative" }}>
            <img src={gallery[idx].src} alt={`${v.brand} ${v.model} ${gallery[idx].label}`} />
            {/* gradient bottom overlay */}
            <div style={{
              position: "absolute", inset: 0, pointerEvents: "none",
              background: "linear-gradient(180deg, transparent 60%, rgba(11,11,12,0.7) 100%)",
            }} />
            <div style={{
              position: "absolute", left: 24, bottom: 24, right: 24,
              display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16,
            }}>
              <div>
                <div className="mono" style={{ fontSize: 10, color: "var(--silver)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 6 }}>
                  Frame {String(idx + 1).padStart(2, "0")} / {String(gallery.length).padStart(2, "0")} · {gallery[idx].label}
                </div>
                <div style={{ fontSize: 13, color: "var(--paper)", opacity: 0.85 }}>← → to navigate</div>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button onClick={() => setIdx((i) => (i - 1 + gallery.length) % gallery.length)}
                  aria-label="Previous"
                  style={{ background: "rgba(11,11,12,0.7)", backdropFilter: "blur(8px)", border: "1px solid var(--line)", borderRadius: 999, width: 40, height: 40, color: "var(--paper)", cursor: "pointer" }}>←</button>
                <button onClick={() => setIdx((i) => (i + 1) % gallery.length)}
                  aria-label="Next"
                  style={{ background: "rgba(11,11,12,0.7)", backdropFilter: "blur(8px)", border: "1px solid var(--line)", borderRadius: 999, width: 40, height: 40, color: "var(--paper)", cursor: "pointer" }}>→</button>
              </div>
            </div>
          </div>

          <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: `repeat(${gallery.length}, 1fr)`, gap: 8 }}>
            {gallery.map((g, i) => (
              <button key={i} className={"thumb" + (i === idx ? " active" : "")}
                onClick={() => setIdx(i)}
                style={{ aspectRatio: "16/10", padding: 0, border: 0, background: "transparent", cursor: "pointer", borderRadius: 4, overflow: "hidden" }}>
                <img src={g.src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </button>
            ))}
          </div>

          {/* media pills row */}
          <div style={{ marginTop: 18, display: "flex", gap: 8, flexWrap: "wrap" }}>
            <button className="btn btn-ghost btn-sm">▶ Walk-around film</button>
            <button className="btn btn-ghost btn-sm">360° tour</button>
            <button className="btn btn-ghost btn-sm">Engine start</button>
            <button className="btn btn-ghost btn-sm">Provenance</button>
            <span className="mono" style={{ marginLeft: "auto", fontSize: 10, color: "var(--mute-dark)", letterSpacing: "0.1em", textTransform: "uppercase", alignSelf: "center" }}>
              Media slots — populated by feed
            </span>
          </div>
        </div>
      </section>

      {/* ─── Main grid: details + sticky enquiry ─── */}
      <section style={{ background: "var(--noir)", paddingBlock: 80 }}>
        <div className="wrap">
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 64, alignItems: "start" }}>

            {/* Left: prose + specs */}
            <div>
              <div className="kbd-eyebrow" style={{ marginBottom: 18 }}>About this car</div>
              <p className="display" style={{ fontSize: "clamp(22px, 2.2vw, 30px)", lineHeight: 1.3, letterSpacing: "-0.02em", margin: 0, fontWeight: 400, color: "var(--paper)", maxWidth: 720 }}>
                A clean, single-owner example of the {v.model.toLowerCase()}, in showroom condition and ready for inspection. Full service history is available on request — we'll walk you through provenance, configuration and options on the floor.
              </p>
              <p style={{ marginTop: 24, fontSize: 16, color: "var(--silver)", lineHeight: 1.6, maxWidth: 680 }}>
                Specification below reflects fields verified by our team. Any field that isn't shown is intentionally omitted until it is verified against the original build sheet — we don't fill blanks.
              </p>

              {/* spec block */}
              <div style={{ marginTop: 48 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 18 }}>
                  <div className="kbd-eyebrow">Specification</div>
                  <span className="mono" style={{ fontSize: 10, color: "var(--mute-dark)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{specRows.length} verified fields</span>
                </div>
                <div>
                  {specRows.map(([k, val]) => (
                    <div className="spec-row" key={k}>
                      <span className="k">{k}</span>
                      <span className="v">{val}</span>
                    </div>
                  ))}
                </div>
                <div style={{ marginTop: 16, padding: 16, border: "1px dashed var(--line)", borderRadius: 8, fontSize: 12, color: "var(--mute)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                  <span>Mileage, service history & build sheet shared on enquiry — privacy first.</span>
                  <button className="btn btn-ghost btn-xs" onClick={() => onEnquire({ intent: "enquire", vehicle: v })}>Request build sheet</button>
                </div>
              </div>

              {/* 360 tour placeholder */}
              <div style={{ marginTop: 56, padding: 32, border: "1px solid var(--line)", borderRadius: 12, background: "linear-gradient(180deg, var(--ink) 0%, var(--noir) 100%)", textAlign: "center" }}>
                <div className="kbd-eyebrow" style={{ marginBottom: 12 }}>360° interior tour</div>
                <div className="display" style={{ fontSize: 26, marginBottom: 8 }}>Step inside.</div>
                <div style={{ color: "var(--mute)", fontSize: 14, maxWidth: 440, marginInline: "auto" }}>
                  This slot embeds the existing 360 tour from f1rstmotors.com when wired to the feed.
                </div>
                <button className="btn btn-ghost btn-sm" style={{ marginTop: 18 }}>Launch tour</button>
              </div>
            </div>

            {/* Right: sticky enquiry */}
            <aside className="sticky-enquire">
              <div style={{ background: "var(--ink)", border: "1px solid var(--line)", borderRadius: 12, padding: 24 }}>
                <div className="kbd-eyebrow" style={{ marginBottom: 12 }}>Price</div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                  <div className="display" style={{ fontSize: 32 }}>Request price</div>
                  <span className="mono" style={{ fontSize: 10, color: "var(--mute)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Privately</span>
                </div>
                <p style={{ marginTop: 4, marginBottom: 20, color: "var(--mute)", fontSize: 13 }}>
                  Prices are shared privately. We respond within 4 working hours.
                </p>

                <div style={{ display: "grid", gap: 8 }}>
                  <button className="btn btn-primary" onClick={() => onEnquire({ intent: "price", vehicle: v })}>Request price</button>
                  <button className="btn btn-ghost" onClick={() => onEnquire({ intent: "viewing", vehicle: v })}>Book a private viewing</button>
                  <button className="btn btn-ghost" onClick={() => onEnquire({ intent: "tradein", vehicle: v })}>Offer trade-in for this</button>
                </div>

                <hr className="rule-soft" style={{ marginBlock: 20 }} />

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  <a className="btn btn-ghost btn-sm" href="tel:+97143201030">
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" style={{ marginInlineEnd: 6 }}><path d="M3 1c.5 0 .9.3 1 .8l.5 2c.1.4 0 .8-.3 1.1L3 6c.7 1.4 1.7 2.4 3 3l1-1.2c.3-.3.7-.4 1.1-.3l2 .5c.5.1.9.5.9 1V11c0 .6-.4 1-1 1A11 11 0 0 1 0 2c0-.6.4-1 1-1H3z"/></svg>
                    Call
                  </a>
                  <button className="btn btn-ghost btn-sm" title="Awaiting verified number" style={{ opacity: 0.45, cursor: "not-allowed" }} onClick={(e) => e.preventDefault()}>
                    WhatsApp · pending
                  </button>
                </div>

                <div className="mono" style={{ marginTop: 16, fontSize: 10, color: "var(--mute-dark)", lineHeight: 1.5, letterSpacing: "0.04em" }}>
                  Sheikh Zayed Rd · Open Sun–Thu/Sat 10:00–21:00 · Fri 14:00–21:00 · Today open
                </div>
              </div>

              {/* Specialist contact card */}
              <div style={{ marginTop: 16, padding: 20, background: "var(--ink)", border: "1px solid var(--line)", borderRadius: 12, display: "flex", gap: 14, alignItems: "center" }}>
                <div style={{ width: 48, height: 48, borderRadius: 99, background: "linear-gradient(135deg, var(--line) 0%, var(--ink-2) 100%)", display: "grid", placeItems: "center", color: "var(--silver)", fontFamily: "var(--mono)", fontSize: 13 }}>—</div>
                <div style={{ flex: 1 }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--mute)", letterSpacing: "0.12em", textTransform: "uppercase" }}>Your specialist</div>
                  <div style={{ fontSize: 14, color: "var(--silver)" }}>Assigned on enquiry</div>
                </div>
                <button className="btn btn-ghost btn-xs" onClick={() => onEnquire({ intent: "enquire", vehicle: v })}>Message</button>
              </div>
            </aside>
          </div>
        </div>
      </section>

      {/* ─── Similar cars ─── */}
      <section className="ink sec-pad-sm" style={{ borderTop: "1px solid var(--line)" }}>
        <div className="wrap">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 28, flexWrap: "wrap", gap: 16 }}>
            <SectionHead eyebrow={`More from ${v.brand}`} title="You might also consider." />
            <button className="btn btn-ghost btn-sm" onClick={() => navigate({ page: "inventory" })}>See all inventory →</button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
            {similar.map((s) => (
              <VehicleCard key={s.slug} vehicle={s} onSelect={onSelect} />
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { Vehicle });
