/* Root: routing + shell + theme + overlays */
const pagesTenant = new Set(["tenant-dashboard","tenant-calls","tenant-insights","tenant-numbers","tenant-team","connections","tenant-billing","tenant-settings","ai-receptionist","support","call-detail"]);
const pagesAdmin  = new Set(["dashboard","tenants","tenant-detail","calls-global","number-pool","at-setup","routing","fraud","billing-plans","audit","admin-settings","create-tenant"]);
const pagesFull   = new Set(["marketing","product","pricing","compliance","docs","changelog","demo","login","signup","forgot","reset","tenant-onboarding"]);
const routePaths = {
  marketing: "/",
  product: "/product",
  pricing: "/pricing",
  compliance: "/compliance",
  docs: "/docs",
  changelog: "/changelog",
  demo: "/demo",
  login: "/login",
  signup: "/signup",
  forgot: "/forgot",
  reset: "/reset",
  "tenant-onboarding": "/onboarding",
  "tenant-dashboard": "/tenant/dashboard",
  "tenant-calls": "/tenant/calls",
  "call-detail": "/tenant/calls/detail",
  "tenant-insights": "/tenant/insights",
  "tenant-numbers": "/tenant/numbers",
  connections: "/tenant/connections",
  "tenant-team": "/tenant/team",
  "tenant-billing": "/tenant/billing",
  "tenant-settings": "/tenant/settings",
  "ai-receptionist": "/tenant/ai-receptionist",
  support: "/tenant/support",
  dashboard: "/admin/dashboard",
  tenants: "/admin/tenants",
  "tenant-detail": "/admin/tenant-detail",
  "create-tenant": "/admin/tenants/new",
  "calls-global": "/admin/calls",
  "number-pool": "/admin/number-pool",
  "at-setup": "/admin/at-setup",
  routing: "/admin/routing",
  fraud: "/admin/fraud",
  "billing-plans": "/admin/billing-plans",
  audit: "/admin/audit",
  "admin-settings": "/admin/settings",
};

function routeFromPath(pathname) {
  const path = pathname || "/";
  const normalized = path === "" ? "/" : path;
  const pair = Object.entries(routePaths).find(([, routePath]) => routePath === normalized);
  return pair ? pair[0] : null;
}

function syncUrl(route, replace = false) {
  const path = routePaths[route];
  if (!path) return;
  const target = `${window.location.origin}${path}`;
  if (window.location.href === target) return;
  if (replace) {
    window.history.replaceState({ route }, "", path);
    return;
  }
  window.history.pushState({ route }, "", path);
}

function pageTitle(route) {
  const map = {
    "tenant-dashboard": "Home", "tenant-calls": "Calls", "tenant-insights": "Insights",
    "tenant-numbers": "Numbers", "tenant-team": "Team", "connections": "Connections",
    "tenant-billing": "Billing", "tenant-settings": "Settings", "ai-receptionist": "AI receptionist",
    "support": "Help & support", "call-detail": "Call detail",
    "dashboard": "Control plane", "tenants": "Tenants", "tenant-detail": "Tenant",
    "calls-global": "All calls", "number-pool": "Number pool", "at-setup": "AT setup queue",
    "routing": "Routing & LCR", "fraud": "Fraud & limits", "billing-plans": "Billing plans",
    "audit": "Audit trail", "admin-settings": "Settings", "create-tenant": "New tenant",
  };
  return map[route] || "Mikaka Voice";
}

function renderRoute(route, onGo) {
  switch (route) {
    case "marketing": return <MarketingPage onGo={onGo}/>;
    case "product": return <ProductPage onGo={onGo}/>;
    case "pricing": return <PricingPage onGo={onGo}/>;
    case "compliance": return <CompliancePage onGo={onGo}/>;
    case "docs": return <DocsPage onGo={onGo}/>;
    case "changelog": return <ChangelogPage onGo={onGo}/>;
    case "demo": return <DemoPage onGo={onGo}/>;
    case "login": return <Login onGo={onGo}/>;
    case "signup": return <Signup onGo={onGo}/>;
    case "forgot": return <ForgotPassword onGo={onGo}/>;
    case "reset": return <ResetPassword onGo={onGo}/>;
    case "tenant-onboarding": return <TenantOnboarding onGo={onGo}/>;

    case "tenant-dashboard": return <TenantDashboard onGo={onGo}/>;
    case "tenant-calls": return <TenantCalls onGo={onGo}/>;
    case "tenant-insights": return <TenantInsights/>;
    case "tenant-numbers": return <TenantNumbers/>;
    case "tenant-team": return <TenantTeam/>;
    case "connections": return <TenantConnections/>;
    case "tenant-billing": return <TenantBilling/>;
    case "tenant-settings": return <TenantSettings/>;
    case "ai-receptionist": return <AIReceptionist/>;
    case "support": return <Support/>;
    case "call-detail": return <CallDetail onGo={onGo}/>;

    case "dashboard": return <AdminDashboard onGo={onGo}/>;
    case "tenants": return <AdminTenants onGo={onGo}/>;
    case "tenant-detail": return <TenantDetail onGo={onGo}/>;
    case "calls-global": return <CallsGlobal onGo={onGo}/>;
    case "number-pool": return <NumberPool/>;
    case "at-setup": return <ATSetupQueue/>;
    case "routing": return <AdminRouting/>;
    case "fraud": return <AdminFraud/>;
    case "billing-plans": return <BillingPlans/>;
    case "audit": return <AuditTrail/>;
    case "admin-settings": return <AdminSettings/>;
    case "create-tenant": return <CreateTenant onGo={onGo}/>;

    default: return <NotFound onGo={onGo}/>;
  }
}

const Shell = () => {
  const [route, setRoute] = useState(() => routeFromPath(window.location.pathname) || localStorage.getItem("mk-route") || "marketing");
  const [theme, setTheme] = useState(() => localStorage.getItem("mk-theme") || "light");
  const [notifOpen, setNotifOpen] = useState(false);
  const [cmdOpen, setCmdOpen] = useState(false);
  const store = MK_USE();

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("mk-theme", theme);
  }, [theme]);

  useEffect(() => {
    syncUrl(route, true);
  }, []);

  useEffect(() => {
    localStorage.setItem("mk-route", route);
    syncUrl(route);
  }, [route]);

  useEffect(() => {
    const onPopState = () => {
      const nextRoute = routeFromPath(window.location.pathname);
      if (nextRoute) setRoute(nextRoute);
    };
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, []);

  useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setCmdOpen(o => !o); }
      if (e.key === "Escape") { setCmdOpen(false); setNotifOpen(false); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  const onGo = (r) => setRoute(r);
  const toggle = () => setTheme(t => t === "light" ? "dark" : "light");
  const onLogout = () => setRoute("login");

  const isFull = pagesFull.has(route);
  const isTenant = pagesTenant.has(route);
  const userType = isTenant ? "tenant" : "admin";
  const notifUnread = store.notifications.filter(n => !n.read).length;

  const overlays = (
    <>
      <NotificationsPanel open={notifOpen} onClose={() => setNotifOpen(false)}/>
      <CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} onGo={onGo}/>
    </>
  );

  if (isFull) {
    return (
      <>
        {renderRoute(route, onGo)}
        <PageSwitcher route={route} onGo={onGo} theme={theme} setTheme={setTheme}/>
        {overlays}
      </>
    );
  }

  return (
    <div className="app-shell">
      <Sidebar userType={userType} current={route} onGo={onGo} onLogout={onLogout}/>
      <main style={{ minWidth: 0 }}>
        <Topbar
          title={pageTitle(route)}
          onThemeToggle={toggle}
          theme={theme}
          onLogout={onLogout}
          userType={userType}
          onOpenNotif={() => setNotifOpen(true)}
          onOpenCmd={() => setCmdOpen(true)}
          notifUnread={notifUnread}
        />
        {renderRoute(route, onGo)}
      </main>
      <PageSwitcher route={route} onGo={onGo} theme={theme} setTheme={setTheme}/>
      {overlays}
    </div>
  );
};

const App = () => (
  <ToastProvider>
    <Shell/>
  </ToastProvider>
);

const PageSwitcher = ({ route, onGo, theme, setTheme }) => {
  const [open, setOpen] = useState(false);
  const groups = [
    ["Public", [["marketing","Landing"],["product","Product"],["pricing","Pricing"],["compliance","Compliance"],["docs","Docs"],["changelog","Changelog"],["demo","Listen demo"],["login","Login"],["signup","Signup"],["forgot","Forgot pw"],["reset","Reset pw"],["tenant-onboarding","Onboarding"]]],
    ["Tenant", [["tenant-dashboard","Home"],["ai-receptionist","Receptionist"],["tenant-calls","Calls"],["call-detail","Call detail"],["tenant-insights","Insights"],["tenant-numbers","Numbers"],["connections","Connections"],["tenant-team","Team"],["tenant-billing","Billing"],["tenant-settings","Settings"],["support","Support"]]],
    ["Admin", [["dashboard","Control plane"],["tenants","Tenants"],["tenant-detail","Tenant detail"],["create-tenant","New tenant"],["calls-global","All calls"],["number-pool","Number pool"],["at-setup","AT setup queue"],["routing","Routing"],["fraud","Fraud"],["billing-plans","Plans"],["audit","Audit"],["admin-settings","Settings"]]],
  ];
  if (!open) {
    return (
      <button onClick={() => setOpen(true)} style={{ position: "fixed", bottom: 20, right: 20, zIndex: 100, background: "var(--mk-ink)", color: "#fff", border: 0, borderRadius: 999, width: 48, height: 48, cursor: "pointer", boxShadow: "var(--sh-lg)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name="layers" size={18}/>
      </button>
    );
  }
  return (
    <div className="page-switcher">
      <div className="row between" style={{ padding: "4px 10px" }}>
        <div className="ps-head" style={{ padding: 0 }}>Screens</div>
        <button onClick={() => setOpen(false)} style={{ padding: 4, fontSize: 10 }}>✕</button>
      </div>
      <div className="theme-tog">
        <button className={theme==="light"?"on":""} onClick={() => setTheme("light")}><Icon name="sun" size={12} style={{ marginRight: 4 }}/> Light</button>
        <button className={theme==="dark"?"on":""} onClick={() => setTheme("dark")}><Icon name="moon" size={12} style={{ marginRight: 4 }}/> Dark</button>
      </div>
      {groups.map(([label, items]) => (
        <React.Fragment key={label}>
          <div className="ps-head">{label}</div>
          {items.map(([id, name]) => (
            <button key={id} className={route===id?"on":""} onClick={() => onGo(id)}>{name}</button>
          ))}
        </React.Fragment>
      ))}
    </div>
  );
};

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