/* global React, ReactDOM */
const { useState: useStateApp, useEffect: useEffectApp } = React;

function GeoSwitcher() {
  const [collapsed, setCollapsed] = useStateApp(true);
  const [region, setRegion] = useStateApp("gta");
  const regions = [
    { k: "gta", name: "GTA · Ontario" },
    { k: "ca", name: "Rest of Canada" },
    { k: "us", name: "US / Rest of World" },
  ];
  if (collapsed) {
    return (
      <div className="geo collapsed" onClick={() => setCollapsed(false)} style={{ cursor: "pointer" }}>
        <div className="geo__head">
          <span className="geo__dot" />
          <span className="geo__label">GTA edition</span>
        </div>
      </div>
    );
  }
  return (
    <div className="geo">
      <div className="geo__head">
        <span className="geo__dot" />
        <span className="geo__label">Detected · GTA · Ontario</span>
        <button className="geo__close" onClick={() => setCollapsed(true)} aria-label="Dismiss">×</button>
      </div>
      <div className="geo__name">You're seeing the GTA version.</div>
      <div className="geo__msg">Regional content tuned to Canadian corridors. Not where we expect?</div>
      <div className="geo__options">
        {regions.map(r => (
          <button key={r.k} className={region === r.k ? "active" : ""} onClick={() => setRegion(r.k)}>
            {r.k === "gta" ? "● " : ""}{r.name}{r.k !== "gta" ? " · soon" : ""}
          </button>
        ))}
      </div>
    </div>
  );
}

function Home() {
  return (
    <main>
      <Hero />
      <WhatsApp />
      <Features />
      <Corridor />
      <CrossBorder />
      <ROI />
      <SwitchFrom />
      <PricingTease />
      <Resources />
      <FinalCTA />
      <Footer />
    </main>
  );
}

// Map between SPA page-state keys and URL paths.
// SEO-meaningful URLs: /customers, /dispatch, /pricing; home is /.
const PAGE_TO_PATH = { home: "/", serve: "/customers", dispatch: "/dispatch", pricing: "/pricing", contact: "/contact" };
const PATH_TO_PAGE = { "/": "home", "/customers": "serve", "/dispatch": "dispatch", "/pricing": "pricing", "/contact": "contact" };
const pageFromPath = () => PATH_TO_PAGE[location.pathname.replace(/\/+$/, "") || "/"] || "home";

// Per-page meta for richer SERPs and AI summaries when each sub-page is loaded directly.
const PAGE_META = {
  home:     { title: "Lanexa — AI-Native TMS for Canadian Carriers",          desc: "WhatsApp-native TMS for Canadian carriers running cross-border. eManifest, dispatch and driver app — in English & ਪੰਜਾਬੀ, priced in CAD. Early access." },
  serve:    { title: "Customers — Carriers, Brokers & 3PLs | Lanexa",         desc: "Lanexa for Canadian motor carriers, freight brokers and 3PLs running cross-border lanes. WhatsApp dispatch, in-app eManifest, driver app in ਪੰਜਾਬੀ." },
  dispatch: { title: "Dispatch — WhatsApp-Native Load Board | Lanexa",        desc: "Drag-and-drop dispatch board with WhatsApp-native driver comms. Built for Canadian carriers running 10–200 power units across cross-border corridors." },
  pricing:  { title: "Pricing — Per-Seat in CAD, Not Per-Truck | Lanexa",     desc: "Lanexa is priced per seat (dispatchers, ops, billing) in Canadian dollars — not per truck. Final plans landing soon; early-access pricing on the waitlist." },
  contact:  { title: "Contact / Book a Demo | Lanexa",                        desc: "Talk to the team building Lanexa. Book a demo, send a sales question, or just say hi. Built in Canada, priced in CAD, real humans on the corridor." },
};

function App() {
  const [page, setPage] = useStateApp(typeof window !== "undefined" ? pageFromPath() : "home");
  const [theme, setTheme] = useStateApp("dark");

  useEffectApp(() => {
    const se = () => document.scrollingElement || document.documentElement;
    window.__navigate = (p) => {
      setPage(p);
      const targetPath = PAGE_TO_PATH[p] || "/";
      if (location.pathname !== targetPath) {
        history.pushState({ page: p }, "", targetPath);
      }
      const el = se();
      const prev = el.style.scrollBehavior;
      el.style.scrollBehavior = "auto";
      el.scrollTop = 0;
      el.style.scrollBehavior = prev;
    };
    const onPop = () => setPage(pageFromPath());
    window.addEventListener("popstate", onPop);
    // Cleanup adds onPop teardown to the existing cleanup below
    const cleanup = () => {
      window.removeEventListener("popstate", onPop);
      delete window.__navigate; delete window.__scrollToId;
    };
    window.__scrollToId = (id) => {
      const node = document.getElementById(id);
      if (!node) return false;
      const el = se();
      const prev = el.style.scrollBehavior;
      el.style.scrollBehavior = "auto"; // force instant per-step; smooth is paused in bg frames
      const start = el.scrollTop;
      const target = node.getBoundingClientRect().top + start - 76;
      const t0 = performance.now();
      const timer = setInterval(() => {
        const p = Math.min(1, (performance.now() - t0) / 420);
        const e = 1 - Math.pow(1 - p, 3);
        el.scrollTop = start + (target - start) * e;
        if (p >= 1) { clearInterval(timer); el.style.scrollBehavior = prev; }
      }, 16);
      return true;
    };
    return cleanup;
  }, []);

  useEffectApp(() => {
    document.documentElement.setAttribute("data-theme", theme);
  }, [theme]);

  // Per-page <title> + meta description swap. Helps when users share a deep
  // link to /customers or /pricing — the page tab and OG preview show the
  // section-specific copy instead of the home title.
  useEffectApp(() => {
    const m = PAGE_META[page] || PAGE_META.home;
    document.title = m.title;
    const desc = document.querySelector('meta[name="description"]');
    if (desc) desc.setAttribute("content", m.desc);
    const canonical = document.querySelector('link[rel="canonical"]');
    if (canonical) canonical.setAttribute("href", "https://lanexa.io" + (PAGE_TO_PATH[page] || "/"));
  }, [page]);

  // Content copy-paste lock. Blocks the casual "drag-select → Ctrl-C" path
  // and right-click → "Copy text" / "Save image". Form fields are still
  // copy/cut-able so the waitlist and contact form work normally.
  // (DevTools still bypasses this — it's a deterrent, not real DRM.)
  useEffectApp(() => {
    const isFormField = (target) => target && target.closest && target.closest('input, textarea, select, [contenteditable="true"]');
    const onCopy = (e) => { if (!isFormField(e.target)) e.preventDefault(); };
    const onCut  = (e) => { if (!isFormField(e.target)) e.preventDefault(); };
    const onCtx  = (e) => { if (!isFormField(e.target)) e.preventDefault(); };
    document.addEventListener("copy", onCopy);
    document.addEventListener("cut", onCut);
    document.addEventListener("contextmenu", onCtx);
    return () => {
      document.removeEventListener("copy", onCopy);
      document.removeEventListener("cut", onCut);
      document.removeEventListener("contextmenu", onCtx);
    };
  }, []);

  const toggleTheme = () => setTheme(t => t === "dark" ? "light" : "dark");

  let content;
  if (page === "serve") content = <ServePage />;
  else if (page === "dispatch") content = <DispatchPage />;
  else if (page === "pricing") content = <PricingPage />;
  else if (page === "contact") content = <ContactPage />;
  else content = <Home />;

  return (
    <>
      <Nav page={page} theme={theme} toggleTheme={toggleTheme} />
      {content}
      <GeoSwitcher />
    </>
  );
}

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