/* app.jsx — top-level router, tweaks, mount */

const { useState: useStateA, useEffect: useEffectA, useCallback: useCallbackA } = React;

// ─── Simple placeholder pages for sell / about / contact ───
function Sell({ onEnquire }) {
  return (
    <main>
      <section style={{ paddingTop: 140, paddingBottom: 80, background: "var(--noir)", borderBottom: "1px solid var(--line)" }}>
        <div className="wrap">
          <div className="kbd-eyebrow" style={{ marginBottom: 18 }}>Sell your car · Trade-in</div>
          <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 112px)", margin: 0, lineHeight: 0.92, letterSpacing: "-0.04em" }}>
            We buy<br />the cars we like.
          </h1>
          <p style={{ marginTop: 24, fontSize: 17, color: "var(--silver)", maxWidth: 560 }}>
            Send make, model, year, mileage and a few photos. We come back with an indicative offer within 24 working hours, and a confirmed offer after a 30-minute inspection at the showroom.
          </p>
        </div>
      </section>
      <section className="paper sec-pad">
        <div className="wrap">
          <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 64 }}>
            <div>
              <h2 className="display" style={{ fontSize: 48, margin: 0, color: "var(--ink-on-paper)" }}>How it works.</h2>
              <div style={{ marginTop: 32 }}>
                {[
                  ["01", "Send details + photos", "Through the form, by email, or on WhatsApp once we publish the verified number."],
                  ["02", "Indicative offer", "Within 24 working hours, with a range and the basis."],
                  ["03", "Inspection at showroom", "30 minutes. We confirm condition, service history and ownership."],
                  ["04", "Settlement & handover", "Same-day funds. No commission, no auction fees, no marketplace listing."],
                ].map(([n, h, p]) => (
                  <div key={n} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 32, paddingBlock: 22, borderBottom: "1px solid rgba(0,0,0,0.1)" }}>
                    <span className="mono" style={{ fontSize: 12, color: "var(--accent)", letterSpacing: "0.12em", paddingTop: 4 }}>{n}</span>
                    <div>
                      <div className="display" style={{ fontSize: 26, color: "var(--ink-on-paper)" }}>{h}</div>
                      <div style={{ marginTop: 8, color: "#54585f", fontSize: 15, maxWidth: 480 }}>{p}</div>
                    </div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 32 }}>
                <button className="btn btn-primary" onClick={() => onEnquire({ intent: "tradein" })}>Send car details</button>
              </div>
            </div>
            <div>
              <img src="media/vehicles-collection-aboutus.webp" alt="" style={{ width: "100%", borderRadius: 12 }} />
              <div style={{ marginTop: 12, display: "flex", justifyContent: "space-between", color: "#6a6e75", fontSize: 12 }}>
                <span className="mono" style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>From our showroom floor</span>
                <DemoBadge>Photo on file</DemoBadge>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function About() {
  return (
    <main>
      <section style={{ paddingTop: 140, paddingBottom: 0, background: "var(--noir)" }}>
        <div className="wrap">
          <div className="kbd-eyebrow" style={{ marginBottom: 18 }}>About · Founded 2021</div>
          <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 120px)", margin: 0, lineHeight: 0.92, letterSpacing: "-0.04em" }}>
            Dubai. <br /> Eight marques. <br /><span style={{ color: "var(--mute-dark)" }}>One showroom.</span>
          </h1>
          <p style={{ marginTop: 32, fontSize: 18, color: "var(--silver)", maxWidth: 620, lineHeight: 1.55 }}>
            F1rst Motors is a Dubai-based luxury, exotic and hyper-car showroom on Sheikh Zayed Road. Founded in 2021, we curate stock across Bugatti, Ferrari, Lamborghini, Pagani, McLaren, Porsche, Mercedes-Benz and Rolls-Royce.
          </p>
        </div>
      </section>
      <section style={{ paddingBlock: 64, background: "var(--noir)" }}>
        <div className="wrap">
          <img src="media/team.webp" alt="The F1rst Motors team" style={{ width: "100%", borderRadius: 12 }} />
          <div style={{ marginTop: 14, display: "flex", justifyContent: "space-between", color: "var(--mute)", fontSize: 12 }}>
            <span className="mono" style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>The team · Sheikh Zayed Rd showroom</span>
            <span className="mono" style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>Photo on file</span>
          </div>
        </div>
      </section>
      <section className="paper sec-pad">
        <div className="wrap">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 48 }}>
            {[
              ["1,000+", "Cars sold", "Figure stated by F1rst Motors."],
              ["$250M+", "Inventory value", "Figure stated by F1rst Motors."],
              ["2021", "Founded", "In Dubai, on Sheikh Zayed Road."],
            ].map(([v, k, n]) => (
              <div key={k} style={{ borderTop: "1px solid rgba(0,0,0,0.1)", paddingTop: 24 }}>
                <div className="kbd-eyebrow" style={{ color: "#6a6e75", marginBottom: 12 }}>{k}</div>
                <div className="display num" style={{ fontSize: "clamp(48px, 5.4vw, 88px)", color: "var(--ink-on-paper)" }}>{v}</div>
                <div className="mono" style={{ fontSize: 10, color: "#7a7e85", letterSpacing: "0.1em", textTransform: "uppercase", marginTop: 10 }}>{n}</div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

function Contact({ onEnquire }) {
  return (
    <main>
      <section style={{ paddingTop: 140, paddingBottom: 64, background: "var(--noir)" }}>
        <div className="wrap">
          <div className="kbd-eyebrow" style={{ marginBottom: 18 }}>Contact · Visit us</div>
          <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 120px)", margin: 0, lineHeight: 0.92, letterSpacing: "-0.04em" }}>
            Drop in. <br /> Or drop us a line.
          </h1>
        </div>
      </section>
      <section style={{ paddingBlock: 64, background: "var(--noir)" }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48 }}>
          <div style={{ display: "grid", gap: 20 }}>
            <div style={{ padding: 24, border: "1px solid var(--line)", borderRadius: 12, background: "var(--ink)" }}>
              <div className="kbd-eyebrow" style={{ marginBottom: 12 }}>Showroom</div>
              <div style={{ fontSize: 17, lineHeight: 1.5 }}>Danube Building, 409 Sheikh Zayed Rd<br />Al Quoz 1, Dubai · UAE</div>
              <div className="mono" style={{ marginTop: 12, fontSize: 11, color: "var(--mute)", letterSpacing: "0.06em" }}>Coords client to confirm before publication</div>
            </div>
            <div style={{ padding: 24, border: "1px solid var(--line)", borderRadius: 12, background: "var(--ink)" }}>
              <div className="kbd-eyebrow" style={{ marginBottom: 12 }}>Hours</div>
              <div style={{ display: "grid", gap: 6 }}>
                {[["Sun – Thu", "10:00 – 21:00"], ["Saturday", "10:00 – 21:00"], ["Friday", "14:00 – 21:00"]].map(([k, v]) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
                    <span style={{ color: "var(--silver)" }}>{k}</span>
                    <span className="mono num">{v}</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ padding: 24, border: "1px solid var(--line)", borderRadius: 12, background: "var(--ink)" }}>
              <div className="kbd-eyebrow" style={{ marginBottom: 12 }}>Direct</div>
              <div style={{ display: "grid", gap: 10 }}>
                <a className="ul-link" href="tel:+97143201030">+971 4 320 1030</a>
                <a className="ul-link" href="mailto:info@f1rstmotors.com">info@f1rstmotors.com</a>
                <div style={{ color: "var(--mute)", fontSize: 13 }}>WhatsApp — pending verified number</div>
              </div>
            </div>
          </div>

          <div style={{ aspectRatio: "4/5", borderRadius: 12, overflow: "hidden", position: "relative", background: "var(--ink)" }}>
            <img src="media/showroom-building-night.webp" alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 50% 50%, transparent 30%, rgba(11,11,12,0.6) 100%)" }} />
            <div style={{ position: "absolute", left: 24, top: 24, padding: "8px 12px", background: "rgba(11,11,12,0.7)", backdropFilter: "blur(8px)", borderRadius: 8, border: "1px solid var(--line)" }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.12em", textTransform: "uppercase" }}>Open today</div>
              <div className="display" style={{ fontSize: 20, marginTop: 4 }}>F1rst Motors</div>
            </div>
            <div style={{ position: "absolute", bottom: 24, left: 24, right: 24 }}>
              <a className="btn btn-light" href="https://maps.google.com" target="_blank" rel="noreferrer">Open in Maps →</a>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ─── Tweaks panel ────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E11D2A",
  "displayFont": "Geist",
  "rtlPreview": false,
  "showDemoBadges": true
}/*EDITMODE-END*/;

function TweaksRoot({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Identity">
        <TweakColor label="Accent" value={tweaks.accent}
          options={["#E11D2A", "#C7CCD1", "#D4A95B", "#5A6BFF"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakRadio label="Display font" value={tweaks.displayFont}
          options={[
            { value: "Geist", label: "Geist" },
            { value: "Instrument Serif", label: "Serif" },
            { value: "Space Grotesk", label: "Grotesk" },
          ]}
          onChange={(v) => setTweak("displayFont", v)} />
      </TweakSection>

      <TweakSection label="Preview">
        <TweakToggle label="RTL Arabic preview" value={tweaks.rtlPreview}
          onChange={(v) => setTweak("rtlPreview", v)} />
        <TweakToggle label="Show demo data badges" value={tweaks.showDemoBadges}
          onChange={(v) => setTweak("showDemoBadges", v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// ─── App ─────────────────────────────────────────────────────────
function App() {
  // route shape: { page, slug?, filter? }
  const [route, setRoute] = useStateA(() => {
    const h = window.location.hash.replace(/^#/, "");
    if (h.startsWith("vehicle/")) return { page: "vehicle", slug: h.slice("vehicle/".length) };
    if (h && ["home", "inventory", "sell", "about", "contact"].includes(h)) return { page: h };
    return { page: "home" };
  });
  const [lang, setLang] = useStateA("en");
  const [modal, setModal] = useStateA({ open: false, intent: "enquire", vehicle: null });

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

  // Apply tweaks → CSS vars + font swap + RTL + badge visibility
  useEffectA(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", tweaks.accent);
    // adjust hot/deep variants relative
    if (tweaks.accent === "#E11D2A") {
      root.style.setProperty("--accent-hot", "#FF2A38");
    } else {
      root.style.setProperty("--accent-hot", tweaks.accent);
    }

    const fontStack = tweaks.displayFont === "Instrument Serif"
      ? `"Instrument Serif", "Times New Roman", serif`
      : tweaks.displayFont === "Space Grotesk"
      ? `"Space Grotesk", "Geist", sans-serif`
      : `"Geist", "Helvetica Neue", Helvetica, Arial, sans-serif`;
    root.style.setProperty("--display", fontStack);

    // RTL
    document.documentElement.setAttribute("dir", tweaks.rtlPreview ? "rtl" : "ltr");

    // Demo badge visibility
    document.documentElement.setAttribute("data-show-demo", tweaks.showDemoBadges ? "true" : "false");

    // dynamically load alternate fonts on demand
    const id = "tweak-extra-fonts";
    if (!document.getElementById(id)) {
      const link = document.createElement("link");
      link.id = id;
      link.rel = "stylesheet";
      link.href = "https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Space+Grotesk:wght@400;500;600;700&display=swap";
      document.head.appendChild(link);
    }
  }, [tweaks.accent, tweaks.displayFont, tweaks.rtlPreview, tweaks.showDemoBadges]);

  // Sync lang with rtl tweak (for label consistency in demo)
  useEffectA(() => {
    if (tweaks.rtlPreview && lang === "en") setLang("ar");
    if (!tweaks.rtlPreview && lang === "ar") setLang("en");
  }, [tweaks.rtlPreview]);

  // Hash-based routing
  useEffectA(() => {
    const onHash = () => {
      const h = window.location.hash.replace(/^#/, "");
      if (h.startsWith("vehicle/")) setRoute({ page: "vehicle", slug: h.slice("vehicle/".length) });
      else if (h && ["home", "inventory", "sell", "about", "contact"].includes(h)) setRoute({ page: h });
      else setRoute({ page: "home" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Scroll progress
  useEffectA(() => {
    const f = () => {
      const max = document.documentElement.scrollHeight - window.innerHeight;
      const p = max > 0 ? (window.scrollY / max) * 100 : 0;
      document.documentElement.style.setProperty("--scroll", p + "%");
    };
    f(); window.addEventListener("scroll", f, { passive: true });
    return () => window.removeEventListener("scroll", f);
  }, []);

  const navigate = useCallbackA((next) => {
    setRoute(next);
    if (next.page === "vehicle") window.location.hash = `vehicle/${next.slug}`;
    else window.location.hash = next.page;
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  const onSelectVehicle = (slug) => navigate({ page: "vehicle", slug });
  const onEnquire = ({ intent = "enquire", vehicle = null } = {}) => {
    setModal({ open: true, intent, vehicle });
  };

  return (
    <>
      <div className="top-progress" />
      <Header route={route} navigate={navigate} lang={lang} setLang={setLang} onEnquire={onEnquire} />

      <div data-screen-label={route.page === "vehicle" ? `vehicle/${route.slug}` : route.page}>
        {route.page === "home" && <Home lang={lang} onEnquire={onEnquire} navigate={navigate} onSelectVehicle={onSelectVehicle} />}
        {route.page === "inventory" && <Inventory onSelect={onSelectVehicle} onEnquire={onEnquire} initialFilter={route.filter || {}} />}
        {route.page === "vehicle" && <Vehicle slug={route.slug} onSelect={onSelectVehicle} onEnquire={onEnquire} navigate={navigate} />}
        {route.page === "sell" && <Sell onEnquire={onEnquire} />}
        {route.page === "about" && <About />}
        {route.page === "contact" && <Contact onEnquire={onEnquire} />}
      </div>

      <Footer navigate={navigate} onEnquire={onEnquire} />

      <Modal open={modal.open} onClose={() => setModal({ ...modal, open: false })} intent={modal.intent} vehicle={modal.vehicle} />

      <TweaksRoot tweaks={tweaks} setTweak={setTweakFn} />
    </>
  );
}

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