"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import * as Avatar from "@radix-ui/react-avatar";
import {
  LayoutGrid,
  Users,
  CheckSquare,
  Settings as SettingsIcon,
  LogOut,
  LogIn,
  ArrowUpCircle,
  Package,
  FolderOpen,
  BriefcaseBusiness,
  Workflow,
  Pickaxe,
  Boxes,
  Gem,
  FlaskConical,
  Factory,
  Building2,
} from "lucide-react";
import { useAccountSession } from "../account-session.jsx";
import SidebarAvatar from "./sidebar-avatar.jsx";

const navigation = [
  { group: "work",    name: "Spaces",      href: "/",            icon: LayoutGrid        },
  { group: "work",    name: "Projects",    href: "/projects",    icon: FolderOpen        },
  { group: "work",    name: "Agents",      href: "/agents",      icon: Users             },
  { group: "work",    name: "Tasks",       href: "/tasks",       icon: BriefcaseBusiness },
  { group: "work",    name: "Workflows",   href: "/workflows",   icon: Workflow          },
  { group: "work",    name: "Approvals",   href: "/approvals",   icon: CheckSquare       },
  { group: "library", name: "Marketplace", href: "/marketplace", icon: Package           },
];

// Icon allowlist for module-contributed nav (manifest carries an icon NAME
// string; map it to a Lucide component here). Unknown names fall back to Boxes.
const MODULE_ICONS = { Pickaxe, Boxes, Gem, FlaskConical, Factory, Building2, Package, FolderOpen, Workflow };

function resolveModuleIcon(name) {
  return MODULE_ICONS[name] || Boxes;
}

const footerNav = [
  { name: "Settings", icon: SettingsIcon, href: "/settings" },
];

function isItemActive(pathname, href) {
  if (!pathname) return false;
  if (href === "/") return pathname === "/";
  return pathname === href || pathname.startsWith(`${href}/`);
}

const baseClasses =
  "relative flex items-center justify-center p-2 rounded-lg transition-colors duration-150 group";
const inactiveClasses =
  "text-[#69707a] hover:text-[#111318] hover:bg-[rgba(17,19,24,0.08)] active:bg-[rgba(17,19,24,0.12)]";
const activeClasses =
  "text-[#C2452A]";

// Drop focus immediately after a pointer click so the link's :focus state
// doesn't pin the tooltip open after navigation. Keyboard users still see
// the tooltip via group-focus-visible.
function handleNavClick(event) {
  event.currentTarget?.blur?.();
}

function NavLink({ item, active }) {
  const Icon = item.icon;
  return (
    <Link
      href={item.href}
      prefetch
      aria-label={item.name}
      aria-current={active ? "page" : undefined}
      data-active={active ? "true" : undefined}
      onClick={handleNavClick}
      className={`${baseClasses} ${active ? activeClasses : inactiveClasses}`}
    >
      <Icon className="w-5 h-5" strokeWidth={1.75} aria-hidden="true" />
      <span className="absolute left-12 px-2 py-1 rounded-md whitespace-nowrap text-xs text-white bg-[#111318] hidden group-hover:inline-block group-focus-visible:inline-block z-50 shadow-lg pointer-events-none">
        {item.name}
      </span>
    </Link>
  );
}

export default function Sidebar({ moduleNav = [] }) {
  const pathname = usePathname();
  const { session, signOut } = useAccountSession();
  const [versionInfo, setVersionInfo] = useState(null);

  useEffect(() => {
    let alive = true;
    fetch('/api/system/update')
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => { if (alive && d) setVersionInfo(d); })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  // Compose: core work items → installed-module surfaces → library (Marketplace).
  // Module items get their own group so a divider sets them apart.
  const moduleItems = (Array.isArray(moduleNav) ? moduleNav : []).map((n) => ({
    group: "module",
    name: n.label,
    href: n.href,
    icon: resolveModuleIcon(n.icon),
  }));
  const navItems = [
    ...navigation.filter((i) => i.group === "work"),
    ...moduleItems,
    ...navigation.filter((i) => i.group === "library"),
  ];
  const accountEmail = session?.email || 'Local owner';
  // Treat unknown (still-loading) session as local — avoids flashing a
  // destructive "Sign out" for users who are actually in local mode.
  const isLocal = (session?.auth_mode || 'local') === 'local';
  const initials = (session?.email || session?.display_name || 'AK')
    .slice(0, 2)
    .toUpperCase();

  return (
    <aside
      className="relative z-30 h-full w-full rounded-[18px] border border-white/75 bg-[var(--glass)] backdrop-blur-[22px] backdrop-saturate-150 flex flex-col"
      aria-label="Primary navigation"
    >
      <div className="h-20 flex items-center justify-center px-3 shrink-0">
        <SidebarAvatar />
      </div>

      <div className="flex-1 flex flex-col min-h-0">
        <ul className="list-none m-0 p-0 px-3 text-sm font-medium flex-1 space-y-1">
          {navItems.map((item, idx) => {
            const prev = navItems[idx - 1];
            const showDivider = prev && prev.group !== item.group;
            const active = isItemActive(pathname, item.href);
            return (
              <li key={item.name}>
                {showDivider ? (
                  <div
                    aria-hidden="true"
                    className="mx-2 my-2 h-px bg-[rgba(20,22,26,0.09)]"
                  />
                ) : null}
                <NavLink item={item} active={active} />
              </li>
            );
          })}
        </ul>

        <ul className="list-none m-0 p-0 px-3 pb-3 pt-2 text-sm font-medium space-y-1">
          {footerNav.map((item) => {
            const active = isItemActive(pathname, item.href);
            return (
              <li key={item.name}>
                <NavLink item={item} active={active} />
              </li>
            );
          })}
        </ul>

        <div className="relative py-4 px-3 border-t border-[rgba(20,22,26,0.09)] flex justify-center">
          <DropdownMenu.Root>
            <DropdownMenu.Trigger
              className="outline-none rounded-full border-0 bg-transparent p-0 appearance-none cursor-pointer focus-visible:ring-2 focus-visible:ring-[#111318] focus-visible:ring-offset-2 focus-visible:ring-offset-white/50"
              aria-label="Account menu"
            >
              <Avatar.Root className="w-10 h-10 rounded-full overflow-hidden cursor-pointer block">
                <Avatar.Image
                  className="w-full h-full object-cover"
                  src="/madarx-mark.svg"
                  alt="AK"
                />
                <Avatar.Fallback
                  className="flex w-full h-full items-center justify-center text-white text-xs font-bold tracking-wider bg-gradient-to-br from-[#111318] to-[#565d6b]"
                  delayMs={150}
                >
                  {initials}
                </Avatar.Fallback>
              </Avatar.Root>
            </DropdownMenu.Trigger>

            <DropdownMenu.Portal>
              <DropdownMenu.Content
                side="right"
                align="end"
                sideOffset={12}
                className="w-64 rounded-xl bg-white shadow-[0_22px_60px_rgba(17,19,24,0.20)] border border-[rgba(20,22,26,0.09)] text-sm text-[#59606b] p-2 z-[100]"
              >
                <div className="px-2 py-1.5 text-[11px] uppercase tracking-[0.14em] text-[var(--accent-600)] font-bold">
                  {isLocal ? 'Local operator' : 'Signed in'}
                </div>
                <span className="block text-[#68707b] px-2 pb-2 truncate">
                  {accountEmail}
                </span>
                <DropdownMenu.Item asChild className="outline-none">
                  <Link
                    href="/"
                    className="block w-full p-2 text-left rounded-md hover:bg-[rgba(17,19,24,0.05)] active:bg-[rgba(17,19,24,0.1)] duration-150 cursor-pointer no-underline text-[#313740]"
                  >
                    Spaces
                  </Link>
                </DropdownMenu.Item>
                <DropdownMenu.Item asChild className="outline-none">
                  <Link
                    href="/settings"
                    className="block w-full p-2 text-left rounded-md hover:bg-[rgba(17,19,24,0.05)] active:bg-[rgba(17,19,24,0.1)] duration-150 cursor-pointer no-underline text-[#313740]"
                  >
                    Settings
                  </Link>
                </DropdownMenu.Item>
                <DropdownMenu.Separator className="my-1 h-px bg-[rgba(20,22,26,0.09)]" />
                {versionInfo?.behind && versionInfo?.latest ? (
                  <DropdownMenu.Item asChild className="outline-none">
                    <Link
                      href="/"
                      className="flex items-center justify-between gap-x-2 w-full p-2 text-left rounded-md hover:bg-[rgba(17,19,24,0.05)] active:bg-[rgba(17,19,24,0.1)] duration-150 cursor-pointer no-underline text-[#313740]"
                    >
                      <span className="flex items-center gap-x-2">
                        <ArrowUpCircle className="w-4 h-4 text-[var(--accent-600)]" strokeWidth={1.75} />
                        Update available
                      </span>
                      <span className="text-[11px] font-semibold text-[var(--accent-600)]">v{versionInfo.latest}</span>
                    </Link>
                  </DropdownMenu.Item>
                ) : (
                  <div className="flex items-center justify-between px-2 py-2 text-[12px] text-[#9aa1ab]">
                    <span>Version</span>
                    <span className="font-medium text-[#68707b]">
                      {versionInfo?.current ? `v${versionInfo.current}` : '—'}
                    </span>
                  </div>
                )}
                <DropdownMenu.Separator className="my-1 h-px bg-[rgba(20,22,26,0.09)]" />
                {isLocal ? (
                  <DropdownMenu.Item asChild className="outline-none">
                    <Link
                      href="/settings/account"
                      className="flex items-center gap-x-2 w-full p-2 text-left rounded-md hover:bg-[rgba(17,19,24,0.05)] active:bg-[rgba(17,19,24,0.1)] duration-150 cursor-pointer no-underline text-[#313740]"
                    >
                      <LogIn className="w-4 h-4" strokeWidth={1.75} />
                      Sign in with an account
                    </Link>
                  </DropdownMenu.Item>
                ) : (
                  <DropdownMenu.Item asChild className="outline-none">
                    <button
                      type="button"
                      onClick={signOut}
                      className="flex items-center gap-x-2 w-full p-2 text-left rounded-md hover:bg-[rgba(17,19,24,0.05)] active:bg-[rgba(17,19,24,0.1)] duration-150 cursor-pointer text-[#313740]"
                    >
                      <LogOut className="w-4 h-4" strokeWidth={1.75} />
                      Sign out
                    </button>
                  </DropdownMenu.Item>
                )}
              </DropdownMenu.Content>
            </DropdownMenu.Portal>
          </DropdownMenu.Root>
        </div>
      </div>
    </aside>
  );
}
