import { Outlet, useLocation, useParams, Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Navbar } from "./Navbar";
import { ToastContainer } from "@/components/ui/Toast";
import { QuotaChip } from "@/components/quota/QuotaChip";
import { useIsAuthenticated } from "@/stores/authStore";
import { useSkill } from "@/hooks/useSkills";

/** Build breadcrumb segments from current route — every crumb is clickable */
function useBreadcrumbs() {
  const location = useLocation();
  const params = useParams();
  const { t } = useTranslation();
  const path = location.pathname;

  // Resolve idOrName → skill name when the route addresses a specific
  // skill, so the breadcrumb shows the human label instead of a raw
  // UUID (e.g. when arriving via notification deep-link). The query is
  // gated on path, so non-skill pages don't trigger a needless fetch.
  // SkillDetailPage already has the same query in flight, so the cache
  // hits without a second round-trip.
  const isSkillRoute = path.startsWith("/skills/") && Boolean(params.idOrName);
  const { data: skillForCrumb } = useSkill(isSkillRoute ? params.idOrName! : "");

  const crumbs: Array<{ label: string; to: string }> = [
    { label: t("breadcrumb.ornn"), to: "/" },
  ];

  const tab = new URLSearchParams(location.search).get("tab");

  if (path === "/registry") {
    crumbs.push(
      tab === "system"
        ? { label: "System Skills", to: "/registry?tab=system" }
        : tab === "my-skills"
        ? { label: t("breadcrumb.mySkills"), to: "/registry?tab=my-skills" }
        : { label: t("breadcrumb.publicSkills"), to: "/registry" }
    );
  } else if (path === "/my-skills") {
    crumbs.push({ label: t("breadcrumb.mySkills"), to: "/my-skills" });
  } else if (path.startsWith("/skills/new")) {
    crumbs.push({ label: t("breadcrumb.createSkill"), to: "/skills/new" });
    if (path === "/skills/new/guided") crumbs.push({ label: t("breadcrumb.guided"), to: "/skills/new/guided" });
    else if (path === "/skills/new/free") crumbs.push({ label: t("breadcrumb.upload"), to: "/skills/new/free" });
    else if (path === "/skills/new/generate") crumbs.push({ label: t("breadcrumb.generate"), to: "/skills/new/generate" });
  } else if (path.startsWith("/skills/") && params.idOrName) {
    // Resolve skill GUID → skill name so the breadcrumb reads the
    // human label even when the user navigated here from a deep link
    // (e.g. notification → /skills/<UUID>/audits). Falls back to the
    // raw idOrName until the skill query lands.
    const skillName = skillForCrumb?.name || params.idOrName;
    crumbs.push({ label: skillName, to: `/skills/${params.idOrName}` });
    if (path.endsWith("/audits") || path.includes("/audits?")) {
      crumbs.push({ label: t("breadcrumb.auditHistory"), to: path });
    }
  } else if (path.startsWith("/skills/") && params.id) {
    crumbs.push({ label: t("breadcrumb.editSkill"), to: path });
  } else if (path === "/playground") {
    const skillName = new URLSearchParams(location.search).get("skill");
    if (skillName) {
      crumbs.push({ label: skillName, to: `/skills/${skillName}` });
      crumbs.push({ label: t("breadcrumb.playground"), to: `/playground?skill=${encodeURIComponent(skillName)}` });
    } else {
      crumbs.push({ label: t("breadcrumb.playground"), to: "/playground" });
    }
  } else if (path === "/services/my") {
    crumbs.push({ label: "My NyxID Services", to: "/services/my" });
  } else if (path === "/services/admin") {
    crumbs.push({ label: "Admin NyxID Services", to: "/services/admin" });
  } else if (path.match(/^\/services\/[^/]+$/)) {
    const source = new URLSearchParams(location.search).get("source");
    if (source === "my") {
      crumbs.push({ label: "My NyxID Services", to: "/services/my" });
    } else {
      crumbs.push({ label: "Admin NyxID Services", to: "/services/admin" });
    }
    crumbs.push({ label: "Service Detail", to: path });
  } else if (path === "/settings") {
    crumbs.push({ label: t("breadcrumb.settings"), to: "/settings" });
  } else if (path === "/docs") {
    const search = new URLSearchParams(location.search);
    const section = search.get("section");
    const title = search.get("title");
    crumbs.push({ label: t("breadcrumb.docs"), to: "/docs" });
    if (section) {
      const label = title || section.replace(/-/g, " ");
      crumbs.push({ label, to: `/docs?section=${section}${title ? `&title=${encodeURIComponent(title)}` : ""}` });
    }
  } else if (path.startsWith("/admin")) {
    // Admin sub-paths get granular crumbs so users can navigate back
    // through the section tree from the top breadcrumb instead of the
    // sidebar. Mirrors the labels the old AdminLayout's own breadcrumb
    // used before admin pages adopted RootLayout's chrome.
    crumbs.push({ label: t("breadcrumb.admin"), to: "/admin/dashboard" });

    if (path.startsWith("/admin/dashboard")) {
      crumbs.push({ label: "Dashboard", to: "/admin/dashboard" });
    } else if (path === "/admin/users-legacy") {
      crumbs.push({ label: "Users (legacy)", to: "/admin/users-legacy" });
    } else if (path.startsWith("/admin/users")) {
      crumbs.push({ label: "Users", to: "/admin/users" });
    } else if (path.startsWith("/admin/quota")) {
      crumbs.push({ label: "Quota", to: "/admin/quota" });
    } else if (path.startsWith("/admin/redemption-codes")) {
      crumbs.push({ label: "Redemption codes", to: "/admin/redemption-codes" });
    } else if (path.startsWith("/admin/skills")) {
      crumbs.push({ label: "Skills", to: "/admin/skills" });
    } else if (path.startsWith("/admin/announcements")) {
      crumbs.push({ label: "Announcements", to: "/admin/announcements" });
    } else if (path.startsWith("/admin/settings")) {
      crumbs.push({ label: "Settings", to: "/admin/settings" });
      const tail = path.replace(/^\/admin\/settings\/?/, "");
      if (tail) {
        crumbs.push({
          label: tail.replace(/[/-]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
          to: path,
        });
      }
    }
  }

  return crumbs;
}

export function RootLayout() {
  const crumbs = useBreadcrumbs();
  const isAuthenticated = useIsAuthenticated();

  return (
    <div className="flex flex-col h-screen bg-page bg-grid overflow-hidden">
      <Navbar />
      {/* Breadcrumb navigation — hide when only root crumb. Width matches
          Navbar (max-w-[1280px] mx-auto px-6 sm:px-8) so the breadcrumb
          rail aligns with the nav above it. The right rail hosts the
          QuotaChip (paired playground + skill-gen pills) when
          authenticated. */}
      {crumbs.length > 1 && (
      <div className="mx-auto w-full max-w-[1280px] shrink-0 px-6 sm:px-8 pt-3 pb-2">
        <div className="flex items-center justify-between gap-4">
          <nav className="flex items-center gap-2 font-mono text-[11px] uppercase tracking-[0.08em]">
            {crumbs.map((crumb, i) => {
              const isLast = i === crumbs.length - 1;
              return (
                <span key={i} className="flex items-center gap-2">
                  {i > 0 && (
                    <span className="text-meta opacity-50 select-none">/</span>
                  )}
                  {isLast ? (
                    <span className="text-accent font-medium">
                      {crumb.label}
                    </span>
                  ) : (
                    <Link
                      to={crumb.to ?? "#"}
                      className="text-meta hover:text-strong transition-colors duration-150"
                    >
                      {crumb.label}
                    </Link>
                  )}
                </span>
              );
            })}
          </nav>
          {isAuthenticated && <QuotaChip />}
        </div>
      </div>
      )}
      <main className="mx-auto w-full max-w-[1280px] flex-1 min-h-0 px-6 sm:px-8 overflow-hidden">
        <Outlet />
      </main>
      <ToastContainer />
    </div>
  );
}
