// RMA Motors Dubai — interactive prototype
// Single-file React app. Mounts into #root.

const { useState, useEffect, useMemo, useRef, useCallback } = React;

// ─────────────────────────────────────────────────────────────────────────────
// Brand mark — RMA wordmark in SVG. Heavy italic forward-leaning grotesque.
// Modelled (originally drawn) after the brand's bold-italic mark seen in
// uploaded brand assets — NOT a trace, but evokes the same forward-thrust
// shape language used in the existing brand.

function RMAWordmark({ color = "currentColor", tagline = true, size = 1 }) {
  return (
    <svg viewBox="0 0 240 64" style={{ width: 240 * size, height: 64 * size }} aria-label="RMA Motors Dubai">
      <g fill={color} style={{ fontFamily: "'Archivo', sans-serif", fontWeight: 900, fontStyle: "italic" }}>
        <text x="0" y="34" fontSize="40" letterSpacing="-1.5">RMA</text>
        <text x="108" y="34" fontSize="22" fontWeight="500" fontStyle="normal" letterSpacing="3">MOTORS</text>
      </g>
      {tagline && (
        <g fill={color} opacity="0.55">
          <text x="108" y="52" fontSize="9" fontWeight="500" letterSpacing="6" style={{ fontFamily: "'Inter', sans-serif" }}>D U B A I</text>
        </g>
      )}
    </svg>
  );
}

// Motorsport stripe — three stripes echoing the brand's racing livery in the
// PPF and finance banners. Used as a visual accent rule.
function Stripe({ vertical = false, w = 120, h = 6, opacity = 1 }) {
  const isV = vertical;
  return (
    <svg width={isV ? h : w} height={isV ? w : h} style={{ opacity, display: "block" }}>
      {isV ? (
        <>
          <rect x="0" y="0" width={h / 3} height={w} fill="var(--rma-blue)" />
          <rect x={h / 3} y="0" width={h / 3} height={w} fill="white" />
          <rect x={(2 * h) / 3} y="0" width={h / 3} height={w} fill="var(--rma-red)" />
        </>
      ) : (
        <>
          <rect x="0" y="0" width={w} height={h / 3} fill="var(--rma-blue)" />
          <rect x="0" y={h / 3} width={w} height={h / 3} fill="white" />
          <rect x="0" y={(2 * h) / 3} width={w} height={h / 3} fill="var(--rma-red)" />
        </>
      )}
    </svg>
  );
}

// Stock chip / spec divider
function SpecPill({ children, kind = "default" }) {
  return <span className={`spec-pill spec-pill--${kind}`}>{children}</span>;
}

// ─────────────────────────────────────────────────────────────────────────────
// Sticky CTA FABs — WhatsApp + Call

function FABs({ onEnquire }) {
  return (
    <div className="fabs">
      <a className="fab fab--whatsapp" href="#" onClick={(e) => { e.preventDefault(); onEnquire({ channel: "whatsapp" }); }} aria-label="WhatsApp RMA Motors">
        <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.9 1-.2.2-.3.2-.6.1-.3-.2-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.4-.8-1.9-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.4 0 1.4 1 2.8 1.2 3 .1.2 2 3.1 4.9 4.3.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.5-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.4 1.3 4.9L2 22l5.2-1.3C8.6 21.6 10.2 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
        <span>WhatsApp</span>
      </a>
      <a className="fab fab--call" href={COPY.contact.mainHref} aria-label="Call RMA Motors">
        <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M6.6 10.8a15 15 0 006.6 6.6l2.2-2.2a1 1 0 011-.2 11 11 0 003.5.6 1 1 0 011 1V20a1 1 0 01-1 1A17 17 0 013 4a1 1 0 011-1h3.5a1 1 0 011 1 11 11 0 00.6 3.5 1 1 0 01-.2 1z"/></svg>
        <span>{COPY.contact.main}</span>
      </a>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Top navigation

function Nav({ view, navigate, locale, setLocale, onEnquire }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const groups = [
    { label: "Inventory", items: [
      { k: "inventory", label: "Used Cars" },
      { k: "inventory", label: "New" },
      { k: "inventory", label: "Trade-in" },
    ]},
    { label: "Services", items: [
      { k: "sell", label: "Sell" },
      { k: "finance", label: "Finance" },
      { k: "carcare", label: "Car Care" },
    ]},
    { label: "Company", items: [
      { k: "about", label: "About" },
      { k: "contact", label: "Contact" },
    ]},
  ];
  return (
    <header className={`nav ${scrolled ? "nav--scrolled" : ""}`}>
      <div className="nav__inner">
        <a className="nav__brand" href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "home" }); }}>
          <RMAWordmark size={0.85} />
        </a>
        <nav className="nav__links">
          {groups.map((g, gi) => (
            <div key={gi} className="nav__group">
              <span className="nav__group-label">{g.label}</span>
              <div className="nav__group-items">
                {g.items.map((l, i) => (
                  <a key={i} href="#" className={`nav__link ${view === l.k ? "is-active" : ""}`} onClick={(e) => { e.preventDefault(); navigate({ view: l.k }); }}>{l.label}</a>
                ))}
              </div>
            </div>
          ))}
        </nav>
        <div className="nav__actions">
          <div className="locale">
            {["EN", "AR", "RU", "ZH"].map((l) => (
              <button key={l} className={`locale__btn ${locale === l ? "is-active" : ""}`} onClick={() => setLocale(l)}>{l}</button>
            ))}
          </div>
          <button className="btn btn--ghost btn--sm" onClick={() => onEnquire({})}>Enquire</button>
          <a className="btn btn--solid btn--sm" href={COPY.contact.mainHref}>
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M6.6 10.8a15 15 0 006.6 6.6l2.2-2.2a1 1 0 011-.2 11 11 0 003.5.6 1 1 0 011 1V20a1 1 0 01-1 1A17 17 0 013 4a1 1 0 011-1h3.5a1 1 0 011 1 11 11 0 00.6 3.5 1 1 0 01-.2 1z"/></svg>
            <span>{COPY.contact.main}</span>
          </a>
        </div>
      </div>
      <Stripe w={9999} h={3} />
    </header>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Vehicle card

function VehicleCard({ v, onClick, dense = false }) {
  return (
    <article className={`vcard ${dense ? "vcard--dense" : ""}`} onClick={onClick}>
      <div className="vcard__media">
        <img src={v.image} alt={`${v.year} ${v.make} ${v.model}`} loading="lazy" />
        <div className="vcard__overlay">
          <div className="vcard__flags">
            {v.flags.map((f, i) => (<span key={i} className="vcard__flag">{f}</span>))}
          </div>
          <div className="vcard__id">{v.id}</div>
        </div>
      </div>
      <div className="vcard__body">
        <div className="vcard__row">
          <span className="vcard__year">{v.year}</span>
          <span className="vcard__tag">{v.tag}</span>
        </div>
        <h3 className="vcard__title">{v.make} <span>{v.model}</span></h3>
        <div className="vcard__specs">
          <span>{v.body}</span><i></i>
          <span>{v.transmission}</span><i></i>
          <span>{v.region} spec</span>
        </div>
        <div className="vcard__foot">
          <div className="vcard__price">
            <span className="vcard__price-label">Price</span>
            <span className="vcard__price-value">{v.price === "POA" ? "On application" : v.price}</span>
          </div>
          <span className="vcard__cta">View details →</span>
        </div>
      </div>
    </article>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// HOME VIEW

function HomeView({ navigate, onEnquire }) {
  const featured = useMemo(
    () => [VEHICLES[0], VEHICLES[1], VEHICLES[9], VEHICLES[10], VEHICLES[13], VEHICLES[6]],
    []
  );
  return (
    <main className="view view--home">
      {/* Hero */}
      <section className="hero">
        <div className="hero__media">
          <img src="media/home-hero-banner-5.webp" alt="" />
          <div className="hero__shade" />
          <div className="hero__grain" />
        </div>
        <div className="hero__inner">
          <div className="hero__eyebrow">
            <Stripe w={48} h={4} />
            <span>Prestige · Sports · Muscle · Classic</span>
          </div>
          <h1 className="hero__title">
            <span className="hero__title-it">The enthusiasts</span><br />
            empowering everyone<br />
            <span className="hero__title-line">to achieve their motoring</span><br />
            <span className="hero__title-em">dreams.</span>
          </h1>
          <p className="hero__sub">
            Dubai Investment Park · Speedex Center · est. by three generations of vehicle technicians.
          </p>
          <div className="hero__cta">
            <button className="btn btn--solid btn--lg" onClick={() => navigate({ view: "inventory" })}>
              Browse the showroom
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="square"/></svg>
            </button>
            <button className="btn btn--ghost btn--lg btn--ghost-light" onClick={() => onEnquire({ channel: "whatsapp" })}>
              Talk on WhatsApp
            </button>
          </div>
          <div className="hero__meta">
            <div><span className="hero__meta-k">Showroom</span><span className="hero__meta-v">Speedex Center, DIP 1</span></div>
            <div><span className="hero__meta-k">Stock</span><span className="hero__meta-v">Live feed — {VEHICLES.length} cars</span></div>
            <div><span className="hero__meta-k">Bookings</span><span className="hero__meta-v">Mon–Sat by appointment</span></div>
          </div>
        </div>
        <div className="hero__corner-mark"><RMAWordmark tagline={false} size={1.6} color="rgba(255,255,255,0.08)" /></div>
      </section>

      {/* Trust strip */}
      <section className="trust">
        <div className="trust__inner">
          <div className="trust__marquee">
            {[...COPY.trust, ...COPY.trust].map((t, i) => (
              <span key={i} className="trust__item">{t}<i className="trust__dot" /></span>
            ))}
          </div>
        </div>
      </section>

      {/* Featured grid */}
      <section className="featured">
        <div className="section__head">
          <div>
            <div className="section__eyebrow"><Stripe w={32} h={3} /><span>Featured / just-arrived</span></div>
            <h2 className="section__title">The current roster</h2>
          </div>
          <button className="section__more" onClick={() => navigate({ view: "inventory" })}>
            See all {VEHICLES.length} cars <span>→</span>
          </button>
        </div>
        <div className="featured__grid">
          {featured.map((v) => (
            <VehicleCard key={v.id} v={v} onClick={() => navigate({ view: "detail", id: v.id })} />
          ))}
        </div>
        <div className="featured__foot">
          <span className="mono">SAMPLE INVENTORY · BOUND TO LIVE GFORCES FEED IN PRODUCTION</span>
        </div>
      </section>

      {/* Services tiles */}
      <section className="services">
        <div className="services__head">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>What we do</span></div>
          <h2 className="section__title services__title">Four ways the showroom works.</h2>
        </div>
        <div className="services__grid">
          {COPY.services.map((s, i) => (
            <article key={s.key} className={`svc svc--${s.key}`}>
              <div className="svc__num">0{i + 1}</div>
              <h3 className="svc__title">{s.title}</h3>
              <p className="svc__body">{s.body}</p>
              <button className="svc__cta" onClick={() => s.key === "buy" ? navigate({ view: "inventory" }) : onEnquire({ topic: s.title })}>
                {s.cta} <span>→</span>
              </button>
            </article>
          ))}
        </div>
      </section>

      {/* Founder / story */}
      <section className="story">
        <div className="story__media">
          <img src="media/about-us-desktop-04.webp" alt="RMA Motors technicians" />
          <div className="story__media-caption mono">SPEEDEX CENTER · WORKSHOP FLOOR</div>
        </div>
        <div className="story__copy">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>Our story</span></div>
          <h2 className="story__title">Built on a workshop floor — not a sales floor.</h2>
          {COPY.about_long.map((p, i) => (
            <p key={i} className="story__p">{p}</p>
          ))}
          <div className="story__creds">
            <div><span className="mono">01</span> Three generations of vehicle technicians</div>
            <div><span className="mono">02</span> Ex-BMW &amp; Rolls-Royce UK senior technicians</div>
            <div><span className="mono">03</span> Ferrari · Bentley · Porsche · GCC specialists</div>
          </div>
          <button className="btn btn--outline btn--md" onClick={() => navigate({ view: "about" })}>Read the long version</button>
        </div>
      </section>

      {/* Car care band */}
      <section className="care">
        <div className="care__copy">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>RMA Car Care &amp; PPF</span></div>
          <h2 className="care__title">The same hands that prepare the showroom cars look after yours.</h2>
          <ul className="care__list">
            <li>Multi-stage polishing &amp; paint correction</li>
            <li>Paint-protection film &amp; ceramic coating</li>
            <li>Window tints, headlight &amp; alloy refurb</li>
          </ul>
          <button className="btn btn--solid btn--md btn--solid-red" onClick={() => onEnquire({ topic: "Car Care booking" })}>Book a service</button>
        </div>
        <div className="care__media">
          <img src="media/car-care-page.webp" alt="RMA PPF workshop" />
          <div className="care__media-tint" />
        </div>
      </section>

      {/* Reviews / Trustpilot placeholder */}
      <section className="reviews">
        <div className="reviews__inner">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>What customers say</span></div>
          <h2 className="section__title">Reviews live where they should — on Trustpilot.</h2>
          <p className="reviews__sub">
            Our review wall is the official Trustpilot widget — self-updating, unfiltered, owned by the
            customer not by us. The embed will load here in production.
          </p>
          <div className="reviews__placeholder">
            <div className="reviews__placeholder-inner">
              <span className="mono">TRUSTPILOT EMBED · LIVE WIDGET</span>
              <div className="reviews__stars">
                {[0,1,2,3,4].map(i => <span key={i}>★</span>)}
              </div>
              <span className="mono reviews__note">RATING + REVIEW COUNT BIND TO LIVE TRUSTPILOT FEED · NO FABRICATED NUMBERS</span>
            </div>
          </div>
        </div>
      </section>

      {/* Locations */}
      <section className="locs">
        <div className="section__head">
          <div>
            <div className="section__eyebrow"><Stripe w={32} h={3} /><span>Visit the showroom</span></div>
            <h2 className="section__title">Two units. One address.</h2>
          </div>
        </div>
        <div className="locs__grid">
          {COPY.locations.map((l, i) => (
            <div key={i} className="loc">
              <div className="loc__kind mono">{String(i+1).padStart(2,'0')} · {l.kind}</div>
              <h3 className="loc__name">{l.name}</h3>
              <p className="loc__addr">{l.addr}<br />{l.sub}</p>
              <div className="loc__phone"><a href={`tel:${l.phone.replace(/\s/g,'')}`}>{l.phone}</a></div>
            </div>
          ))}
          <div className="loc loc--map">
            <div className="loc__map-placeholder">
              <span className="mono">MAP · SPEEDEX CENTER · DIP 1</span>
              <span className="mono loc__map-note">COORDS TBC · SITE'S OWN COORDS LOOK PLACEHOLDER</span>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// INVENTORY VIEW

function InventoryView({ navigate }) {
  const [filters, setFilters] = useState({ make: "All", segment: "All", q: "", sort: "newest" });
  const filtered = useMemo(() => {
    let r = VEHICLES.slice();
    if (filters.make !== "All") r = r.filter((v) => v.make === filters.make);
    if (filters.segment !== "All") r = r.filter((v) => v.segment === filters.segment);
    if (filters.q) {
      const q = filters.q.toLowerCase();
      r = r.filter((v) => `${v.make} ${v.model} ${v.body}`.toLowerCase().includes(q));
    }
    if (filters.sort === "newest") r.sort((a, b) => b.year - a.year);
    if (filters.sort === "oldest") r.sort((a, b) => a.year - b.year);
    if (filters.sort === "az") r.sort((a, b) => a.make.localeCompare(b.make));
    return r;
  }, [filters]);

  return (
    <main className="view view--inventory">
      <div className="inv__head">
        <div className="inv__head-inner">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>Live inventory</span></div>
          <h1 className="inv__title">The showroom.</h1>
          <p className="inv__sub">
            Every car in stock today. Prices are quoted on application — collector-grade and consigned
            cars are individually appraised. Tap any car for the full spec, gallery and enquiry.
          </p>
        </div>
      </div>

      <div className="inv__toolbar">
        <div className="inv__toolbar-inner">
          <div className="inv__filters">
            <FilterGroup label="Make" value={filters.make} options={["All", ...MAKES]} onChange={(v) => setFilters((f) => ({ ...f, make: v }))} />
            <FilterGroup label="Segment" value={filters.segment} options={["All", ...SEGMENTS]} onChange={(v) => setFilters((f) => ({ ...f, segment: v }))} />
            <div className="filter filter--search">
              <label>Search</label>
              <input type="text" placeholder="model, body, year…" value={filters.q} onChange={(e) => setFilters((f) => ({ ...f, q: e.target.value }))} />
            </div>
            <div className="filter">
              <label>Sort</label>
              <select value={filters.sort} onChange={(e) => setFilters((f) => ({ ...f, sort: e.target.value }))}>
                <option value="newest">Newest first</option>
                <option value="oldest">Oldest first</option>
                <option value="az">Make A–Z</option>
              </select>
            </div>
          </div>
          <div className="inv__count">
            <span className="mono">{filtered.length}</span> <span>of {VEHICLES.length} in stock</span>
          </div>
        </div>
      </div>

      <div className="inv__grid">
        {filtered.map((v) => (
          <VehicleCard key={v.id} v={v} onClick={() => navigate({ view: "detail", id: v.id })} />
        ))}
        {filtered.length === 0 && (
          <div className="inv__empty">
            <p>No cars match those filters.</p>
            <button className="btn btn--outline btn--sm" onClick={() => setFilters({ make: "All", segment: "All", q: "", sort: "newest" })}>Clear filters</button>
          </div>
        )}
      </div>

      <div className="inv__foot">
        <span className="mono">SAMPLE INVENTORY · BINDS TO LIVE GFORCES FEED · SSG + ISR PER VEHICLE</span>
      </div>
    </main>
  );
}

function FilterGroup({ label, value, options, onChange }) {
  return (
    <div className="filter">
      <label>{label}</label>
      <select value={value} onChange={(e) => onChange(e.target.value)}>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// VEHICLE DETAIL VIEW

function DetailView({ id, navigate, onEnquire }) {
  const v = VEHICLES.find((x) => x.id === id) || VEHICLES[0];
  const similar = useMemo(() => VEHICLES.filter((x) => x.id !== v.id && (x.make === v.make || x.segment === v.segment)).slice(0, 3), [v]);
  const [galleryIdx, setGalleryIdx] = useState(0);
  // Simulate multi-angle gallery: use the hero + 3 zoom-crops styled differently
  const galleryShots = [
    { src: v.image, label: "FRONT 3/4" },
    { src: v.image, label: "PROFILE", style: { objectPosition: "left center", transform: "scale(1.1)" } },
    { src: v.image, label: "DETAIL", style: { objectPosition: "right center", transform: "scale(1.4)" } },
    { src: v.image, label: "STUDIO", style: { filter: "brightness(0.8) contrast(1.05)" } },
  ];

  const specs = [
    { k: "Year", v: v.year },
    { k: "Make", v: v.make },
    { k: "Model", v: v.model },
    { k: "Body", v: v.body },
    { k: "Segment", v: v.segment },
    { k: "Drivetrain", v: v.drivetrain },
    { k: "Transmission", v: v.transmission },
    { k: "Exterior", v: v.exterior },
    { k: "Interior", v: v.interior },
    { k: "Regional spec", v: v.region },
    { k: "Mileage", v: "On enquiry" },
    { k: "Stock ID", v: v.id },
  ];

  return (
    <main className="view view--detail">
      {/* Breadcrumb */}
      <div className="crumb">
        <a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "home" }); }}>Home</a>
        <span>/</span>
        <a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "inventory" }); }}>Used Cars</a>
        <span>/</span>
        <span className="crumb__current">{v.year} {v.make} {v.model}</span>
      </div>

      {/* Cinematic hero */}
      <section className="dh">
        <div className="dh__gallery">
          <div className="dh__main">
            <img src={galleryShots[galleryIdx].src} alt="" style={galleryShots[galleryIdx].style || {}} />
            <div className="dh__main-grain" />
            <div className="dh__main-overlay">
              <div className="dh__main-label mono">{galleryShots[galleryIdx].label}</div>
              <div className="dh__main-counter mono">{String(galleryIdx + 1).padStart(2, "0")} / {String(galleryShots.length).padStart(2, "0")}</div>
            </div>
            <button className="dh__nav dh__nav--prev" onClick={() => setGalleryIdx((i) => (i - 1 + galleryShots.length) % galleryShots.length)} aria-label="Previous"><span>←</span></button>
            <button className="dh__nav dh__nav--next" onClick={() => setGalleryIdx((i) => (i + 1) % galleryShots.length)} aria-label="Next"><span>→</span></button>
          </div>
          <div className="dh__thumbs">
            {galleryShots.map((s, i) => (
              <button key={i} className={`dh__thumb ${galleryIdx === i ? "is-active" : ""}`} onClick={() => setGalleryIdx(i)}>
                <img src={s.src} alt="" style={s.style || {}} />
                <span className="mono">{s.label}</span>
              </button>
            ))}
          </div>
        </div>

        <aside className="dh__panel">
          <div className="dh__flags">
            {v.flags.map((f, i) => <span key={i} className="dh__flag">{f}</span>)}
            <span className="dh__flag dh__flag--id mono">{v.id}</span>
          </div>
          <div className="dh__year mono">{v.year}</div>
          <h1 className="dh__title"><span>{v.make}</span><br />{v.model}</h1>
          <div className="dh__tags">
            <SpecPill>{v.body}</SpecPill>
            <SpecPill>{v.segment}</SpecPill>
            <SpecPill>{v.region} spec</SpecPill>
          </div>
          <div className="dh__price">
            <span className="dh__price-label mono">Price</span>
            <span className="dh__price-value">On application</span>
            <span className="dh__price-note">All cars are individually appraised. POA reflects either consignment terms or collector value.</span>
          </div>
          <div className="dh__cta">
            <button className="btn btn--solid btn--lg btn--block" onClick={() => onEnquire({ vehicle: v })}>
              Enquire / Request price
            </button>
            <div className="dh__cta-row">
              <button className="btn btn--outline btn--sm" onClick={() => onEnquire({ vehicle: v, topic: "Test drive" })}>Test drive</button>
              <button className="btn btn--outline btn--sm" onClick={() => onEnquire({ vehicle: v, topic: "Reserve" })}>Reserve</button>
            </div>
            <div className="dh__cta-row">
              <button className="btn btn--outline btn--sm" onClick={() => onEnquire({ vehicle: v, topic: "Trade-in" })}>Trade-in</button>
              <button className="btn btn--outline btn--sm" onClick={() => onEnquire({ vehicle: v, topic: "Finance" })}>Finance</button>
            </div>
            <a className="btn btn--ghost btn--sm btn--block" href="#" onClick={(e) => { e.preventDefault(); onEnquire({ vehicle: v, channel: "whatsapp" }); }}>
              <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.9 1-.2.2-.3.2-.6.1-.3-.2-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.4-.8-1.9-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.4 0 1.4 1 2.8 1.2 3 .1.2 2 3.1 4.9 4.3.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.5-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.4 1.3 4.9L2 22l5.2-1.3C8.6 21.6 10.2 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
              <span>Chat on WhatsApp</span>
            </a>
          </div>
        </aside>
      </section>

      {/* Spec table + story */}
      <section className="dspec">
        <div className="dspec__head">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>Specification</span></div>
          <h2 className="dspec__title">Every field is what the feed gives us — nothing invented.</h2>
        </div>
        <div className="dspec__grid">
          <div className="dspec__table">
            {specs.map((s, i) => (
              <div key={i} className="dspec__row">
                <span className="dspec__k mono">{s.k}</span>
                <span className="dspec__v">{s.v}</span>
              </div>
            ))}
          </div>
          <div className="dspec__notes">
            <h3>Preparation</h3>
            <p>
              Every car that enters Speedex Center is mechanically and cosmetically prepared by the same
              technicians who would sign off a factory delivery. Our ULTIMATE detail is applied as
              standard — multi-stage paint correction, full interior recommission and a roadworthiness
              report kept on file.
            </p>
            <h3>Provenance &amp; paperwork</h3>
            <p>
              Service history, regional spec confirmation and warranty status are walked through with
              you in person before any test drive. We do not list mileage publicly on collector and
              consignment cars — those figures are shared during enquiry.
            </p>
            <div className="dspec__note mono">
              ⚠ DEMO DATA · IN PRODUCTION SPECS BIND 1:1 TO LIVE GFORCES FEED FIELDS · POA SUPPORTED · NO INVENTED VALUES
            </div>
          </div>
        </div>
      </section>

      {/* Similar */}
      <section className="dsim">
        <div className="section__head">
          <div>
            <div className="section__eyebrow"><Stripe w={32} h={3} /><span>You may also consider</span></div>
            <h2 className="section__title">Similar cars in the showroom.</h2>
          </div>
          <button className="section__more" onClick={() => navigate({ view: "inventory" })}>See all stock <span>→</span></button>
        </div>
        <div className="dsim__grid">
          {similar.map((s) => (
            <VehicleCard key={s.id} v={s} onClick={() => { navigate({ view: "detail", id: s.id }); window.scrollTo({ top: 0 }); }} />
          ))}
        </div>
      </section>
    </main>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// "Placeholder" pages — Sell / Finance / Car Care / About / Contact
// Just enough to give the nav real links without padding with filler.

function MiniView({ title, eyebrow, body, ctaLabel, onEnquire, image }) {
  return (
    <main className="view view--mini">
      <section className="mini">
        <div className="mini__copy">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>{eyebrow}</span></div>
          <h1 className="mini__title">{title}</h1>
          {body.map((p, i) => <p key={i} className="mini__p">{p}</p>)}
          <button className="btn btn--solid btn--md" onClick={() => onEnquire({ topic: eyebrow })}>{ctaLabel}</button>
        </div>
        <div className="mini__media">
          <img src={image} alt="" />
          <div className="mini__media-shade" />
        </div>
      </section>
    </main>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Enquiry modal

function EnquiryModal({ open, onClose, prefill }) {
  const [sent, setSent] = useState(false);
  const [form, setForm] = useState({ name: "", phone: "", email: "", msg: "" });
  useEffect(() => { if (open) { setSent(false); setForm({ name: "", phone: "", email: "", msg: "" }); } }, [open, prefill]);
  if (!open) return null;
  const veh = prefill?.vehicle;
  const topic = prefill?.topic || (veh ? `${veh.year} ${veh.make} ${veh.model}` : "General enquiry");
  const channel = prefill?.channel === "whatsapp" ? "WhatsApp" : "RMA Motors";
  return (
    <div className="modal" role="dialog" aria-modal="true" onClick={onClose}>
      <div className="modal__panel" onClick={(e) => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Close">×</button>
        <div className="modal__head">
          <div className="section__eyebrow"><Stripe w={32} h={3} /><span>{channel}</span></div>
          <h2 className="modal__title">{topic}</h2>
          {veh && (
            <div className="modal__veh">
              <img src={veh.image} alt="" />
              <div>
                <span className="mono">{veh.id}</span>
                <strong>{veh.year} {veh.make} {veh.model}</strong>
                <span>{veh.body} · {veh.transmission} · {veh.region} spec</span>
              </div>
            </div>
          )}
        </div>
        {!sent ? (
          <form className="modal__form" onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
            <label>Name<input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Your full name" /></label>
            <label>Phone<input required type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+971 …" /></label>
            <label>Email<input required type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@example.com" /></label>
            <label>Message<textarea rows="3" value={form.msg} onChange={(e) => setForm({ ...form, msg: e.target.value })} placeholder={veh ? `Interested in the ${veh.make} ${veh.model}…` : "How can we help?"} /></label>
            <div className="modal__foot">
              <span className="mono modal__foot-note">FORM POSTS TO CRM + WHATSAPP HANDOFF</span>
              <button type="submit" className="btn btn--solid btn--md">Send enquiry</button>
            </div>
          </form>
        ) : (
          <div className="modal__sent">
            <div className="modal__sent-tick">✓</div>
            <h3>Enquiry received.</h3>
            <p>A member of the sales team will be in touch on the number you provided. For anything urgent, our showroom line is <a href={COPY.contact.mainHref}>{COPY.contact.main}</a>.</p>
            <button className="btn btn--outline btn--sm" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Footer

function Footer({ navigate }) {
  return (
    <footer className="foot">
      <Stripe w={9999} h={3} />
      <div className="foot__inner">
        <div className="foot__brand">
          <RMAWordmark size={1.1} color="white" />
          <p className="foot__motto">{COPY.motto}</p>
          <div className="foot__contact">
            <a href={COPY.contact.mainHref}>{COPY.contact.main}</a>
            <span className="mono">EMAIL · TBC</span>
            <span className="mono">WHATSAPP · TBC</span>
          </div>
        </div>
        <div className="foot__cols">
          <div>
            <h4>Showroom</h4>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "inventory" }); }}>Used cars</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "inventory" }); }}>New cars</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "inventory" }); }}>Trade-in stock</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "inventory" }); }}>Previously sold</a></li>
            </ul>
          </div>
          <div>
            <h4>Services</h4>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "sell" }); }}>Sell your car</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "finance" }); }}>Finance</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "carcare" }); }}>RMA Car Care</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "carcare" }); }}>RMA PPF</a></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "about" }); }}>About</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); navigate({ view: "contact" }); }}>Contact</a></li>
              <li><a href="#">Reviews · Trustpilot</a></li>
              <li><a href="#">EN / AR / RU / ZH</a></li>
            </ul>
          </div>
          <div>
            <h4>Visit</h4>
            <p>Speedex Center<br />Dubai Investment Park 1<br />Dubai, UAE</p>
            <p className="mono foot__addr-note">SHOWROOM No.3 · CAR CARE No.2</p>
          </div>
        </div>
      </div>
      <div className="foot__base">
        <span className="mono">© RMA MOTORS · DUBAI</span>
        <span className="mono">DESIGN PROTOTYPE · NOT THE LIVE SITE</span>
        <span className="mono">RMAMOTORS.COM</span>
      </div>
    </footer>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Tweaks integration

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "racing",
  "density": "comfortable",
  "heroTreatment": "dark",
  "gridSize": "regular"
}/*EDITMODE-END*/;

function TweaksUI() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => {
    const root = document.documentElement;
    // accent palette
    const accents = {
      racing: { red: "#C8102E", blue: "#1B3A8F", primary: "#C8102E" },
      cobalt: { red: "#1B3A8F", blue: "#1B3A8F", primary: "#1B3A8F" },
      steel:  { red: "#8C95A0", blue: "#3A4049", primary: "#3A4049" },
      ember:  { red: "#E25822", blue: "#1B3A8F", primary: "#E25822" },
    };
    const a = accents[t.accent] || accents.racing;
    root.style.setProperty("--rma-red", a.red);
    root.style.setProperty("--rma-blue", a.blue);
    root.style.setProperty("--primary", a.primary);
    // density
    root.style.setProperty("--density", t.density === "tight" ? "0.85" : t.density === "loose" ? "1.15" : "1");
    // grid
    root.style.setProperty("--grid-min", t.gridSize === "large" ? "360px" : t.gridSize === "small" ? "240px" : "300px");
    // hero treatment
    root.dataset.heroTreatment = t.heroTreatment;
  }, [t]);
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Accent">
        <TweakRadio
          value={t.accent}
          onChange={(v) => setTweak("accent", v)}
          options={[
            { value: "racing", label: "Racing" },
            { value: "cobalt", label: "Cobalt" },
            { value: "steel",  label: "Steel" },
            { value: "ember",  label: "Ember" },
          ]}
        />
      </TweakSection>
      <TweakSection title="Density">
        <TweakRadio
          value={t.density}
          onChange={(v) => setTweak("density", v)}
          options={[
            { value: "tight", label: "Tight" },
            { value: "comfortable", label: "Comfortable" },
            { value: "loose", label: "Loose" },
          ]}
        />
      </TweakSection>
      <TweakSection title="Hero treatment">
        <TweakRadio
          value={t.heroTreatment}
          onChange={(v) => setTweak("heroTreatment", v)}
          options={[
            { value: "dark", label: "Dark cinematic" },
            { value: "light", label: "Light editorial" },
          ]}
        />
      </TweakSection>
      <TweakSection title="Card grid">
        <TweakRadio
          value={t.gridSize}
          onChange={(v) => setTweak("gridSize", v)}
          options={[
            { value: "small", label: "Dense" },
            { value: "regular", label: "Regular" },
            { value: "large", label: "Spacious" },
          ]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Root App

function App() {
  const [route, setRoute] = useState({ view: "home" });
  const [locale, setLocale] = useState("EN");
  const [enquiry, setEnquiry] = useState(null);

  const navigate = useCallback((r) => {
    setRoute(r);
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);
  const onEnquire = useCallback((prefill) => setEnquiry(prefill || {}), []);
  const closeEnquiry = useCallback(() => setEnquiry(null), []);

  useEffect(() => {
    document.documentElement.dir = locale === "AR" ? "rtl" : "ltr";
    document.documentElement.lang = locale.toLowerCase();
  }, [locale]);

  let body;
  switch (route.view) {
    case "inventory":
      body = <div data-screen-label="02 Inventory"><InventoryView navigate={navigate} /></div>;
      break;
    case "detail":
      body = <div data-screen-label="03 Vehicle Detail"><DetailView id={route.id} navigate={navigate} onEnquire={onEnquire} /></div>;
      break;
    case "sell":
      body = <div data-screen-label="04 Sell"><MiniView eyebrow="Sell · Trade-in · Consignment" title="The team that will sell the car gives the valuation." body={["Drop your car in, share photos and history, or let us collect. We'll appraise it honestly, against the market we actually sell into — not against an auction house's haircut.", "Consignment is available for collector and high-value cars where you want our showroom and our buyer pool, on agreed terms."]} ctaLabel="Request a valuation" image="media/about-us-desktop-02.webp" onEnquire={onEnquire} /></div>;
      break;
    case "finance":
      body = <div data-screen-label="05 Finance"><MiniView eyebrow="Finance · Auto loans" title="Flexible UAE finance, arranged in the showroom." body={["We work with UAE banking partners to structure finance around the car and the customer — terms and rates are quoted against the specific vehicle, not against a generic calculator.", "Bring a UAE driving licence copy and the basics — we handle the rest."]} ctaLabel="Enquire about finance" image="media/about-us-desktop-04.webp" onEnquire={onEnquire} /></div>;
      break;
    case "carcare":
      body = <div data-screen-label="06 Car Care"><MiniView eyebrow="RMA Car Care &amp; PPF" title="The workshop next door to the showroom." body={["Multi-stage polishing, paint correction, ceramic coating, paint-protection film and window tints — performed by the same technicians who prepare our showroom cars.", "PPF specifications, ceramic packages and tint warranties are quoted on the car. We'll show you the products before you commit to them."]} ctaLabel="Book a service" image="media/car-care-page.webp" onEnquire={onEnquire} /></div>;
      break;
    case "about":
      body = <div data-screen-label="07 About"><MiniView eyebrow="Our story" title="Three generations of vehicle technicians." body={COPY.about_long} ctaLabel="Get in touch" image="media/about-us-showroom.webp" onEnquire={onEnquire} /></div>;
      break;
    case "contact":
      body = <div data-screen-label="08 Contact"><MiniView eyebrow="Visit · Call · Message" title="Speedex Center, Dubai Investment Park 1." body={[`Two units, one address. Sales is at Showroom No. 3 — RMA Car Care is at Showroom No. 2. Our main line is ${COPY.contact.main}.`, "WhatsApp, opening hours and a verified email address are still being confirmed with the client — they will be wired here before launch."]} ctaLabel="Send a message" image="media/about-us-showroom.webp" onEnquire={onEnquire} /></div>;
      break;
    default:
      body = <div data-screen-label="01 Home"><HomeView navigate={navigate} onEnquire={onEnquire} /></div>;
  }

  return (
    <div className="app" data-locale={locale}>
      <Nav view={route.view} navigate={navigate} locale={locale} setLocale={setLocale} onEnquire={onEnquire} />
      {body}
      <Footer navigate={navigate} />
      <FABs onEnquire={onEnquire} />
      <EnquiryModal open={!!enquiry} onClose={closeEnquiry} prefill={enquiry || {}} />
      <TweaksUI />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
