'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 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'] },
  { href: '/despachos/equipo', label: 'Equipo', icon: Users, roles: ['owner', 'cfo', 'supervisor'] },
];

export function DespachoSubnav() {
  const pathname = usePathname();
  const role = useAuthStore(s => s.user?.role);
  if (!role) return null;
  const visibles = ITEMS.filter(i => 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): string {
  if (role === 'owner' || role === 'cfo') return '/despachos/contribuyentes';
  if (role === 'supervisor' || role === 'auxiliar') return '/despachos/mis-asignados';
  return '/despachos/mis-asignados';
}
