/* global React, VEHICLES, BRANCHES */
const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2 } = React;

/* ============================================================
   VEHICLE DETAIL — the flagship page
   ============================================================ */
const VehicleScreen = ({ vehicle, navigate, openVehicle, onEnquire }) => {
  const v = vehicle;
  const [imgIdx, setImgIdx] = useState2(0);
  useEffect2(() => { setImgIdx(0); window.scrollTo(0, 0); }, [v && v.id]);
  if (!v) return null;
  const gallery = v.gallery && v.gallery.length ? v.gallery : [v.photo];

  const similar = useMemo2(() =>
    VEHICLES.filter(x => x.id !== v.id && (x.make === v.make || x.body === v.body)).slice(0, 3),
    [v.id]
  );

  const specs = [
    ["Model Year", v.year],
    ["Mileage", v.mileage],
    ["Exterior", v.exterior],
    ["Interior", v.interior],
    ["Engine", v.engine],
    ["Power", v.power],
    ["Transmission", v.transmission],
    ["Stock ID", v.stockId],
  ];

  return (
    <div className="vd" data-screen-label="Vehicle Detail">
      <button className="vd-back" onClick={() => navigate("inventory")}>
        ← All inventory
      </button>

      {/* Cinematic gallery */}
      <section className="vd-gallery">
        <div className="main-img" style={{ backgroundImage: `url(${gallery[imgIdx]})` }}/>
        <div className="veil"/>
        <div className="overlay-info container-wide">
          <div className="meta">
            <span>{v.year} · {v.make}</span>
            <span>Stock <b>{v.stockId}</b></span>
            <span>{v.condition === "new" ? "New · 0 owners" : "Pre-owned · 1 owner"}</span>
            <span>Photo <b>{imgIdx + 1}/{gallery.length}</b></span>
          </div>
          <div className="thumbs">
            {gallery.map((g, i) => (
              <button key={i}
                className={i === imgIdx ? "active" : ""}
                style={{ backgroundImage: `url(${g})` }}
                onClick={() => setImgIdx(i)}
                aria-label={"View photo " + (i+1)}/>
            ))}
          </div>
        </div>
      </section>

      {/* Title block */}
      <section className="vd-title">
        <div className="container vd-title-inner">
          <div>
            <div className="eyebrow eyebrow-light">{v.year} · {v.make}</div>
            <h1>{v.model.split(" ")[0]} <span className="ital">{v.model.split(" ").slice(1).join(" ") || v.subtitle.split(" ")[0]}</span></h1>
            <p className="summary" style={{marginTop: 24}}>
              {v.subtitle}. {v.engine}, {v.power}. Finished in {v.exterior} over {v.interior}.
              On display at the Main Branch — Sheikh Zayed Road, Dubai. Worldwide delivery on request.
            </p>
          </div>
          <div>
            <div className="poa-block">
              <span className="label">Price</span>
              <span className="val">Price on application</span>
              <span className="hint">Discreet enquiry · CRM-handled · WhatsApp on supply</span>
            </div>
          </div>
        </div>
      </section>

      {/* CTA cluster */}
      <section className="vd-cta">
        <div className="container vd-cta-inner">
          <button className="vd-cta-btn primary" onClick={() => onEnquire("price", v)}>
            <Icon name="mail" size={14}/> Request price
          </button>
          <button className="vd-cta-btn wa" onClick={() => onEnquire("whatsapp", v)}>
            <Icon name="whatsapp" size={14}/> WhatsApp
          </button>
          <button className="vd-cta-btn" onClick={() => onEnquire("export", v)}>
            <Icon name="ship" size={14}/> Export this car
          </button>
          <button className="vd-cta-btn" onClick={() => onEnquire("sell", v)}>
            <Icon name="sell" size={14}/> Trade-in
          </button>
          <a className="vd-cta-btn" href="tel:+97143782222">
            <Icon name="phone" size={14}/> +971 4 378 2222
          </a>
        </div>
      </section>

      {/* Spec table */}
      <section className="vd-specs">
        <div className="container vd-specs-inner">
          <div className="col-l">
            <div className="eyebrow">Technical details</div>
            <h3>The <span className="ital">specification.</span></h3>
            <p>Every field below is drawn directly from the showroom feed — model year, mileage, exterior and interior trim, engine, peak power, transmission and stock ID. No invented specifications.</p>
            <p>If you would like the complete service history, original window sticker, or build-sheet, the concierge will share it on request.</p>
            <div className="legacy-note">
              <Icon name="plus" size={10}/> Live feed · revalidates every 60s
            </div>
          </div>
          <div className="spec-table">
            {specs.map(([k, val]) => (
              <div key={k} className="spec-row">
                <div className="spec-key">{k}</div>
                <div className="spec-val">{val}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Description */}
      <section className="vd-description">
        <div className="container vd-description-inner">
          <div>
            <div className="eyebrow">Description</div>
            <h3>From the <span className="ital">concierge.</span></h3>
          </div>
          <div className="body">
            <p>
              A {v.subtitle.toLowerCase()} {v.model} in our care at the Dubai flagship — presented in {v.exterior} over a {v.interior} cabin. The car has been prepared to Alain Class standards and is ready for collection or private viewing by appointment.
            </p>
            <div className="pull">
              "A car of this calibre asks for the right setting. We can arrange a private viewing at any of our five branches — or, if you prefer, at your residence or hotel."
            </div>
            <p>
              First-owner provenance with full documentation, original tool-kit, factory accessories and service history available on request. The vehicle is in stock and ready for delivery within the U.A.E., or for worldwide export with full documentation handled by our team.
            </p>
            <p>
              For private collectors abroad, our export team arranges shipping to any port or airport worldwide — established corridors include the GCC, Europe, the Russian-speaking market and Greater China.
            </p>
            <div style={{display:"flex", gap:10, marginTop:32, flexWrap:"wrap"}}>
              <button className="btn btn-primary" onClick={() => onEnquire("price", v)}>Request price <Icon name="arrow" size={12}/></button>
              <button className="btn" onClick={() => onEnquire("enquire", v)}>Schedule viewing</button>
            </div>
          </div>
        </div>
      </section>

      {/* Similar */}
      <section className="vd-similar">
        <div className="container">
          <header className="section-head">
            <div>
              <div className="eyebrow">Continue browsing</div>
              <h2 className="display">You may also <span className="ital">be interested.</span></h2>
            </div>
            <button className="btn" onClick={() => navigate("inventory")}>All inventory <Icon name="arrow" size={12}/></button>
          </header>
          <div className="featured-grid">
            {similar.map(s => (
              <VehicleCard key={s.id} v={s} onOpen={openVehicle}/>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
};
window.VehicleScreen = VehicleScreen;

/* ============================================================
   SELL YOUR CAR
   ============================================================ */
const SellScreen = ({ navigate, onEnquire }) => {
  const [form, setForm] = useState2({
    name: "", phone: "", email: "",
    brand: "", model: "", year: "", mileage: "", price: "", notes: ""
  });
  const [sent, setSent] = useState2(false);
  const submit = (e) => { e.preventDefault(); setSent(true); window.scrollTo({top: 0, behavior: "smooth"}); };

  return (
    <div className="page" data-screen-label="Sell your car">
      <section className="page-head">
        <div className="container">
          <div className="eyebrow eyebrow-light">Sell your car · Trade-in</div>
          <h1>Bring your car<br/>to a <span className="ital">trusted home.</span></h1>
          <p>
            We acquire high-end vehicles privately from collectors and individuals. Submit a few photos and details — receive a discreet valuation from our buyer within one business day. Confidentiality assured.
          </p>
        </div>
      </section>
      <section className="form-page">
        <div className="container form-page-inner">
          <div className="narrative">
            <div className="eyebrow">How it works</div>
            <h3>Three steps from<br/>enquiry to <span className="ital">settlement.</span></h3>
            <p>Each enquiry is handled by a single dedicated buyer — no auctions, no anonymous platforms, no fees. We pay in cleared U.A.E. dirhams, and we handle the transfer paperwork at our showroom.</p>
            <div className="steps">
              <div className="step">
                <div className="num">01</div>
                <div>
                  <h4>Submit</h4>
                  <p>Share make, model, year, mileage and a few photos. The form takes under three minutes.</p>
                </div>
              </div>
              <div className="step">
                <div className="num">02</div>
                <div>
                  <h4>Valuation</h4>
                  <p>A buyer responds within one business day with an indicative figure and any clarifying questions.</p>
                </div>
              </div>
              <div className="step">
                <div className="num">03</div>
                <div>
                  <h4>Inspect & settle</h4>
                  <p>Bring the car to any branch for a brief in-person inspection. We settle the same day; ownership transfer is handled by us.</p>
                </div>
              </div>
            </div>
          </div>

          {sent ? (
            <div className="form-card" style={{textAlign:"center", padding:"80px 40px"}}>
              <div style={{width:56, height:56, border:"1px solid var(--champagne-deep)", borderRadius:"50%", display:"inline-flex", alignItems:"center", justifyContent:"center", color:"var(--champagne-deep)", fontFamily:"var(--display)", fontSize:30, marginBottom:20}}>✓</div>
              <h3>Valuation requested.</h3>
              <p style={{color:"var(--muted)"}}>One of our buyers will reply within one business day to <b>{form.email || "your email"}</b>.</p>
              <button className="btn btn-primary" style={{marginTop:24}} onClick={() => setSent(false)}>Submit another</button>
            </div>
          ) : (
            <form className="form-card" onSubmit={submit}>
              <h3>Tell us about your car.</h3>
              <p className="lede">All fields confidential. Photos accelerate valuation but are not required.</p>
              <div className="field-row">
                <div className="field"><label>Full name</label><input required value={form.name} onChange={e=>setForm({...form, name:e.target.value})}/></div>
                <div className="field"><label>Phone</label><input required value={form.phone} onChange={e=>setForm({...form, phone:e.target.value})}/></div>
              </div>
              <div className="field"><label>Email</label><input required type="email" value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></div>
              <div className="field-row">
                <div className="field"><label>Brand</label><input required placeholder="e.g. Ferrari" value={form.brand} onChange={e=>setForm({...form, brand:e.target.value})}/></div>
                <div className="field"><label>Model</label><input required placeholder="e.g. 488 Pista" value={form.model} onChange={e=>setForm({...form, model:e.target.value})}/></div>
              </div>
              <div className="field-row">
                <div className="field"><label>Year</label><input required type="number" placeholder="2021" value={form.year} onChange={e=>setForm({...form, year:e.target.value})}/></div>
                <div className="field"><label>Mileage</label><input required placeholder="e.g. 4,200 KM" value={form.mileage} onChange={e=>setForm({...form, mileage:e.target.value})}/></div>
              </div>
              <div className="field"><label>Asking price (optional)</label><input placeholder="AED — optional" value={form.price} onChange={e=>setForm({...form, price:e.target.value})}/></div>
              <div className="field"><label>Notes — condition, history, modifications</label><textarea rows={3} value={form.notes} onChange={e=>setForm({...form, notes:e.target.value})}/></div>
              <div className="field">
                <label>Photos</label>
                <div className="upload">+ Drop up to 12 photos here or click to upload</div>
              </div>
              <div style={{display:"flex", gap:10, marginTop:20, flexWrap:"wrap"}}>
                <button type="submit" className="btn btn-gold">Request valuation <Icon name="arrow" size={12}/></button>
                <a className="btn" href="tel:+97143782222"><Icon name="phone" size={12}/> Or call directly</a>
              </div>
            </form>
          )}
        </div>
      </section>
    </div>
  );
};
window.SellScreen = SellScreen;

/* ============================================================
   EXPORT
   ============================================================ */
const ExportScreen = ({ navigate, onEnquire }) => {
  const [form, setForm] = useState2({
    name: "", phone: "", email: "",
    country: "", destPort: "",
    interest: "", message: ""
  });
  const [sent, setSent] = useState2(false);
  const corridors = [
    { name: "Europe",        cities: "Geneva · Monaco · London · Frankfurt" },
    { name: "Russian-speaking", cities: "Moscow · St Petersburg · Almaty" },
    { name: "Greater China", cities: "Hong Kong · Shanghai · Macau" },
    { name: "GCC",           cities: "Riyadh · Doha · Kuwait · Manama" },
  ];

  return (
    <div className="page" data-screen-label="Export">
      <section className="page-head">
        <div className="container">
          <div className="eyebrow eyebrow-light">Worldwide export</div>
          <h1>To any port,<br/>any <span className="ital">airport.</span></h1>
          <p>
            Alain Class Motors arranges worldwide delivery from Dubai — established corridors to Europe, the Russian-speaking market, Greater China and the wider GCC. Handled door-to-door by our logistics team, with all paperwork prepared in advance.
          </p>
        </div>
      </section>

      <section className="form-page">
        <div className="container form-page-inner">
          <div className="narrative">
            <div className="eyebrow">Active corridors</div>
            <h3>From Dubai, <span className="ital">everywhere.</span></h3>
            <p>Each corridor is operated by a dedicated logistics partner with rolling reservation capacity. RoRo, air-freight and enclosed-container options available depending on car and destination.</p>
            <div className="steps" style={{marginTop:32}}>
              {corridors.map(c => (
                <div className="step" key={c.name}>
                  <div className="num"><Icon name="ship" size={14}/></div>
                  <div>
                    <h4>{c.name}</h4>
                    <p>{c.cities}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {sent ? (
            <div className="form-card" style={{textAlign:"center", padding:"80px 40px"}}>
              <div style={{width:56, height:56, border:"1px solid var(--champagne-deep)", borderRadius:"50%", display:"inline-flex", alignItems:"center", justifyContent:"center", color:"var(--champagne-deep)", fontFamily:"var(--display)", fontSize:30, marginBottom:20}}>✓</div>
              <h3>Export enquiry received.</h3>
              <p style={{color:"var(--muted)"}}>Our export team will reply within one business hour with a quote and timeline for <b>{form.destPort || form.country}</b>.</p>
              <button className="btn btn-primary" style={{marginTop:24}} onClick={() => setSent(false)}>Submit another</button>
            </div>
          ) : (
            <form className="form-card" onSubmit={e => { e.preventDefault(); setSent(true); window.scrollTo({top:0, behavior:"smooth"});}}>
              <h3>International purchase enquiry.</h3>
              <p className="lede">Available in English, العربية, Русский and 中文 — your enquiry will be routed to a corridor specialist.</p>
              <div className="field-row">
                <div className="field"><label>Full name</label><input required value={form.name} onChange={e=>setForm({...form, name:e.target.value})}/></div>
                <div className="field"><label>Phone</label><input required value={form.phone} onChange={e=>setForm({...form, phone:e.target.value})}/></div>
              </div>
              <div className="field"><label>Email</label><input required type="email" value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></div>
              <div className="field-row">
                <div className="field"><label>Country of residence</label><input required value={form.country} onChange={e=>setForm({...form, country:e.target.value})}/></div>
                <div className="field"><label>Destination port / airport</label><input placeholder="e.g. Geneva, Hong Kong" value={form.destPort} onChange={e=>setForm({...form, destPort:e.target.value})}/></div>
              </div>
              <div className="field"><label>Car(s) of interest</label><input required placeholder="Make / model / stock ID if known" value={form.interest} onChange={e=>setForm({...form, interest:e.target.value})}/></div>
              <div className="field"><label>Message</label><textarea rows={3} value={form.message} onChange={e=>setForm({...form, message:e.target.value})}/></div>
              <div style={{display:"flex", gap:10, marginTop:20, flexWrap:"wrap"}}>
                <button type="submit" className="btn btn-gold">Send export enquiry <Icon name="arrow" size={12}/></button>
                <button type="button" className="btn" onClick={() => navigate("inventory")}>Browse inventory first</button>
              </div>
            </form>
          )}
        </div>
      </section>
    </div>
  );
};
window.ExportScreen = ExportScreen;

/* ============================================================
   ABOUT
   ============================================================ */
const AboutScreen = ({ navigate, onEnquire }) => {
  return (
    <div className="page" data-screen-label="About">
      <section className="page-head">
        <div className="container">
          <div className="eyebrow eyebrow-light">The house</div>
          <h1>Since 1995,<br/>from <span className="ital">Al Ain.</span></h1>
          <p>
            Founded by Mr. Abdulla Al Ketbi — a car enthusiast and collector — Alain Class Motors began trading luxury cars in 1992 and opened the first showroom in Al Ain in 1995. Today the house operates five branches across the United Arab Emirates, with the Dubai flagship on Sheikh Zayed Road.
          </p>
        </div>
      </section>

      <section className="heritage">
        <div className="container heritage-grid">
          <div className="img-block" style={{backgroundImage:"url(media/showroom.webp)"}}/>
          <div>
            <div className="eyebrow">Founder · Abdulla Al Ketbi</div>
            <h3 style={{fontFamily:"var(--display)", fontWeight:400, fontSize:"clamp(32px,4vw,52px)", lineHeight:1.05, letterSpacing:"-0.01em", margin:"12px 0 24px"}}>
              "A passion for cars,<br/>turned into a <span style={{fontStyle:"italic", color:"var(--champagne-deep)"}}>house.</span>"
            </h3>
            <p style={{color:"var(--muted)", fontSize:15, lineHeight:1.75}}>
              The story began in 1992 when Mr. Al Ketbi started importing Mercedes-Benz cars from Germany and selling them privately to close relatives and friends. By 1995 the demand led to the opening of the first Alain Class showroom in Al Ain — and the brand name has carried the city's heritage ever since.
            </p>
            <p style={{color:"var(--muted)", fontSize:15, lineHeight:1.75, marginTop:16}}>
              Over thirty years on, the house carries always ~100 vehicles in stock across its five U.A.E. branches and is cited by BBC Top Gear as "the best supercar dealership in the world" — an attributable media quote we wear with quiet pride.
            </p>

            <div className="timeline">
              <div className="timeline-row">
                <div className="yr">1992</div>
                <div><h4>First imports</h4><p>Private trade begins — Mercedes-Benz cars sourced from Germany.</p></div>
              </div>
              <div className="timeline-row">
                <div className="yr">1995</div>
                <div><h4>The first showroom</h4><p>Alain Class Motors opens in Al Ain, U.A.E.</p></div>
              </div>
              <div className="timeline-row">
                <div className="yr">2000s</div>
                <div><h4>Dubai flagship</h4><p>The Sheikh Zayed Road branch opens; the business broadens into multi-marque hypercars and classics.</p></div>
              </div>
              <div className="timeline-row">
                <div className="yr">Today</div>
                <div><h4>Five branches · worldwide</h4><p>Five U.A.E. addresses, ~32,500 sq ft of showroom space, ~100 vehicles in stock, established export corridors to Europe, the Russian-speaking market, Greater China and the GCC.</p></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="visit">
        <div className="bg" />
        <div className="veil" />
        <div className="container-wide">
          <div className="visit-inner">
            <div className="eyebrow eyebrow-light">Visit</div>
            <h2>The showroom is open <span className="ital">for guests.</span></h2>
            <p>By appointment or by walk-in. Refreshments, paperwork concierge and full transfer of ownership handled in-house.</p>
            <div className="visit-row">
              <button className="btn btn-gold" onClick={() => navigate("contact")}>Find your nearest branch <Icon name="arrow" size={12}/></button>
              <button className="btn btn-ghost-light" onClick={() => onEnquire("enquire")}>Make an appointment</button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};
window.AboutScreen = AboutScreen;

/* ============================================================
   CONTACT — five branches
   ============================================================ */
const ContactScreen = ({ navigate, onEnquire }) => (
  <div className="page" data-screen-label="Contact">
    <section className="page-head">
      <div className="container">
        <div className="eyebrow eyebrow-light">Five branches · One hotline</div>
        <h1>Find <span className="ital">us.</span></h1>
        <p>
          Single hotline across every branch: <b>+971 4 378 2222</b>.
          Fax +971 4 379 0337 · <b>info@alainclass.com</b>.
          WhatsApp number to be enabled on client confirmation.
        </p>
        <div style={{display:"flex", gap:10, marginTop:32, flexWrap:"wrap"}}>
          <a className="btn btn-gold" href="tel:+97143782222"><Icon name="phone" size={12}/> +971 4 378 2222</a>
          <a className="btn btn-ghost-light" href="mailto:info@alainclass.com"><Icon name="mail" size={12}/> info@alainclass.com</a>
          <button className="btn btn-ghost-light" onClick={() => onEnquire("enquire")}><Icon name="whatsapp" size={12}/> WhatsApp (TBC)</button>
        </div>
      </div>
    </section>

    <section className="branches">
      <div className="container">
        <header className="section-head">
          <div>
            <div className="eyebrow">U.A.E. addresses</div>
            <h2 className="display">Five doors. <span className="ital">~32,500 sq ft.</span></h2>
          </div>
          <div className="right">
            <span>Hours to be confirmed per branch</span>
          </div>
        </header>
        <div className="branches-grid">
          {BRANCHES.map(b => (
            <div key={b.name} className="branch-card">
              <div className="head">
                <div>
                  <div className="eyebrow" style={{marginBottom:6}}>
                    {b.flagship ? "Flagship" : "Branch"}
                  </div>
                  <h3>{b.name.replace("—", "—")}</h3>
                  <div style={{color:"var(--muted)", fontSize:13, marginTop:6}}>{b.sub}</div>
                </div>
                <span className="size">{b.size}</span>
              </div>
              <div className="addr">{b.addr}</div>
              <div className="map">
                <span className="pin">{b.coords || "Map coords TBC"}</span>
              </div>
              <div className="actions">
                <a className="btn btn-sm" href="tel:+97143782222"><Icon name="phone" size={11}/> Call</a>
                <button className="btn btn-sm" onClick={() => onEnquire("enquire")}><Icon name="pin" size={11}/> Book viewing</button>
                <button className="btn btn-sm" onClick={() => onEnquire("whatsapp")}><Icon name="whatsapp" size={11}/> WhatsApp</button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  </div>
);
window.ContactScreen = ContactScreen;

/* ============================================================
   BRANDS — simple list view
   ============================================================ */
const BrandsScreen = ({ navigate, openVehicle }) => {
  const byBrand = useMemo2(() => {
    const m = {};
    VEHICLES.forEach(v => { (m[v.make] = m[v.make] || []).push(v); });
    return m;
  }, []);
  const brands = Object.keys(byBrand).sort();
  return (
    <div className="page" data-screen-label="Brands">
      <section className="page-head">
        <div className="container">
          <div className="eyebrow eyebrow-light">Marques carried</div>
          <h1>The <span className="ital">house</span> floor.</h1>
          <p>Alain Class Motors is an independent multi-brand showroom. The marques below are those currently represented in our live inventory — the broader list of brands we trade in spans more than fifty makes.</p>
        </div>
      </section>
      <section style={{padding:"var(--section) 0", background:"var(--paper)"}}>
        <div className="container">
          {brands.map(b => (
            <div key={b} style={{marginBottom: 64, borderTop:"1px solid var(--line)", paddingTop: 32}}>
              <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom: 24}}>
                <h2 style={{fontFamily:"var(--display)", fontWeight:400, fontSize:"clamp(32px, 4vw, 56px)", margin:0, letterSpacing:"-0.01em"}}>{b}</h2>
                <span className="eyebrow">{byBrand[b].length} {byBrand[b].length === 1 ? "vehicle" : "vehicles"}</span>
              </div>
              <div className="featured-grid">
                {byBrand[b].slice(0, 3).map(v => (
                  <VehicleCard key={v.id} v={v} onOpen={openVehicle}/>
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};
window.BrandsScreen = BrandsScreen;
