"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Building2, CreditCard, Database, FileClock, KeyRound, KanbanSquare, Lock, MessagesSquare, Settings2, ShieldCheck, Users, Shield } from "lucide-react";
import { cx } from "@/components/ui";
import { useApi } from "@/components/hooks";

const ITEMS = [
  { href: "/settings", label: "General", icon: <Settings2 />, cap: "admin" },
  { href: "/settings/security", label: "Profile & security", icon: <Lock /> },
  { href: "/settings/security-policy", label: "Security policy", icon: <Shield />, cap: "admin" },
  { href: "/settings/team", label: "Team", icon: <Users />, cap: "admin" },
  { href: "/settings/roles", label: "Roles & permissions", icon: <ShieldCheck />, cap: "admin" },
  { href: "/settings/social", label: "Social inbox", icon: <MessagesSquare />, cap: "social" },
  { href: "/settings/pipelines", label: "Pipelines & routing", icon: <KanbanSquare />, cap: "pipelines" },
  { href: "/settings/fields", label: "Fields & objects", icon: <Database />, cap: "admin" },
  { href: "/settings/api", label: "API keys", icon: <KeyRound />, cap: "admin" },
  { href: "/settings/audit", label: "Audit log", icon: <FileClock />, cap: "admin" },
  { href: "/settings/privacy", label: "Privacy & data", icon: <Shield />, cap: "admin" },
  { href: "/settings/billing", label: "Billing & usage", icon: <CreditCard />, cap: "admin" },
  { href: "/settings/agency", label: "Agency & white-label", icon: <Building2 />, agency: true },
];

export default function SettingsLayout({ children }: { children: React.ReactNode }) {
  const path = usePathname();
  const me = useApi<{ data: { user: { isAgencyAdmin: boolean } | null; permissions: Record<string, string> } }>("/me");
  const perms = me.data?.data.permissions ?? {};
  const items = ITEMS.filter((i) => (i.agency ? me.data?.data.user?.isAgencyAdmin : !i.cap || perms[i.cap]));
  return (
    <div className="grid gap-6 lg:grid-cols-[210px_1fr]">
      <nav className="flex gap-1 overflow-x-auto lg:flex-col">
        {items.map((i) => (
          <Link key={i.href} href={i.href} className={cx("flex shrink-0 items-center gap-2 rounded-[7px] px-2.5 py-1.5 text-[13px] [&>svg]:h-4 [&>svg]:w-4", path === i.href ? "bg-ink/[.08] font-medium text-ink" : "text-ink-2 hover:bg-ink/[.05]")}>
            {i.icon}{i.label}
          </Link>
        ))}
      </nav>
      <div className="min-w-0">{children}</div>
    </div>
  );
}
