import { type ParentProps, createMemo } from "solid-js";
import { useLocation, useNavigate } from "@solidjs/router";
import DashboardShell from "~/components/DashboardShell";

const SIDEBAR_ITEMS = [
  "My Dashboard",
  "Leads",
  "My Requests",
  "Credits",
  "Settings",
  "Logout",
];

const ROUTE_BY_LABEL: Record<string, string> = {
  "my dashboard": "/dashboard",
  leads: "/dashboard/leads",
  "my requests": "/dashboard/requests",
  credits: "/dashboard/credits",
  settings: "/dashboard/settings",
  logout: "/dashboard/logout",
};

function readUserName() {
  if (typeof window === "undefined") return "User";
  try {
    const raw =
      localStorage.getItem("nxtgauge_auth_user") ||
      localStorage.getItem("nxtgauge_user");
    if (!raw) return "User";
    const parsed = JSON.parse(raw);
    return parsed?.full_name || parsed?.name || parsed?.email || "User";
  } catch {
    return "User";
  }
}

export default function DashboardLayout(props: ParentProps) {
  const location = useLocation();
  const navigate = useNavigate();

  const activeSidebar = createMemo(() => {
    const path = location.pathname || "";
    if (path.startsWith("/dashboard/requests")) return "My Requests";
    if (path.startsWith("/dashboard/leads")) return "Leads";
    if (path.startsWith("/dashboard/credits")) return "Credits";
    if (path.startsWith("/dashboard/settings")) return "Settings";
    return "My Dashboard";
  });

  const handleSidebarSelect = (item: string) => {
    const target = ROUTE_BY_LABEL[item.toLowerCase()];
    if (target) navigate(target);
  };

  const roleKey = createMemo(() => {
    if (typeof window === "undefined") return "DEVELOPER";
    const fromUrl = new URLSearchParams(window.location.search).get("role");
    if (fromUrl && fromUrl.trim()) return fromUrl.trim().toUpperCase();
    try {
      const raw =
        localStorage.getItem("nxtgauge_signup_profile_v1") ||
        localStorage.getItem("nxtgauge_auth_user") ||
        localStorage.getItem("nxtgauge_user") ||
        sessionStorage.getItem("nxtgauge_signup_profile_v1") ||
        sessionStorage.getItem("nxtgauge_auth_user") ||
        sessionStorage.getItem("nxtgauge_user");
      if (!raw) return "DEVELOPER";
      const parsed = JSON.parse(raw);
      const candidate = String(
        parsed?.selectedProfessionalRole || parsed?.active_role || parsed?.roleKey || parsed?.role || ""
      )
        .trim()
        .toUpperCase();
      return candidate && candidate !== "PROFESSIONAL" ? candidate : "DEVELOPER";
    } catch {
      return "DEVELOPER";
    }
  });

  return (
    <DashboardShell
      sidebarItems={SIDEBAR_ITEMS}
      activeSidebar={activeSidebar()}
      onSidebarSelect={handleSidebarSelect}
      roleKey={roleKey()}
      userName={readUserName()}
    >
      {props.children}
    </DashboardShell>
  );
}
