'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { LayoutDashboard, Users, Ship, Anchor, Menu } from 'lucide-react';

import { cn } from '@/lib/utils';

type TabSpec = {
  label: string;
  icon: typeof LayoutDashboard;
  segment: string; // route segment after /[portSlug]/
};

const TABS: TabSpec[] = [
  { label: 'Dashboard', icon: LayoutDashboard, segment: 'dashboard' },
  { label: 'Clients', icon: Users, segment: 'clients' },
  { label: 'Yachts', icon: Ship, segment: 'yachts' },
  { label: 'Berths', icon: Anchor, segment: 'berths' },
];

export function MobileBottomTabs({ onMoreClick }: { onMoreClick: () => void }) {
  const pathname = usePathname();

  // Derive the active port slug from the URL so tab links always target the
  // current port, even after a port-switch. The dashboard route shape is
  // /[portSlug]/<rest>, so the slug is the first non-empty path segment.
  const portSlug = pathname.split('/').filter(Boolean)[0] ?? 'port-nimara';

  function isActive(segment: string): boolean {
    return pathname.startsWith(`/${portSlug}/${segment}`);
  }

  return (
    <nav
      aria-label="Primary navigation"
      className={cn(
        'fixed bottom-0 inset-x-0 z-40 bg-background border-t border-border',
        'pb-safe-bottom',
        'grid grid-cols-5',
      )}
    >
      {TABS.map((tab) => {
        const active = isActive(tab.segment);
        const Icon = tab.icon;
        return (
          <Link
            key={tab.segment}
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            href={`/${portSlug}/${tab.segment}` as any}
            aria-current={active ? 'page' : undefined}
            className={cn(
              'flex flex-col items-center justify-center gap-0.5 h-14 text-xs',
              active ? 'text-primary' : 'text-muted-foreground',
            )}
          >
            <Icon className="size-5" aria-hidden />
            <span className="font-medium">{tab.label}</span>
          </Link>
        );
      })}
      <button
        type="button"
        onClick={onMoreClick}
        className="flex flex-col items-center justify-center gap-0.5 h-14 text-xs text-muted-foreground"
      >
        <Menu className="size-5" aria-hidden />
        <span className="font-medium">More</span>
      </button>
    </nav>
  );
}
