/* global React, ReactDOM, Navbar, Hero, BrandStrip, NoDepositBand, FeaturedFleet, CategoriesBlock, HowItWorks, AwardStrip, CTABand, Footer, FleetPage, VehicleDetail, BookingDrawer, ContactPage, HowPage, AboutPage, FloatRail, TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakColor, TweakToggle, TweakSelect */
const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E16C2A",
  "heroVariant": "ferrari",
  "rtl": false,
  "density": "comfortable",
  "displayFont": "Saira"
}/*EDITMODE-END*/;

const HERO_IMAGES = {
  huracan: "media/car-lamborghini-huracan.webp",
  bentley: "media/car-bentley-bentayga.webp",
  ferrari: "media/car-ferrari-f8.webp",
  cybertruck: "media/car-tesla-cybertruck.webp",
  audi: "media/car-audi-r8.webp"
};

function App() {
  const [route, setRoute] = useState("home");
  const [vehicle, setVehicle] = useState(null);
  const [bookingOpen, setBookingOpen] = useState(false);
  const [bookingVehicle, setBookingVehicle] = useState(null);
  const [locale, setLocale] = useState("en");
  const [initialCategory, setInitialCategory] = useState(null);

  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Imperative navigation exposed to inner components for simplicity
  useEffect(() => {
    window.go = (r) => { setRoute(r); window.scrollTo({top: 0}); };
    window.openVehicle = (v) => { setVehicle(v); setRoute("vehicle"); window.scrollTo({top: 0}); };
    window.openBooking = (v) => { setBookingVehicle(v); setBookingOpen(true); };
  }, []);

  // Apply tweaks to CSS vars
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--primary", tweaks.accent);
    // Derive secondary/accent shades from primary
    root.style.setProperty("--secondary", shade(tweaks.accent, -15));
    root.style.setProperty("--accent", shade(tweaks.accent, 18));
    root.style.setProperty("--font-display", `"${tweaks.displayFont}", "Saira", system-ui, sans-serif`);
    document.documentElement.dir = tweaks.rtl ? "rtl" : "ltr";
    document.documentElement.lang = locale;
  }, [tweaks, locale]);

  // Open hero image swap via tweaks
  useEffect(() => {
    const heroImg = document.querySelector("[data-hero-img]");
    if (heroImg) heroImg.src = HERO_IMAGES[tweaks.heroVariant] || HERO_IMAGES.huracan;
  }, [tweaks.heroVariant, route]);

  const handleSelect = (v) => { setVehicle(v); setRoute("vehicle"); window.scrollTo({top:0}); };
  const handleBook = (v) => { setBookingVehicle(v); setBookingOpen(true); };
  const handlePickCategory = (cat) => { setInitialCategory(cat); setRoute("fleet"); window.scrollTo({top:0}); };

  return (
    <div data-screen-label={`Route: ${route}`}>
      <Navbar locale={locale} setLocale={setLocale} route={route}/>

      {route === "home" && (
        <>
          <Hero locale={locale} heroVariant={tweaks.heroVariant}/>
          <BrandStrip/>
          <FeaturedFleet onSelect={handleSelect}/>
          <NoDepositBand locale={locale}/>
          <CategoriesBlock onPick={handlePickCategory}/>
          <HowItWorks/>
          <AwardStrip/>
          <CTABand/>
        </>
      )}

      {route === "fleet" && <FleetPage onSelect={handleSelect} initialCategory={initialCategory}/>}
      {route === "categories" && <FleetPage onSelect={handleSelect} initialCategory={initialCategory}/>}
      {route === "vehicle" && vehicle && <VehicleDetail v={vehicle} onClose={() => setRoute("fleet")} onBook={handleBook}/>}
      {route === "contact" && <ContactPage/>}
      {route === "how" && <HowPage/>}
      {route === "about" && <AboutPage/>}
      {route === "longterm" && <LeadPlaceholder kind="long-term"/>}
      {route === "corporate" && <LeadPlaceholder kind="corporate"/>}

      <Footer/>
      <FloatRail/>

      <BookingDrawer vehicle={bookingVehicle} open={bookingOpen} onClose={() => setBookingOpen(false)}/>

      <TweaksPanel title="Tweaks" defaultOpen={false}>
        <TweakSection title="Theme">
          <TweakColor
            label="Accent"
            value={tweaks.accent}
            options={["#E16C2A","#D04C2A","#F4A04C","#1F8A5B","#2A6FDB","#A855F7"]}
            onChange={(v) => setTweak("accent", v)}
          />
          <TweakSelect
            label="Display font"
            value={tweaks.displayFont}
            options={["Saira","Rajdhani","Space Grotesk","JetBrains Mono","Inter"]}
            onChange={(v) => setTweak("displayFont", v)}
          />
        </TweakSection>
        <TweakSection title="Hero">
          <TweakSelect
            label="Hero car"
            value={tweaks.heroVariant}
            options={[
              ["huracan","Lambo Huracán (green)"],
              ["bentley","Bentley Bentayga (Dubai night)"],
              ["ferrari","Ferrari F8 (white)"],
              ["cybertruck","Tesla Cybertruck"],
              ["audi","Audi R8 (yellow wall)"]
            ]}
            onChange={(v) => setTweak("heroVariant", v)}
          />
        </TweakSection>
        <TweakSection title="Localisation">
          <TweakToggle label="RTL preview" value={tweaks.rtl} onChange={(v) => setTweak("rtl", v)}/>
          <p style={{ margin:"8px 0 0", fontSize: 11, color:"var(--muted)", lineHeight: 1.4 }}>
            Flips layout direction. Use the EN/AR/RU/ZH switcher in the navbar for copy.
          </p>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function LeadPlaceholder({ kind }) {
  const meta = kind === "long-term"
    ? { title:"Long-term rental", kicker:"Weekly · Monthly · Subscription", body:"The longer the rental, the lower the daily rate. Tell us your dates and we'll match you to the right vehicle with a tailored monthly quote." }
    : { title:"Corporate & fleet", kicker:"Business accounts · VAT-invoiced", body:"Long-term commercial vehicle rental, executive fleets and chauffeur services. We work with hotels, production crews and family offices." };

  return (
    <div style={{ background:"var(--bg)" }}>
      <section style={{ padding:"96px 0", borderBottom:"1px solid var(--border)" }}>
        <div className="container" style={{ padding:"0 32px", maxWidth: 880 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color:"var(--primary)", letterSpacing: 2.5, textTransform:"uppercase", marginBottom: 14 }}>{meta.kicker}</div>
          <h1 style={{ margin: 0, fontFamily:"var(--font-display)", fontSize:"clamp(40px, 6vw, 80px)", fontWeight: 600, letterSpacing:-1.5, lineHeight: 1 }}>
            {meta.title.split(" ").slice(0,-1).join(" ")} <span style={{ color:"var(--primary)", fontStyle:"italic" }}>{meta.title.split(" ").slice(-1)}</span>
          </h1>
          <p style={{ marginTop: 20, color:"var(--muted)", fontSize: 17, lineHeight: 1.6, maxWidth: 640 }}>{meta.body}</p>
          <div style={{ marginTop: 32, display:"flex", gap: 10 }}>
            <Btn variant="primary" iconRight="arrow" onClick={() => window.go("fleet")}>Browse fleet</Btn>
            <Btn variant="whatsapp" icon="whatsapp" href="https://wa.me/971527269337">Talk on WhatsApp</Btn>
          </div>
        </div>
      </section>
    </div>
  );
}

// Lightweight palette helper - shifts a hex color's lightness
function shade(hex, percent) {
  const num = parseInt(hex.slice(1), 16);
  const r = Math.min(255, Math.max(0, (num >> 16) + percent * 2.55));
  const g = Math.min(255, Math.max(0, ((num >> 8) & 0xff) + percent * 2.55));
  const b = Math.min(255, Math.max(0, (num & 0xff) + percent * 2.55));
  return "#" + [r,g,b].map(x => Math.round(x).toString(16).padStart(2, "0")).join("");
}

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