/* global React, VEHICLES, BRANDS, BODY_TYPES */
const { useState: useState1, useEffect: useEffect1, useMemo: useMemo1, useRef: useRef1 } = React;

/* ============================================================
   HOME
   ============================================================ */
const HOME_HERO = [
  { id: "pagani-huayra-bc-roadster", title: ["Pagani Huayra", "Roadster BC"], note: "1 of 40 worldwide · Just arrived" },
  { id: "koenigsegg-jesko-attack",   title: ["Koenigsegg", "Jesko Attack"],   note: "Track-spec aero · 1,600 HP" },
  { id: "bugatti-chiron-sport",      title: ["Bugatti Chiron", "Pur Sport"],  note: "Glacier White · 1,500 HP" },
  { id: "mclaren-p1-gtr",            title: ["McLaren", "P1 GTR"],            note: "Road-converted hypercar" },
];

const HomeScreen = ({ navigate, onEnquire, openVehicle }) => {
  const [slide, setSlide] = useState1(0);
  useEffect1(() => {
    const t = setInterval(() => setSlide(s => (s + 1) % HOME_HERO.length), 6500);
    return () => clearInterval(t);
  }, []);
  const cur = HOME_HERO[slide];
  const curVehicle = VEHICLES.find(v => v.id === cur.id);
  const featured = useMemo1(() => VEHICLES.filter(v => v.condition === "new").slice(0, 6), []);
  const services = [
    { num: "01", title: "Acquire from our showroom", body: "Always ~100 outstanding automobiles in stock — hypercars, supercars, GTs, classics and luxury SUVs. Every car is private-treaty.", link: "Browse inventory", to: "inventory" },
    { num: "02", title: "Sell us your car",          body: "Bring a high-end vehicle to a trusted home. Submit photos and details — receive a discreet valuation within one business day.", link: "Sell your car", to: "sell" },
    { num: "03", title: "Worldwide export",          body: "We arrange delivery to any port or airport worldwide — established export to GCC, Europe, the Russian-speaking market, and Greater China.", link: "Export enquiry", to: "export" },
  ];

  return (
    <div className="page" data-screen-label="Home">
      {/* Hero */}
      <section className="hero" data-screen-label="Hero">
        <div className="bg" style={{ backgroundImage: `url(${curVehicle.photo})` }}/>
        <div className="veil"/>
        <div className="hero-inner container-wide">
          <div className="hero-meta">
            <span>Dubai · U.A.E. · Since <b>1995</b></span>
            <span>Featured · <b>{cur.note}</b></span>
          </div>
          <div style={{flex: 1}} />
          <div className="eyebrow eyebrow-light" style={{marginBottom: 24}}>The world's most exclusive automobile showroom</div>
          <h1 className="display">
            Singular machines,<br/>
            sourced and delivered <span className="ital">worldwide.</span>
          </h1>
          <div className="hero-sub">
            <p>
              A private showroom of hypercars, supercars, classics and luxury saloons —
              acquired, traded and exported by Alain Class Motors from Dubai since 1995.
            </p>
            <div className="hero-actions">
              <button className="btn btn-gold" onClick={() => navigate("inventory")}>
                Browse inventory <Icon name="arrow" size={12} />
              </button>
              <button className="btn btn-ghost-light" onClick={() => openVehicle(curVehicle)}>
                View this car
              </button>
            </div>
          </div>
        </div>
        <div className="hero-slider-controls">
          <span className="tabular">{String(slide + 1).padStart(2,'0')} / {String(HOME_HERO.length).padStart(2,'0')}</span>
          <div className="hero-slider-dots">
            {HOME_HERO.map((_, i) => (
              <button key={i} className={i === slide ? "active" : ""} onClick={() => setSlide(i)} aria-label={"Slide " + (i+1)}/>
            ))}
          </div>
        </div>
      </section>

      {/* Top Gear accolade */}
      <section className="accolade" data-screen-label="Accolade">
        <div className="container">
          <div className="accolade-row">
            <span className="accolade-badge"><Icon name="plus" size={10}/> Press · cited media</span>
            <p className="accolade-quote">The best supercar dealership in the world.</p>
            <span className="accolade-attr">— BBC Top Gear<br/><span style={{color:"rgba(246,245,242,0.35)"}}>Attributed quote · topgear.com</span></span>
          </div>
        </div>
      </section>

      {/* Trust strip */}
      <section className="trust" data-screen-label="Trust strip">
        <div className="container">
          <div className="trust-row">
            <div className="trust-cell">
              <div className="n">31<span className="small">yrs</span></div>
              <div className="l">Since 1995 · Al Ain origin</div>
            </div>
            <div className="trust-cell">
              <div className="n">~100</div>
              <div className="l">Vehicles in stock at any time</div>
            </div>
            <div className="trust-cell">
              <div className="n">5</div>
              <div className="l">U.A.E. branches · ~32,500 sq ft</div>
            </div>
            <div className="trust-cell">
              <div className="n">∞</div>
              <div className="l">Worldwide import & export</div>
            </div>
          </div>
        </div>
      </section>

      {/* Featured inventory */}
      <section className="featured" data-screen-label="Featured inventory">
        <div className="container">
          <header className="section-head">
            <div>
              <div className="eyebrow">In the showroom</div>
              <h2 className="display">
                Recently <span className="ital">arrived.</span>
              </h2>
            </div>
            <div className="right">
              <span>Updated daily from the showroom feed</span>
              <button className="btn" onClick={() => navigate("inventory")}>View all <Icon name="arrow" size={12}/></button>
            </div>
          </header>
          <div className="featured-grid">
            {featured.map(v => (
              <VehicleCard key={v.id} v={v} onOpen={openVehicle}/>
            ))}
          </div>
        </div>
      </section>

      {/* Services teaser */}
      <section className="services" data-screen-label="Services teaser">
        <div className="container">
          <header className="section-head">
            <div>
              <div className="eyebrow eyebrow-light">Concierge</div>
              <h2 className="display" style={{color:"var(--paper)"}}>
                Three doors. <span className="ital">One concierge.</span>
              </h2>
            </div>
            <div className="right">
              <span>Each enquiry replies within one business hour</span>
            </div>
          </header>
        </div>
        <div className="container-wide">
          <div className="services-grid">
            {services.map(s => (
              <button key={s.num} className="svc-card" onClick={() => navigate(s.to)}>
                <div className="num">— {s.num}</div>
                <h3>{s.title}</h3>
                <p>{s.body}</p>
                <span className="link">{s.link} <Icon name="arrow" size={12}/></span>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Brand wall */}
      <section className="brandwall" data-screen-label="Brand wall">
        <div className="container">
          <header className="section-head">
            <div>
              <div className="eyebrow">Marques carried</div>
              <h2 className="display">A multi-marque <span className="ital">showroom.</span></h2>
            </div>
            <div className="right">
              <button className="btn" onClick={() => navigate("brands")}>All brands <Icon name="arrow" size={12}/></button>
            </div>
          </header>
          <div className="brand-grid">
            {BRANDS.slice(0, 16).map(b => (
              <button key={b} className="brand-cell" onClick={() => navigate("inventory")}>{b}</button>
            ))}
          </div>
          <p className="brand-disclaimer">
            Alain Class Motors is an independent multi-brand showroom and is not affiliated with, endorsed by, or sponsored by any of the manufacturers above. All marques are the property of their respective owners.
          </p>
        </div>
      </section>

      {/* Visit a branch */}
      <section className="visit" data-screen-label="Visit">
        <div className="bg" />
        <div className="veil" />
        <div className="container-wide">
          <div className="visit-inner">
            <div className="eyebrow eyebrow-light">Visit a showroom</div>
            <h2>
              Five U.A.E. addresses.<br/>
              <span className="ital">Private viewings on request.</span>
            </h2>
            <p>
              From the flagship on Sheikh Zayed Road to the heritage Al Ain showroom — every vehicle is on display in person. We're happy to arrange private viewings, after-hours appointments, or vehicle delivery to your home or hotel.
            </p>
            <div className="visit-row">
              <button className="btn btn-gold" onClick={() => navigate("contact")}>See all branches <Icon name="arrow" size={12}/></button>
              <button className="btn btn-ghost-light" onClick={() => onEnquire("enquire")}>Book a viewing</button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};
window.HomeScreen = HomeScreen;

/* ============================================================
   INVENTORY
   ============================================================ */
const InventoryScreen = ({ navigate, openVehicle }) => {
  const [brand, setBrand] = useState1("All");
  const [body, setBody] = useState1("All");
  const [cond, setCond] = useState1("All");
  const [sort, setSort] = useState1("featured");

  const filtered = useMemo1(() => {
    let arr = VEHICLES.slice();
    if (brand !== "All") arr = arr.filter(v => v.make === brand);
    if (body !== "All") arr = arr.filter(v => v.body === body);
    if (cond !== "All") arr = arr.filter(v => v.condition === cond);
    if (sort === "year-desc") arr.sort((a,b) => b.year - a.year);
    if (sort === "year-asc")  arr.sort((a,b) => a.year - b.year);
    if (sort === "make")      arr.sort((a,b) => a.make.localeCompare(b.make));
    return arr;
  }, [brand, body, cond, sort]);

  const bodyCounts = useMemo1(() => {
    const c = {};
    VEHICLES.forEach(v => { c[v.body] = (c[v.body] || 0) + 1; });
    return c;
  }, []);

  return (
    <div className="page" data-screen-label="Inventory">
      <section className="inv-head">
        <div className="container">
          <div className="eyebrow">Inventory · {VEHICLES.length} live</div>
          <h1>
            Vehicles in the <span className="ital">showroom.</span>
          </h1>
          <p>
            Demo seed only — production reads from the live DMS / Dubicars feed.
            All prices are <b>POA (price on application)</b>.
            Updated daily across five U.A.E. branches.
          </p>
        </div>
      </section>

      <div className="inv-toolbar">
        <div className="container inv-toolbar-inner">
          <div className="inv-filters">
            <button className={"chip " + (brand === "All" ? "active" : "")} onClick={() => setBrand("All")}>
              All brands <span className="ct">{VEHICLES.length}</span>
            </button>
            {[...new Set(VEHICLES.map(v => v.make))].sort().map(b => (
              <button key={b} className={"chip " + (brand === b ? "active" : "")} onClick={() => setBrand(b)}>
                {b}
              </button>
            ))}
          </div>
          <div className="inv-sort">
            <span>Sort</span>
            <select value={sort} onChange={e => setSort(e.target.value)}>
              <option value="featured">Featured</option>
              <option value="year-desc">Year — newest</option>
              <option value="year-asc">Year — oldest</option>
              <option value="make">Make A → Z</option>
            </select>
          </div>
        </div>
        <div className="container inv-toolbar-inner" style={{paddingTop: 12, borderTop: "1px solid var(--line-soft)"}}>
          <div className="inv-filters">
            <button className={"chip " + (body === "All" ? "active" : "")} onClick={() => setBody("All")}>All body types</button>
            {BODY_TYPES.map(t => (
              <button key={t.id} className={"chip " + (body === t.id ? "active" : "")} onClick={() => setBody(t.id)}>
                {t.label} <span className="ct">{bodyCounts[t.id] || 0}</span>
              </button>
            ))}
          </div>
          <div className="inv-filters">
            <button className={"chip " + (cond === "All" ? "active" : "")} onClick={() => setCond("All")}>All</button>
            <button className={"chip " + (cond === "new" ? "active" : "")} onClick={() => setCond("new")}>New</button>
            <button className={"chip " + (cond === "used" ? "active" : "")} onClick={() => setCond("used")}>Pre-owned</button>
          </div>
        </div>
      </div>

      <section className="inv-grid-wrap">
        <div className="container">
          <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom: 24, fontSize: 12, color: "var(--muted)", letterSpacing: "0.16em", textTransform: "uppercase"}}>
            <span>Showing <b className="tabular" style={{color:"var(--ink-light)"}}>{filtered.length}</b> of {VEHICLES.length}</span>
            <span>Prices on application · Watermarked photography</span>
          </div>
          {filtered.length === 0 ? (
            <div className="inv-empty">No vehicles match these filters. <br/><button className="btn" style={{marginTop:16}} onClick={() => { setBrand("All"); setBody("All"); setCond("All"); }}>Clear filters</button></div>
          ) : (
            <div className="inv-grid">
              {filtered.map(v => (
                <VehicleCard key={v.id} v={v} onOpen={openVehicle}/>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
};
window.InventoryScreen = InventoryScreen;
