'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAuthStore } from '@/stores/auth-store';
import { cn } from '@horux/shared-ui';
import { Building2, UserCheck, Users } from 'lucide-react';

interface NavItem {
  href: string;
  label: string;
  icon: React.ElementType;
  roles: string[];
}

const PLATFORM_SUPERSET = new Set(['platform_admin', 'platform_ti']);

const ITEMS: NavItem[] = [
  { href: '/despachos/contribuyentes', label: 'Contribuyentes', icon: Building2, roles: ['owner', 'cfo'] },
  { href: '/despachos/mis-asignados', label: 'Mis asignados', icon: UserCheck, roles: ['owner', 'cfo', 'supervisor', 'auxiliar', 'contador', 'visor'] },
  { href: '/despachos/equipo', label: 'Equipo', icon: Users, roles: ['owner', 'cfo', 'supervisor'] },
];

export function DespachoSubnav() {
  const pathname = usePathname();
  const role = useAuthStore(s => s.user?.role);
  const platformRoles = useAuthStore(s => s.user?.platformRoles);
  const isPlatformStaff = platformRoles?.some(r => PLATFORM_SUPERSET.has(r)) ?? false;
  if (!role) return null;
  const visibles = ITEMS.filter(i => isPlatformStaff || i.roles.includes(role));
  return (
    <div className="flex border-b mb-6">
      {visibles.map(item => {
        const active = pathname === item.href || pathname.startsWith(`${item.href}/`);
        const Icon = item.icon;
        return (
          <Link
            key={item.href}
            href={item.href}
            className={cn(
              'flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors',
              active
                ? 'border-primary text-primary'
                : 'border-transparent text-muted-foreground hover:text-foreground',
            )}
          >
            <Icon className="h-4 w-4" />
            {item.label}
          </Link>
        );
      })}
    </div>
  );
}

/** Resuelve la página default según rol al entrar a /despachos. */
export function defaultDespachoPathForRole(role: string, platformRoles?: string[]): string {
  const isPlatformStaff = platformRoles?.some(r => PLATFORM_SUPERSET.has(r)) ?? false;
  if (isPlatformStaff) return '/despachos/contribuyentes';
  if (role === 'owner' || role === 'cfo') return '/despachos/contribuyentes';
  if (role === 'supervisor' || role === 'auxiliar') return '/despachos/mis-asignados';
  return '/despachos/contribuyentes';
}
