"use client";

import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { useCurrentUser } from "@/components/layout/CurrentUserContext";

const baseSections = [
  { label: "Toko & Koneksi", href: "/tokens", paths: ["/tokens", "/integrations"] },
  { label: "Aktivitas Sistem", href: "/logs", paths: ["/logs"] },
];

function isCurrent(pathname: string, paths: string[]) {
  return paths.some((path) => pathname === path || pathname.startsWith(`${path}/`));
}

export default function ControlCenterNav() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const shopId = searchParams.get("shop_id");
  const currentUser = useCurrentUser();
  const canManageUsers = currentUser?.role === "super_admin" || currentUser?.role === "owner";
  const sections = [
    ...baseSections,
    ...(canManageUsers ? [{ label: "Manajemen Pengguna", href: "/users", paths: ["/users"] }] : []),
    { label: canManageUsers ? "Pengaturan & AI" : "Pengaturan Akun", href: "/settings", paths: ["/settings", "/admin"] },
  ];

  function hrefFor(href: string) {
    return shopId ? `${href}?shop_id=${encodeURIComponent(shopId)}` : href;
  }

  return (
    <section className="control-center-nav" aria-label="Pusat sistem Sellfin">
      <div className="control-center-title">
        <span className="text-sm font-bold text-slate-950 dark:text-white">Pusat Sistem</span>
        <span className="text-[11px] text-slate-500">Koneksi toko, aktivitas, pengguna, dan pengaturan</span>
      </div>
      <nav className="control-center-tabs" aria-label="Bagian pusat sistem">
        {sections.map((section) => {
          const active = isCurrent(pathname, section.paths);
          return (
            <Link className={`control-center-tab ${active ? "is-active" : ""}`} href={hrefFor(section.href)} key={section.href}>
              <span className="block truncate">{section.label}</span>
            </Link>
          );
        })}
      </nav>
    </section>
  );
}
