'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';

export type AppNavIcon =
  | 'leads'
  | 'precios'
  | 'galeria'
  | 'empresa'
  | 'opiniones'
  | 'resumen'
  | 'usuarios'
  | 'planes';

export type AppNavLink = { href: string; label: string; icon: AppNavIcon };

// El enlace activo es el href más específico (más largo) que prefija el pathname.
function activeHref(pathname: string, links: readonly AppNavLink[]): string {
  let best = '';
  for (const l of links) {
    if ((pathname === l.href || pathname.startsWith(l.href + '/')) && l.href.length > best.length) {
      best = l.href;
    }
  }
  return best;
}

const ICON_PATHS: Record<AppNavIcon | 'salir', React.ReactNode> = {
  leads: (
    <>
      <path d="M3 4h18v12H6l-3 3V4Z" />
      <path d="M7 9h10M7 12h6" />
    </>
  ),
  precios: (
    <>
      <path d="M20 12 12.5 4.5A2 2 0 0 0 11 4H5a1 1 0 0 0-1 1v6a2 2 0 0 0 .6 1.4L12 20l8-8Z" />
      <circle cx="8.5" cy="8.5" r="1.2" />
    </>
  ),
  galeria: (
    <>
      <rect x="3" y="3" width="18" height="18" rx="2" />
      <circle cx="8.5" cy="8.5" r="1.5" />
      <path d="m21 15-5-5L5 21" />
    </>
  ),
  empresa: (
    <>
      <path d="M4 21V6l8-3 8 3v15" />
      <path d="M4 21h16M9 21v-5h6v5M8 9h.01M12 9h.01M16 9h.01M8 13h.01M12 13h.01M16 13h.01" />
    </>
  ),
  opiniones: (
    <>
      <path d="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" />
    </>
  ),
  resumen: (
    <>
      <rect x="3" y="3" width="7" height="9" rx="1" />
      <rect x="14" y="3" width="7" height="5" rx="1" />
      <rect x="14" y="12" width="7" height="9" rx="1" />
      <rect x="3" y="16" width="7" height="5" rx="1" />
    </>
  ),
  usuarios: (
    <>
      <circle cx="9" cy="8" r="3" />
      <path d="M3.5 20a5.5 5.5 0 0 1 11 0" />
      <path d="M16 5.5a3 3 0 0 1 0 5.5M17 14.5a5.5 5.5 0 0 1 3.5 5" />
    </>
  ),
  planes: (
    <>
      <path d="M12 3 3 8l9 5 9-5-9-5Z" />
      <path d="M3 13l9 5 9-5M3 18l9 5 9-5" />
    </>
  ),
  salir: (
    <>
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
      <path d="M16 17l5-5-5-5M21 12H9" />
    </>
  ),
};

function Icon({ name }: { name: AppNavIcon | 'salir' }) {
  return (
    <svg
      width="22"
      height="22"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {ICON_PATHS[name]}
    </svg>
  );
}

export default function AppNav({ links }: { links: readonly AppNavLink[] }) {
  const pathname = usePathname();
  const active = activeHref(pathname, links);

  return (
    <>
      {/* Escritorio: navegación horizontal en la cabecera */}
      <nav className="hidden sm:flex items-center gap-4 text-xs font-medium">
        {links.map((l) => (
          <Link
            key={l.href}
            href={l.href}
            className={active === l.href ? 'text-primary-700 font-semibold' : 'text-gray-500 hover:text-primary-700'}
          >
            {l.label}
          </Link>
        ))}
        <form action="/logout" method="post">
          <button type="submit" className="text-gray-500 hover:text-primary-700">
            Salir
          </button>
        </form>
      </nav>

      {/* Móvil: barra de pestañas fija inferior (thumb-friendly) */}
      <nav
        className="sm:hidden fixed inset-x-0 bottom-0 z-30 border-t border-gray-200 bg-white/95 backdrop-blur supports-[backdrop-filter]:bg-white/80"
        style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
        aria-label="Navegación principal"
      >
        <div
          className="grid"
          style={{ gridTemplateColumns: `repeat(${links.length + 1}, minmax(0, 1fr))` }}
        >
          {links.map((l) => {
            const isActive = active === l.href;
            return (
              <Link
                key={l.href}
                href={l.href}
                aria-current={isActive ? 'page' : undefined}
                className={
                  'relative flex flex-col items-center justify-center gap-1 pt-2.5 pb-2 text-[11px] font-medium transition-colors ' +
                  (isActive ? 'text-primary-700' : 'text-gray-400 hover:text-gray-600')
                }
              >
                {isActive && (
                  <span className="absolute top-0 h-0.5 w-8 rounded-full bg-primary-700" aria-hidden="true" />
                )}
                <Icon name={l.icon} />
                <span className="leading-none">{l.label}</span>
              </Link>
            );
          })}
          <form action="/logout" method="post" className="contents">
            <button
              type="submit"
              className="flex flex-col items-center justify-center gap-1 pt-2.5 pb-2 text-[11px] font-medium text-gray-400 transition-colors hover:text-gray-600"
            >
              <Icon name="salir" />
              <span className="leading-none">Salir</span>
            </button>
          </form>
        </div>
      </nav>
    </>
  );
}
