/* Superior Car Rental — Fleet listing + Car detail screens */

/* =========================
   FLEET LISTING
   ========================= */
const FleetScreen = ({ navigate, initialCat = "all" }) => {
  const [cat, setCat] = useState(initialCat);
  const [brand, setBrand] = useState("all");
  const [priceBand, setPriceBand] = useState("all");
  const [sort, setSort] = useState("featured");

  useEffect(() => { window.scrollTo(0, 0); }, []);

  const filtered = useMemo(() => {
    let arr = SCR_DATA.FLEET.slice();
    if (cat !== "all") arr = arr.filter(c => c.cat === cat);
    if (brand !== "all") arr = arr.filter(c => c.make === brand);
    if (priceBand !== "all") {
      const [lo, hi] = priceBand.split("-").map(Number);
      arr = arr.filter(c => c.fromRate >= lo && c.fromRate <= (hi||Infinity));
    }
    if (sort === "price-asc") arr.sort((a,b) => a.fromRate - b.fromRate);
    else if (sort === "price-desc") arr.sort((a,b) => b.fromRate - a.fromRate);
    else if (sort === "newest") arr.sort((a,b) => b.year - a.year);
    else arr.sort((a,b) => (b.featured?1:0) - (a.featured?1:0));
    return arr;
  }, [cat, brand, priceBand, sort]);

  return (
    <div className="section-noir" data-screen-label="fleet" style={{minHeight:"100vh"}}>
      {/* Page header */}
      <div style={{paddingTop:140,paddingBottom:48}}>
        <div className="shell-wide">
          <Eyebrow gold>The fleet</Eyebrow>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-end",gap:32,flexWrap:"wrap",marginTop:18}}>
            <h1 style={{fontSize:"clamp(48px,6vw,84px)"}}>
              <span style={{fontVariantNumeric:"tabular-nums"}}>{filtered.length}</span> cars,<br/>
              <span className="serif-it">ready to drive.</span>
            </h1>
            <div style={{maxWidth:420,color:"var(--muted-2)",fontSize:15,lineHeight:1.6}}>
              Filter by body, brand, or budget. Every car ships with free delivery in Dubai &amp; UAE. Rates shown are indicative — confirm at booking.
            </div>
          </div>
        </div>
      </div>

      {/* Filter bar */}
      <div className="shell-wide">
        <div className="filter-bar" style={{margin:0}}>
          {SCR_DATA.CATEGORIES.map(c => (
            <button key={c.id} className={`filter-chip ${cat===c.id?"on":""}`} onClick={() => setCat(c.id)}>
              {c.label}
            </button>
          ))}
          <div className="filter-spacer"/>
          <select className="filter-sort" value={brand} onChange={e => setBrand(e.target.value)}>
            <option value="all">All brands</option>
            {SCR_DATA.BRANDS.map(b => <option key={b} value={b}>{b}</option>)}
          </select>
          <select className="filter-sort" value={priceBand} onChange={e => setPriceBand(e.target.value)}>
            <option value="all">Any price</option>
            <option value="0-1000">Under AED 1,000/day</option>
            <option value="1000-2000">AED 1,000–2,000</option>
            <option value="2000-3500">AED 2,000–3,500</option>
            <option value="3500-99999">AED 3,500+</option>
          </select>
          <select className="filter-sort" value={sort} onChange={e => setSort(e.target.value)}>
            <option value="featured">Featured</option>
            <option value="newest">Newest</option>
            <option value="price-asc">Price ↑</option>
            <option value="price-desc">Price ↓</option>
          </select>
        </div>
      </div>

      {/* Grid */}
      <div className="shell-wide" style={{paddingTop:32,paddingBottom:120}}>
        {filtered.length === 0 ? (
          <div style={{padding:80,textAlign:"center",color:"var(--muted-2)"}}>
            No cars match your filters yet — try widening the brand or price.
          </div>
        ) : (
          <div className="fleet-grid">
            {filtered.map(c => (
              <CarCard key={c.id} car={c} onClick={() => navigate({name:"car", id: c.id})}/>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

/* =========================
   CAR DETAIL
   ========================= */
const CarDetailScreen = ({ navigate, carId, onReserve }) => {
  const car = useMemo(() => SCR_DATA.FLEET.find(c => c.id === carId), [carId]);
  const [pickupDate, setPickupDate] = useState(todayPlus(1));
  const [returnDate, setReturnDate] = useState(todayPlus(4));
  const [pickupLoc, setPickupLoc] = useState("dxb");
  const [fav, setFav] = useState(false);

  useEffect(() => { window.scrollTo(0, 0); }, [carId]);
  if (!car) return null;

  const days = Math.max(1, Math.round((new Date(returnDate) - new Date(pickupDate)) / 86400000));
  const subtotal = car.fromRate * days;
  const delivery = 0;
  const total = subtotal + delivery;

  const similar = SCR_DATA.FLEET.filter(c => c.cat === car.cat && c.id !== car.id).slice(0, 3);

  const reserveMsg = `Hi Superior Rental, I'd like to reserve the ${car.year} ${car.make} ${car.model}.\nPickup: ${fmtDate(pickupDate)} from ${SCR_DATA.PICKUP_LOCATIONS.find(p=>p.id===pickupLoc)?.label}\nReturn: ${fmtDate(returnDate)}\n(${days} days)`;

  return (
    <div data-screen-label={`car-${car.id}`}>
      {/* Hero image */}
      <div className="cd-hero">
        <div className="cd-hero-img">
          <img src={car.image} alt={`${car.make} ${car.model}`}/>
        </div>

        {/* Title block */}
        <div className="cd-titleblock">
          <div className="cd-title">
            <div className="cd-stockcode">
              <span className="cd-stockcode-line"></span>
              <span>{car.cat.toUpperCase()} · {car.body}</span>
              <span style={{color:"var(--accent)"}}>SCR-{car.id.slice(-4).toUpperCase()}</span>
              <button onClick={() => setFav(!fav)} style={{color: fav?"var(--accent)":"var(--muted-2)",display:"flex",alignItems:"center",gap:6}}>
                <Icon.Heart filled={fav} className="icon-sm"/> {fav?"Saved":"Save"}
              </button>
            </div>
            <div style={{display:"flex",alignItems:"baseline",gap:18,flexWrap:"wrap"}}>
              <h1>{car.make}</h1>
              <span className="mono" style={{color:"var(--muted-2)",fontSize:14,letterSpacing:"0.1em"}}>· {car.year}</span>
            </div>
            <h1 className="serif-it" style={{marginTop:4,color:"var(--accent)"}}>{car.model}</h1>
            <p style={{maxWidth:600,marginTop:28,fontSize:17,color:"var(--muted-2)",lineHeight:1.55}}>{car.blurb}</p>
            <div style={{display:"flex",gap:10,marginTop:32,flexWrap:"wrap"}}>
              <Button kind="primary" size="lg" onClick={() => onReserve({car, pickupDate, returnDate, pickupLoc})}>
                Reserve <Icon.Arrow/>
              </Button>
              <Button kind="whatsapp" size="lg" onClick={() => window.open(waLink(reserveMsg))}>
                <Icon.Whatsapp/> WhatsApp
              </Button>
              <Button kind="ghost" size="lg" onClick={() => window.open("tel:+971567671411")}>
                <Icon.Phone className="icon-sm"/> Call
              </Button>
            </div>
          </div>

          {/* Price card */}
          <div className="cd-price-block">
            <div className="cd-price-from">From — indicative</div>
            <div className="cd-price-row">
              <span className="cd-price-ccy">AED</span>
              <span className="cd-price-amt tabular">{SCR_DATA.formatAED(car.fromRate)}</span>
              <span className="cd-price-per">/ day</span>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginTop:18,padding:"16px 0",borderTop:"1px solid var(--line-2)"}}>
              <div>
                <div className="eyebrow">Deposit</div>
                <div style={{marginTop:4,fontFamily:"var(--font-mono)",fontSize:14}}>AED {SCR_DATA.formatAED(car.deposit)}</div>
              </div>
              <div>
                <div className="eyebrow">Mileage</div>
                <div style={{marginTop:4,fontFamily:"var(--font-mono)",fontSize:14}}>{car.mileageCap}</div>
              </div>
              <div>
                <div className="eyebrow">Min. rental</div>
                <div style={{marginTop:4,fontFamily:"var(--font-mono)",fontSize:14}}>{car.minDays} day</div>
              </div>
              <div>
                <div className="eyebrow">Delivery</div>
                <div style={{marginTop:4,fontFamily:"var(--font-mono)",fontSize:14,color:"var(--accent)"}}>Free in UAE</div>
              </div>
            </div>
            <div className="cd-price-note">
              Rates vary by season &amp; duration. Final quote at booking includes Salik, fuel deposit, and any add-ons (chauffeur, child seat, additional driver).
            </div>
          </div>
        </div>
      </div>

      {/* Body */}
      <div className="cd-body">
        {/* Left column */}
        <div>
          {/* Specs */}
          <div className="cd-section">
            <h3><span className="num">01</span>Specification</h3>
            <div className="spec-grid">
              <div className="spec-row"><span className="k">Engine</span><span className="v">{car.engine}</span></div>
              <div className="spec-row"><span className="k">Power</span><span className="v">{car.power}</span></div>
              <div className="spec-row"><span className="k">0–100 km/h</span><span className="v">{car.zeroTo}</span></div>
              <div className="spec-row"><span className="k">Top speed</span><span className="v">{car.topSpeed}</span></div>
              <div className="spec-row"><span className="k">Transmission</span><span className="v">{car.transmission}</span></div>
              <div className="spec-row"><span className="k">Drivetrain</span><span className="v">{car.drivetrain}</span></div>
              <div className="spec-row"><span className="k">Seats / Doors</span><span className="v">{car.seats} / {car.doors}</span></div>
              <div className="spec-row"><span className="k">Fuel</span><span className="v">{car.fuel}</span></div>
              <div className="spec-row"><span className="k">Year</span><span className="v">{car.year}</span></div>
              <div className="spec-row"><span className="k">Exterior</span><span className="v">{car.color}</span></div>
            </div>
            <div style={{marginTop:14,fontSize:12,color:"var(--muted-2)",fontFamily:"var(--font-mono)",letterSpacing:"0.05em"}}>
              Spec values are indicative of the typical configuration of this model. Individual vehicles may vary — confirm at booking.
            </div>
          </div>

          {/* Features */}
          <div className="cd-section">
            <h3><span className="num">02</span>Features &amp; equipment</h3>
            <ul className="features-list">
              {car.features.map((f, i) => <li key={i}>{f}</li>)}
            </ul>
          </div>

          {/* Gallery (use same image with overlays — placeholders flagging "client to supply") */}
          <div className="cd-section">
            <h3><span className="num">03</span>Gallery <span style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--muted-2)",marginLeft:14,letterSpacing:"0.1em"}}>· additional angles to follow</span></h3>
            <div className="gallery-grid">
              <div><img src={car.image} alt=""/></div>
              <div style={{background:"var(--ink-2)",aspectRatio:"16/10",position:"relative"}}>
                <PlaceholderShot label="Interior shot" />
              </div>
              <div style={{background:"var(--ink-2)",aspectRatio:"16/10",position:"relative"}}>
                <PlaceholderShot label="Rear 3/4" />
              </div>
              <div style={{background:"var(--ink-2)",aspectRatio:"16/10",position:"relative"}}>
                <PlaceholderShot label="Detail / wheel" />
              </div>
              <div style={{background:"var(--ink-2)",aspectRatio:"16/10",position:"relative"}}>
                <PlaceholderShot label="Dashboard" />
              </div>
            </div>
          </div>

          {/* Rental terms / requirements */}
          <div className="cd-section">
            <h3><span className="num">04</span>What you'll need</h3>
            <div style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",gap:24}}>
              <div style={{padding:24,background:"var(--ink)",border:"1px solid var(--line-2)",borderRadius:4}}>
                <Icon.Shield/>
                <h4 style={{marginTop:14,marginBottom:8,fontSize:16,fontWeight:600}}>Driver requirements</h4>
                <p style={{fontSize:13,color:"var(--muted-2)",lineHeight:1.6}}>
                  Valid UAE driving licence — or, for visitors, your home licence plus an International Driving Permit. Exact age &amp; document specifics confirmed at booking.
                </p>
              </div>
              <div style={{padding:24,background:"var(--ink)",border:"1px solid var(--line-2)",borderRadius:4}}>
                <Icon.Cal/>
                <h4 style={{marginTop:14,marginBottom:8,fontSize:16,fontWeight:600}}>Deposit &amp; mileage</h4>
                <p style={{fontSize:13,color:"var(--muted-2)",lineHeight:1.6}}>
                  Refundable security deposit of AED {SCR_DATA.formatAED(car.deposit)} on this car (varies by model). Daily mileage cap {car.mileageCap}. Extra distance billed at pickup rate.
                </p>
              </div>
              <div style={{padding:24,background:"var(--ink)",border:"1px solid var(--line-2)",borderRadius:4}}>
                <Icon.Truck/>
                <h4 style={{marginTop:14,marginBottom:8,fontSize:16,fontWeight:600}}>Free delivery, UAE-wide</h4>
                <p style={{fontSize:13,color:"var(--muted-2)",lineHeight:1.6}}>
                  We bring the car to your hotel, residence, DXB curbside or any address in the UAE — at no extra cost.
                </p>
              </div>
              <div style={{padding:24,background:"var(--ink)",border:"1px solid var(--line-2)",borderRadius:4}}>
                <Icon.Clock/>
                <h4 style={{marginTop:14,marginBottom:8,fontSize:16,fontWeight:600}}>24/7 concierge</h4>
                <p style={{fontSize:13,color:"var(--muted-2)",lineHeight:1.6}}>
                  Lost the key at the beach? Salik gate trouble? One WhatsApp number — answered at any hour. +971 56 767 1411.
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Right column — booking */}
        <div>
          <div className="booking-card">
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:18}}>
              <div className="eyebrow gold" style={{color:"var(--accent)"}}>Check availability</div>
              <div style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--muted-2)"}}>STEP 1 / 3</div>
            </div>
            <div className="bcard-row">
              <div className="bcard-field">
                <label>Pickup date</label>
                <input type="date" value={pickupDate} onChange={e => setPickupDate(e.target.value)} />
              </div>
              <div className="bcard-field">
                <label>Return date</label>
                <input type="date" value={returnDate} onChange={e => setReturnDate(e.target.value)} />
              </div>
            </div>
            <div className="bcard-field" style={{marginBottom:14}}>
              <label>Pickup location</label>
              <select value={pickupLoc} onChange={e => setPickupLoc(e.target.value)}>
                {SCR_DATA.PICKUP_LOCATIONS.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
              </select>
            </div>
            <div className="bcard-totals">
              <div className="bcard-line">
                <span><Aed/> {SCR_DATA.formatAED(car.fromRate)} × {days} day{days>1?"s":""}</span>
                <span><Aed/> {SCR_DATA.formatAED(subtotal)}</span>
              </div>
              <div className="bcard-line">
                <span>Free delivery</span>
                <span style={{color:"var(--accent)"}}>Included</span>
              </div>
              <div className="bcard-line">
                <span>Refundable deposit</span>
                <span><Aed/> {SCR_DATA.formatAED(car.deposit)}</span>
              </div>
              <div className="bcard-line total">
                <span>Indicative total</span>
                <span className="amt"><Aed/> {SCR_DATA.formatAED(total)}</span>
              </div>
              <div style={{fontSize:11,color:"var(--muted-2)",marginTop:8,lineHeight:1.5,fontFamily:"var(--font-mono)",letterSpacing:"0.02em"}}>
                Final quote at booking · Salik &amp; fuel deposit additional
              </div>
            </div>
            <Button kind="primary" size="lg" style={{width:"100%",marginTop:18}}
              onClick={() => onReserve({car, pickupDate, returnDate, pickupLoc, days, total})}>
              Continue to reserve <Icon.Arrow/>
            </Button>
            <div style={{display:"flex",gap:8,marginTop:10}}>
              <Button kind="whatsapp" style={{flex:1}} onClick={() => window.open(waLink(reserveMsg))}>
                <Icon.Whatsapp className="icon-sm"/> WhatsApp
              </Button>
              <Button kind="ghost" style={{flex:1}} onClick={() => window.open("tel:+971567671411")}>
                <Icon.Phone className="icon-sm"/> Call
              </Button>
            </div>
            <div style={{marginTop:20,paddingTop:18,borderTop:"1px solid var(--line-2)",display:"flex",flexDirection:"column",gap:10,fontSize:12,color:"var(--muted-2)"}}>
              <div style={{display:"flex",gap:10,alignItems:"center"}}><Icon.Check className="icon-sm" style={{color:"var(--accent)"}}/> No card charged until confirmed</div>
              <div style={{display:"flex",gap:10,alignItems:"center"}}><Icon.Check className="icon-sm" style={{color:"var(--accent)"}}/> Free cancellation 24h before pickup</div>
              <div style={{display:"flex",gap:10,alignItems:"center"}}><Icon.Check className="icon-sm" style={{color:"var(--accent)"}}/> Insurance &amp; CDW included</div>
            </div>
          </div>
        </div>
      </div>

      {/* Similar cars */}
      {similar.length > 0 && (
        <section className="section section-ink">
          <div className="shell-wide">
            <div className="section-head">
              <div>
                <Eyebrow gold>You might also like</Eyebrow>
                <h2 style={{marginTop:18,fontSize:"clamp(28px,3vw,40px)"}}>Other {car.body.toLowerCase()}s in the fleet</h2>
              </div>
              <div className="section-head-actions">
                <Button kind="ghost" onClick={() => navigate({name:"fleet", cat: car.cat})}>All {car.cat} <Icon.Arrow/></Button>
              </div>
            </div>
            <div className="fleet-grid">
              {similar.map(c => <CarCard key={c.id} car={c} onClick={() => navigate({name:"car", id: c.id})}/>)}
            </div>
          </div>
        </section>
      )}
    </div>
  );
};

/* Placeholder for missing gallery shots */
const PlaceholderShot = ({ label }) => (
  <div style={{
    position:"absolute",inset:0,
    background: `repeating-linear-gradient(135deg, var(--ink-2) 0 12px, var(--ink) 12px 24px)`,
    display:"flex",alignItems:"center",justifyContent:"center",
    flexDirection:"column",gap:8,color:"var(--muted-2)"
  }}>
    <div style={{fontFamily:"var(--font-mono)",fontSize:11,letterSpacing:"0.15em",textTransform:"uppercase",color:"var(--muted-2)"}}>
      [ client to supply ]
    </div>
    <div style={{fontSize:13,color:"var(--muted-2)"}}>{label}</div>
  </div>
);

Object.assign(window, { FleetScreen, CarDetailScreen, PlaceholderShot });
