"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import BrandMark from "@/components/site/BrandMark";

export type NavItem = { href: string; label: string; icon: string };

const ICONS: Record<string, React.ReactNode> = {
  grid: (
    <>
      <rect x="3" y="3" width="7" height="7" rx="1" />
      <rect x="14" y="3" width="7" height="7" rx="1" />
      <rect x="3" y="14" width="7" height="7" rx="1" />
      <rect x="14" y="14" width="7" height="7" rx="1" />
    </>
  ),
  server: (
    <>
      <rect x="3" y="4" width="18" height="7" rx="1.5" />
      <rect x="3" y="13" width="18" height="7" rx="1.5" />
      <path d="M7 7.5 h.01 M7 16.5 h.01" />
    </>
  ),
  ticket: (
    <>
      <path d="M4 7 h16 v4 a2 2 0 0 0 0 2 v4 H4 v-4 a2 2 0 0 0 0 -2 Z" />
      <path d="M13 7 v10" strokeDasharray="2 2.5" />
    </>
  ),
  invoice: (
    <>
      <path d="M6 3 h12 v18 l-3 -2 -3 2 -3 -2 -3 2 Z" />
      <path d="M9 8 h6 M9 12 h6" />
    </>
  ),
  inbox: (
    <>
      <path d="M4 4 h16 v16 H4 Z" />
      <path d="M4 14 h5 l1.5 2.5 h3 L15 14 h5" />
    </>
  ),
  users: (
    <>
      <circle cx="9" cy="8" r="3.2" />
      <path d="M3.5 20 c0 -3.5 2.5 -5.5 5.5 -5.5 s5.5 2 5.5 5.5" />
      <circle cx="17" cy="9" r="2.4" />
      <path d="M15.5 14.8 c2.8 0 5 1.8 5 4.7" />
    </>
  ),
  globe: (
    <>
      <circle cx="12" cy="12" r="9" />
      <path d="M3 12 h18 M12 3 c3 3.5 3 14 0 18 c-3 -4 -3 -14.5 0 -18" />
    </>
  ),
};

function Icon({ name }: { name: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="h-[18px] w-[18px]"
      aria-hidden
    >
      {ICONS[name] ?? ICONS.grid}
    </svg>
  );
}

export default function PanelShell({
  items,
  title,
  userName,
  userMeta,
  children,
}: {
  items: NavItem[];
  title: string;
  userName: string;
  userMeta: string;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState(false);

  const logout = async () => {
    await fetch("/api/auth/logout", { method: "POST" });
    router.push("/");
    router.refresh();
  };

  const nav = (
    <nav aria-label={`${title} navigation`} className="flex flex-1 flex-col gap-1">
      {items.map((it) => {
        const active = it.href === pathname || (it.href.split("/").length > 2 && pathname.startsWith(it.href + "/"));
        return (
          <Link
            key={it.href}
            href={it.href}
            aria-current={active ? "page" : undefined}
            onClick={() => setOpen(false)}
            className={`flex items-center gap-3 rounded-lg px-3.5 py-2.5 text-[0.92rem] transition-colors ${
              active
                ? "bg-azure/15 font-medium text-azure-bright"
                : "text-tmid hover:bg-white/5 hover:text-thi"
            }`}
          >
            <Icon name={it.icon} />
            {it.label}
          </Link>
        );
      })}
    </nav>
  );

  return (
    <div className="weave-dark flex min-h-[100svh]">
      {/* sidebar (desktop) */}
      <aside className="sticky top-0 hidden h-[100svh] w-[248px] shrink-0 flex-col border-r border-white/10 bg-ink-2/60 p-5 lg:flex">
        <Link href="/" className="flex items-center gap-2.5 px-2 text-thi">
          <BrandMark className="h-7 w-7" />
          <span className="font-[family-name:var(--font-display)] text-xl font-bold leading-none">
            Vira<span className="font-medium text-azure-bright">.sa</span>
          </span>
        </Link>
        <p className="mb-5 mt-1.5 px-2 font-[family-name:var(--font-mono)] text-[0.66rem] uppercase tracking-[0.18em] text-tlo">
          {title}
        </p>
        {nav}
        <div className="border-t border-white/10 pt-4">
          <p className="px-2 text-[0.88rem] font-medium text-thi">{userName}</p>
          <p className="px-2 text-[0.76rem] text-tlo">{userMeta}</p>
          <button
            onClick={logout}
            className="mt-3 w-full rounded-lg border border-white/10 px-3 py-2 text-[0.85rem] text-tmid transition-colors hover:border-ice hover:text-ice"
          >
            Sign out
          </button>
        </div>
      </aside>

      {/* mobile top bar */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="sticky top-0 z-40 flex items-center justify-between border-b border-white/10 bg-ink/90 px-4 py-3 backdrop-blur-md lg:hidden">
          <Link href="/" className="flex items-center gap-2 text-thi">
            <BrandMark className="h-6 w-6" />
            <span className="font-[family-name:var(--font-display)] text-lg font-bold">
              Vira <span className="font-[family-name:var(--font-mono)] text-[0.65rem] font-normal uppercase tracking-widest text-tlo">{title}</span>
            </span>
          </Link>
          <button
            onClick={() => setOpen(!open)}
            aria-expanded={open}
            aria-label={open ? "Close menu" : "Open menu"}
            className="rounded-lg border border-white/15 px-3.5 py-2 text-[0.85rem] text-tmid"
          >
            {open ? "Close" : "Menu"}
          </button>
        </header>
        {open && (
          <div className="border-b border-white/10 bg-ink-2 p-4 lg:hidden">
            {nav}
            <button
              onClick={logout}
              className="mt-3 w-full rounded-lg border border-white/10 px-3 py-2 text-[0.85rem] text-tmid"
            >
              Sign out ({userName})
            </button>
          </div>
        )}

        <main className="min-w-0 flex-1 p-4 md:p-8">{children}</main>
      </div>
    </div>
  );
}
