'use client';

import { useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Menu as MenuIcon, ShoppingBag, Search, Globe } from 'lucide-react';
import type { Branding, Menu, MenuItem } from '@/types/api';
import { useTranslations } from 'next-intl';
import { MobileDrawer } from './MobileDrawer';
import { AccountMenu } from './AccountMenu';
import { CartBadge } from '@/components/cart/CartBadge';

type Props = { branding: Branding; menu: Menu; mobileDrawer: Menu; locale: string };

function hrefFromItem(item: MenuItem, locale: string): string {
  switch (item.target_type) {
    case 'internal_path':
      return `/${locale}${item.target_value.startsWith('/') ? item.target_value : `/${item.target_value}`}`;
    case 'cms_page':
      return `/${locale}/p/${item.target_value}`;
    case 'category':
      return `/${locale}/c/${item.target_value}`;
    case 'occasion':
      return `/${locale}/o/${item.target_value}`;
    case 'external_url':
    default:
      return item.target_value;
  }
}

export function Header({ branding, menu, mobileDrawer, locale }: Props) {
  const t = useTranslations('nav');
  const [drawerOpen, setDrawerOpen] = useState(false);
  // Feature 054 (US14, C8) — state-driven logo fallback so the wordmark never
  // mounts hidden (no SSR "flash then hide"). The logo is a CMS-provided URL not
  // in next/image remotePatterns, so a plain <img> with state is the safe fix.
  const [logoFailed, setLogoFailed] = useState(false);
  const showLogo = !!branding.assets.logo_light && !logoFailed;
  const otherLocale = locale === 'ar' ? 'en' : 'ar';
  const pathname = usePathname();
  const router = useRouter();

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

  return (
    <header className="sticky top-0 z-40 border-b border-neutral-200 bg-white/95 backdrop-blur-sm">
      <div className="mx-auto flex max-w-7xl items-center gap-3 px-4 py-3">
        {/* Mobile: hamburger | Desktop: hidden */}
        <button
          type="button"
          className="md:hidden p-2 -ms-2 rounded-md hover:bg-neutral-100 transition-colors"
          aria-label={t('menu')}
          onClick={() => setDrawerOpen(true)}
        >
          <MenuIcon className="h-5 w-5 text-neutral-700" />
        </button>

        {/* Logo */}
        <Link href={`/${locale}`} className="flex items-center gap-2 me-auto md:me-0">
          {showLogo ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={branding.assets.logo_light!}
              alt={branding.site_name}
              className="h-8 w-auto"
              onError={() => setLogoFailed(true)}
            />
          ) : (
            <span className="font-heading text-lg font-bold text-primary-700">
              {branding.site_name}
            </span>
          )}
        </Link>

        {/* Desktop: primary nav */}
        <nav className="hidden md:flex items-center gap-6 ms-8">
          {menu.items.map((item) => (
            <Link
              key={item.public_id}
              href={hrefFromItem(item, locale)}
              target={item.opens_in_new_tab ? '_blank' : undefined}
              rel={item.opens_in_new_tab ? 'noreferrer' : undefined}
              className="text-sm font-medium text-neutral-600 hover:text-neutral-900 transition-colors"
            >
              {item.label}
            </Link>
          ))}
        </nav>

        {/* Right utilities */}
        <div className="ms-auto flex items-center gap-0.5">
          {/* Language toggle: always visible */}
          <button
            type="button"
            onClick={handleLangSwitch}
            className="flex items-center gap-1 text-sm font-medium px-2.5 py-1.5 rounded-md text-neutral-600 hover:bg-neutral-100 hover:text-neutral-900 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-1"
            aria-label={t('language')}
          >
            <Globe aria-hidden="true" className="h-4 w-4" />
            {t('language')}
          </button>

          {/* Desktop: Plan event CTA */}
          <Link
            href={`/${locale}/wizard`}
            className="hidden md:inline-flex items-center rounded-md border border-primary-600 text-primary-700 hover:bg-primary-600 hover:text-white px-3 py-1.5 text-sm font-medium transition-colors ms-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-1"
          >
            {t('wizard')}
          </Link>

          {/* Desktop: search and cart */}
          <Link
            href={`/${locale}/search`}
            aria-label={t('search')}
            className="hidden md:flex p-2 rounded-md text-neutral-600 hover:bg-neutral-100 hover:text-neutral-900 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-1"
          >
            <Search className="h-4 w-4" aria-hidden="true" />
          </Link>
          <Link
            href={`/${locale}/cart`}
            aria-label={t('cart')}
            className="relative hidden md:flex p-2 rounded-md text-neutral-600 hover:bg-neutral-100 hover:text-neutral-900 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-1"
          >
            <ShoppingBag className="h-4 w-4" aria-hidden="true" />
            <CartBadge />
          </Link>

          {/* Desktop: account; hidden on mobile (BottomNav covers it) */}
          <span className="hidden md:flex">
            <AccountMenu locale={locale} />
          </span>
        </div>
      </div>

      <MobileDrawer
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        items={(mobileDrawer.items.length ? mobileDrawer : menu).items}
        locale={locale}
        hrefFromItem={hrefFromItem}
      />
    </header>
  );
}
