'use client';

import { useState, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
import { isLoggedIn as checkAuth, logout as authLogout, getUser } from '@/lib/auth';
import { api, apiPaths } from '@/lib/api';
import { useI18n } from '@/lib/i18n/context';
import { useSiteFooter, useSiteLogoUrl } from '@/lib/siteFooterContext';
interface NavbarProps {
  activePage?: 'home' | 'store' | 'cart' | 'orders' | 'notifications' | 'profile' | 'settings';
}

/** عند عدم تمرير `activePage` يُستنتج من المسار (للتخطيط العام) */
function deriveActivePageFromPath(
  pathname: string | null
): NavbarProps['activePage'] | undefined {
  if (!pathname) return undefined;
  if (pathname === '/') return 'home';
  if (pathname.startsWith('/store')) return 'store';
  if (pathname.startsWith('/cart') || pathname.startsWith('/checkout')) return 'cart';
  if (pathname.startsWith('/orders')) return 'orders';
  if (pathname.startsWith('/notifications')) return 'notifications';
  if (pathname.startsWith('/profile')) return 'profile';
  if (pathname === '/settings' || pathname.startsWith('/settings/')) return 'settings';
  return undefined;
}

export default function Navbar({ activePage }: NavbarProps) {
  const router = useRouter();
  const pathname = usePathname();
  const effectiveActive = activePage ?? deriveActivePageFromPath(pathname);
  const { t, isRtl, locale, setLocale } = useI18n();
  const { footer: siteFooter } = useSiteFooter();
  const logoUrl = useSiteLogoUrl();
  const siteTitle = useMemo(() => {
    if (!siteFooter) return '';
    const ar = (siteFooter.site_name_ar || siteFooter.brand_name_ar || '').trim();
    const en = (siteFooter.site_name_en || siteFooter.brand_name_en || '').trim();
    if (locale === 'en') return en || ar;
    return ar || en;
  }, [siteFooter, locale]);
  const [langBusy, setLangBusy] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [notifCount, setNotifCount] = useState(0);
  const [userName, setUserName] = useState<string | null>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    const loggedIn = checkAuth();
    setIsLoggedIn(loggedIn);
    if (loggedIn) {
      const u = getUser();
      setUserName(u?.name ?? null);
      api.get<{ count: number }>(apiPaths.user.notificationsCount).then((res) => {
        if (res.key === 'success' && res.data) {
          setNotifCount(res.data.count ?? 0);
        }
      }).catch(() => {});
    }
  }, [mounted, pathname]);

  const handleLogout = async () => {
    await authLogout();
    router.push('/login');
  };

  const isActive = (page: string) => effectiveActive === page;

  /** روابط لوحة المستخدم: نفس أسلوب الزائر (كحلي عند التفعيل) */
  const loggedLinkClass = (page: 'home' | 'store' | 'cart') =>
    isActive(page)
      ? 'text-[#1e3a5f] font-bold bg-sky-100 px-2.5 py-1 rounded-lg shrink-0 text-sm sm:text-base shadow-sm'
      : 'text-gray-700 hover:text-[#1e3a5f] transition-colors whitespace-nowrap shrink-0 text-sm sm:text-base';

  const guestLinkClass = (page: 'home' | 'store' | 'cart') =>
    isActive(page)
      ? 'text-[#1e3a5f] font-bold hover:text-[#1a3254] transition-colors cursor-pointer whitespace-nowrap shrink-0'
      : 'text-gray-700 hover:text-[#1e3a5f] transition-colors cursor-pointer whitespace-nowrap shrink-0';

  const guestSettingsActive =
    pathname === '/settings' || effectiveActive === 'settings';

  if (!mounted) {
    return (
      <nav className="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-50 h-16" />
    );
  }

  return (
    <nav dir={isRtl ? 'rtl' : 'ltr'} className="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-50">
      <div className="w-full px-4 sm:px-6">
        <div className="flex items-center justify-between h-16 gap-2">
          {!isLoggedIn ? (
            <>
              <div className="flex items-center gap-3 md:gap-8 min-w-0 flex-1">
                <Link href="/" className="shrink-0">
                  <div className="relative h-12 w-12 shrink-0 overflow-hidden rounded-full bg-[#1e3a5f] shadow-sm ring-1 ring-black/5">
                    {logoUrl ? (
                      <img
                        src={logoUrl}
                        alt={siteTitle || t('meta.siteTitle')}
                        className="absolute inset-0 size-full rounded-full object-cover object-center"
                      />
                    ) : (
                      <span className="relative z-10 flex h-full w-full items-center justify-center text-sm font-bold text-white">
                        {(siteTitle || t('meta.siteTitle')).slice(0, 2)}
                      </span>
                    )}
                  </div>
                </Link>
                <div className="flex items-center gap-3 sm:gap-5 md:gap-6 overflow-x-auto min-w-0 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
                  <Link href="/" className={`${guestLinkClass('home')} text-sm sm:text-base`}>
                    {t('nav.home')}
                  </Link>
                  <Link href="/store" className={`${guestLinkClass('store')} text-sm sm:text-base`}>
                    {t('nav.store')}
                  </Link>
                  <Link href="/cart" className={`${guestLinkClass('cart')} text-sm sm:text-base`}>
                    {t('nav.cart')}
                  </Link>
                  <Link
                    href="/settings"
                    className={
                      guestSettingsActive
                        ? 'text-[#1e3a5f] font-bold bg-sky-100 px-2.5 py-1 rounded-lg shrink-0 text-sm sm:text-base shadow-sm'
                        : 'text-gray-700 hover:text-[#1e3a5f] transition-colors whitespace-nowrap shrink-0 text-sm sm:text-base'
                    }
                  >
                    {t('settings.title')}
                  </Link>
                </div>
              </div>
              <div className="flex items-center gap-1.5 sm:gap-3 shrink-0">
                <Link
                  href="/store"
                  className="w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center rounded-lg text-gray-600 hover:bg-gray-100 transition-colors"
                  title={t('store.searchProductPlaceholder')}
                >
                  <i className="ri-search-line text-lg sm:text-xl" />
                </Link>
                <button
                  type="button"
                  disabled={langBusy}
                  onClick={() => {
                    setLangBusy(true);
                    void setLocale(locale === 'ar' ? 'en' : 'ar').finally(() => setLangBusy(false));
                  }}
                  className="text-sm font-semibold text-gray-700 hover:text-gray-900 px-1.5 py-1 min-w-[2rem] disabled:opacity-50"
                >
                  {locale === 'ar' ? 'EN' : 'عربي'}
                </button>
                <button
                  type="button"
                  onClick={() => router.push('/login')}
                  className="bg-[#1e3a5f] text-white px-3 sm:px-5 py-2 sm:py-2.5 rounded-xl hover:bg-[#1a3254] transition-colors cursor-pointer whitespace-nowrap text-xs sm:text-sm font-semibold shadow-sm"
                >
                  {t('nav.login')}
                </button>
              </div>
            </>
          ) : (
            <>
              <div className="flex items-center gap-3 md:gap-8 min-w-0 flex-1">
                <Link href="/" className="shrink-0">
                  <div className="relative h-12 w-12 shrink-0 overflow-hidden rounded-full bg-[#1e3a5f] shadow-sm ring-1 ring-black/5">
                    {logoUrl ? (
                      <img
                        src={logoUrl}
                        alt={siteTitle || t('meta.siteTitle')}
                        className="absolute inset-0 size-full rounded-full object-cover object-center"
                      />
                    ) : (
                      <span className="relative z-10 flex h-full w-full items-center justify-center text-sm font-bold text-white">
                        {(siteTitle || t('meta.siteTitle')).slice(0, 2)}
                      </span>
                    )}
                  </div>
                </Link>
                <div className="flex items-center gap-3 sm:gap-5 md:gap-6 overflow-x-auto min-w-0 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
                  <Link href="/" className={loggedLinkClass('home')}>
                    {t('nav.home')}
                  </Link>
                  <Link href="/store" className={loggedLinkClass('store')}>
                    {t('nav.store')}
                  </Link>
                  <Link href="/cart" className={loggedLinkClass('cart')}>
                    {t('nav.cart')}
                  </Link>
                </div>
              </div>

              <div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
                <Link
                  href="/profile"
                  className={`flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-4 py-2 rounded-xl transition-colors cursor-pointer text-sm font-semibold whitespace-nowrap ${isActive('profile') ? 'bg-sky-200 text-[#1e3a5f]' : 'bg-sky-100 text-[#1e3a5f] hover:bg-sky-200'}`}
                >
                  <i className="ri-user-3-fill text-[#1e3a5f] text-lg shrink-0" />
                  <span className="inline max-w-[120px] sm:max-w-[200px] md:max-w-none truncate">
                    {userName ? t('nav.welcomeUser', { name: userName }) : t('nav.welcome')}
                  </span>
                </Link>
                <button
                  type="button"
                  disabled={langBusy}
                  onClick={() => {
                    setLangBusy(true);
                    void setLocale(locale === 'ar' ? 'en' : 'ar').finally(() => setLangBusy(false));
                  }}
                  className="text-sm font-semibold text-gray-700 hover:text-gray-900 px-1.5 py-1 min-w-[2rem] disabled:opacity-50"
                >
                  {locale === 'ar' ? 'EN' : 'عربي'}
                </button>
                <Link
                  href="/store"
                  className="w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center rounded-lg text-gray-600 hover:bg-gray-100 transition-colors"
                  title={t('store.searchProductPlaceholder')}
                >
                  <i className="ri-search-line text-lg sm:text-xl" />
                </Link>
                <Link
                  href="/notifications"
                  className={`relative w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center rounded-lg transition-colors cursor-pointer shrink-0 ${isActive('notifications') ? 'text-[#1e3a5f] bg-sky-100' : 'text-gray-600 hover:text-[#1e3a5f] hover:bg-gray-100'}`}
                >
                  <i className="ri-notification-3-line text-lg sm:text-xl" />
                  {notifCount > 0 && (
                    <span className="absolute -top-0.5 -end-0.5 min-w-[1.15rem] h-[1.15rem] px-0.5 bg-red-500 text-white text-[10px] leading-none rounded-full flex items-center justify-center font-bold">
                      {notifCount > 99 ? '99+' : notifCount}
                    </span>
                  )}
                </Link>
                <button
                  type="button"
                  onClick={handleLogout}
                  className="text-gray-500 hover:text-red-600 transition-colors cursor-pointer p-2 rounded-lg hover:bg-red-50 shrink-0"
                  title={t('nav.logout')}
                >
                  <i className="ri-logout-box-r-line text-lg sm:text-xl" />
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </nav>
  );
}
