'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import {
  CalendarCheck,
  Heart,
  Bookmark,
  MapPin,
  UserCircle,
  Sparkles,
  Bell,
  Wallet,
  LogOut,
  Globe,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuthStore } from '@/lib/store/auth';
import { authApi, clearToken } from '@/lib/auth';

const NAV_ITEMS = [
  { href: '/me/bookings', key: 'bookings', icon: CalendarCheck },
  { href: '/me/wishlist', key: 'wishlist', icon: Heart },
  { href: '/me/saved-vendors', key: 'saved_vendors', icon: Bookmark },
  { href: '/me/addresses', key: 'addresses', icon: MapPin },
  { href: '/me/profile', key: 'profile', icon: UserCircle },
  { href: '/me/loyalty', key: 'loyalty', icon: Sparkles },
  { href: '/me/wallet', key: 'wallet', icon: Wallet },
  { href: '/me/notifications', key: 'notifications', icon: Bell },
];

function useLogout(locale: string) {
  const router = useRouter();
  const reset = useAuthStore((s) => s.reset);
  return async () => {
    try { await authApi.logout(); } catch { /* clear regardless */ }
    await clearToken();
    reset();
    router.push(`/${locale}`);
    router.refresh();
  };
}

/** Horizontal scrollable tab strip — mobile only (md:hidden) */
export function MeMobileNav({ locale }: { locale: string }) {
  const t = useTranslations('me.nav');
  const tNav = useTranslations('nav');
  const tAccount = useTranslations('account.menu');
  const pathname = usePathname() ?? '';
  const router = useRouter();
  const onLogout = useLogout(locale);

  const otherLocale = locale === 'ar' ? 'en' : 'ar';
  const switchLang = () => {
    const switched = pathname.replace(/^\/[a-z]{2}(\/|$)/, `/${otherLocale}$1`);
    router.push(switched + (typeof window !== 'undefined' ? window.location.search : ''));
  };

  return (
    <nav
      aria-label="Account navigation"
      className="md:hidden border-b border-neutral-100 bg-white overflow-x-auto"
    >
      <ul className="flex gap-1 px-4 py-2 min-w-max">
        {NAV_ITEMS.map((item) => {
          const Icon = item.icon;
          const href = `/${locale}${item.href}`;
          const isActive = pathname === href || pathname.startsWith(`${href}/`);
          return (
            <li key={item.key}>
              <Link
                href={href}
                className={cn(
                  'flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium whitespace-nowrap transition-colors',
                  isActive
                    ? 'bg-primary-50 text-primary-700'
                    : 'text-neutral-600 hover:bg-neutral-50',
                )}
              >
                <Icon className="h-3.5 w-3.5 flex-shrink-0" aria-hidden />
                {t(item.key)}
              </Link>
            </li>
          );
        })}

        {/* Feature 054 — US12: language switch + logout parity on mobile */}
        <li className="ms-1 border-s border-neutral-200 ps-1">
          <button
            type="button"
            onClick={switchLang}
            className="flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium whitespace-nowrap text-neutral-600 transition-colors hover:bg-neutral-50"
          >
            <Globe className="h-3.5 w-3.5 flex-shrink-0" aria-hidden />
            {tAccount('language_switch')}
          </button>
        </li>
        <li>
          <button
            type="button"
            onClick={onLogout}
            className="flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium whitespace-nowrap text-danger transition-colors hover:bg-danger/10"
          >
            <LogOut className="h-3.5 w-3.5 flex-shrink-0" aria-hidden />
            {tNav('logout')}
          </button>
        </li>
      </ul>
    </nav>
  );
}

/** Vertical sidebar — desktop only (rendered inside the grid) */
export function MeSidebar({ locale }: { locale: string }) {
  const t = useTranslations('me.nav');
  const tNav = useTranslations('nav');
  const pathname = usePathname() ?? '';
  const onLogout = useLogout(locale);

  return (
    <nav className="rounded-lg border border-neutral-200 bg-white p-2 text-sm">
      <ul className="space-y-1">
        {NAV_ITEMS.map((item) => {
          const Icon = item.icon;
          const href = `/${locale}${item.href}`;
          const isActive = pathname === href || pathname.startsWith(`${href}/`);
          return (
            <li key={item.key}>
              <Link
                href={href}
                className={cn(
                  'flex items-center gap-2 rounded-md px-3 py-2',
                  isActive ? 'bg-primary-50 text-primary-700' : 'text-neutral-700 hover:bg-neutral-50',
                )}
              >
                <Icon className="h-4 w-4" />
                {t(item.key)}
              </Link>
            </li>
          );
        })}
      </ul>
      <div className="mt-2 border-t border-neutral-100 pt-2">
        <button
          type="button"
          onClick={onLogout}
          className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm text-danger hover:bg-danger/10"
        >
          <LogOut className="h-4 w-4" />
          {tNav('logout')}
        </button>
      </div>
    </nav>
  );
}
