/* app.jsx — root router. The URL hash is the single source of truth for the
   current top-level view, so every screen has a stable, shareable, deep-linkable
   route that works on any static host (S3/CloudFront) with zero server config.

   Routes:
     #/hub                 → the showroom (default)
     #/app/<businessId>    → a brand demo (evercare | nro | bloom)
     #/eagle/<screen>      → Eagle Eye (soc | model | app | agent | compare)
     #/garfio/<id>         → El Capitán Garfio per-box runbook
     #/cifte/<id>          → Çifte Kale per-VM runbook (cifte-linux | cifte-win)

   Auth lives in localStorage (shared across tabs). A new tab inherits the
   session and lands directly on the requested route; an unauthenticated deep
   link shows the gate, then resolves to the originally-requested route. */

const LR_AUTH_KEY = "lr-authed";
function lrReadAuthed() { try { return localStorage.getItem(LR_AUTH_KEY) === "1"; } catch (e) { return false; } }
function lrWriteAuthed(v) { try { v ? localStorage.setItem(LR_AUTH_KEY, "1") : localStorage.removeItem(LR_AUTH_KEY); } catch (e) {} }

// Parse window.location.hash into a navigational route (location only — never
// transient state like in-progress runs or form text).
function lrParseRoute() {
  const full = (window.location.hash || "").replace(/^#\/?/, "");
  const [path, queryStr] = full.split("?");
  const query = {};
  if (queryStr) queryStr.split("&").forEach((kv) => { const i = kv.indexOf("="); const k = i < 0 ? kv : kv.slice(0, i); const val = i < 0 ? "" : kv.slice(i + 1); if (k) query[decodeURIComponent(k)] = decodeURIComponent(val); });
  const parts = path.split("/").filter(Boolean);
  if (!parts.length) return { view: "hub" };
  switch (parts[0]) {
    case "app": return { view: "app", id: parts[1] || null };
    case "eagle": return { view: "eagle", screen: parts[1] || "soc" };
    case "bogazici": return { view: "bogazici", gw: query.gw || "apigee" };
    case "houdini": return { view: "houdini" };
    case "ventriloquist": return { view: "ventriloquist" };
    case "chiquitito": return { view: "chiquitito", screen: parts[1] || "demo" };
    case "shiphappens": return { view: "shiphappens" };
    case "azuredevops": return { view: "azuredevops" };
    case "cucaracha": return { view: "cucaracha", id: parts[1] || null };
    case "garfio": return { view: "garfio", id: parts[1] || null };
    case "cifte": return { view: "cifte", id: parts[1] || null };
    case "ted": return { view: "ted", cat: parts[1] || "skills" };
    case "hub": return { view: "hub" };
    default: return { view: "hub" };
  }
}

function App() {
  const [route, setRoute] = React.useState(lrParseRoute);
  const [authed, setAuthed] = React.useState(lrReadAuthed);
  // shell theme for login + hub ("dark" | "light"), persisted
  const [shellMode, setShellMode] = React.useState(() => {
    try { return localStorage.getItem("lr-shell-theme") || "dark"; } catch (e) { return "dark"; }
  });

  // The URL drives the view: re-read it on hashchange AND popstate (Back/Forward).
  React.useEffect(() => {
    const onChange = () => setRoute(lrParseRoute());
    window.addEventListener("hashchange", onChange);
    window.addEventListener("popstate", onChange);
    return () => { window.removeEventListener("hashchange", onChange); window.removeEventListener("popstate", onChange); };
  }, []);

  // Adopt a session a sibling tab created while this one was open.
  React.useEffect(() => {
    const onStorage = (e) => { if (e.key === LR_AUTH_KEY) setAuthed(lrReadAuthed()); };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  const navigate = React.useCallback((hash) => {
    const h = hash.charAt(0) === "#" ? hash : "#" + hash;
    if (window.location.hash === h) setRoute(lrParseRoute());
    else window.location.hash = h;
  }, []);

  function toggleShellTheme() {
    setShellMode((m) => { const next = m === "dark" ? "light" : "dark"; try { localStorage.setItem("lr-shell-theme", next); } catch (e) {} return next; });
  }

  function handleAuthed() { lrWriteAuthed(true); setAuthed(true); }       // hash is preserved → deep-link resolves
  function handleLogout() { lrWriteAuthed(false); try { localStorage.removeItem("lr-token"); } catch (e) {} window.LR_SESSION_TOKEN = null; setAuthed(false); navigate("#/hub"); }

  // Correct invalid business deep-links back to the hub.
  React.useEffect(() => {
    if (authed && route.view === "app" && !window.getBusiness(route.id)) navigate("#/hub");
  }, [authed, route, navigate]);

  // Unauthenticated → gate. We DON'T touch the hash, so the intended destination
  // is preserved and rendered automatically once authed flips true.
  if (!authed) {
    return <LoginGate onAuthed={handleAuthed} mode={shellMode} onToggleTheme={toggleShellTheme} />;
  }

  let body;
  if (route.view === "app" && window.getBusiness(route.id)) {
    const business = window.getBusiness(route.id);
    body = <DemoApp key={business.id} business={business} route={"#/app/" + business.id} onBack={() => navigate("#/hub")} mode={shellMode} />;
  } else if (route.view === "eagle") {
    body = <EagleEye key="eagle" screen={route.screen} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "bogazici") {
    body = <window.Bogazici key="bogazici" gw={route.gw} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "houdini") {
    body = <window.Houdini key="houdini" mode={shellMode} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "ventriloquist") {
    body = <window.Ventriloquist key="ventriloquist" mode={shellMode} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "chiquitito") {
    body = <window.Chiquitito key="chiquitito" screen={route.screen} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "shiphappens") {
    body = <window.ShipHappens key="shiphappens" navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "azuredevops") {
    body = <window.AzureDevops key="azuredevops" navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "cucaracha") {
    body = <window.CucarachaRunbook key={"cucaracha-" + route.id} vmId={route.id} mode={shellMode} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "garfio") {
    body = <window.GarfioRunbook key={"garfio-" + route.id} id={route.id} mode={shellMode} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "cifte") {
    body = <window.CifteRunbook key={"cifte-" + route.id} id={route.id} mode={shellMode} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else if (route.view === "ted") {
    body = <window.TedStation key={"ted-" + route.cat} cat={route.cat} mode={shellMode} navigate={navigate} onBack={() => navigate("#/hub")} />;
  } else {
    body = (
      <Hub
        onLaunch={(b) => navigate("#/app/" + b.id)}
        onLaunchEagle={(s) => navigate("#/eagle/" + (s || "soc"))}
        onLaunchBogazici={(g) => navigate("#/bogazici?gw=" + (g || "apigee"))}
        onLogout={handleLogout}
        mode={shellMode}
        onToggleTheme={toggleShellTheme}
      />
    );
  }

  return <div className="h-full w-full">{body}</div>;
}

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