'use client';

import Image from 'next/image';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useState } from 'react';
import { ROUTES } from '@/lib/routes';
import { logoutAccount } from '@/app/account/actions';
import type { ApiAccount, ApiSiteSettings } from '@/lib/backend-api';
import { useCart } from '@/lib/cart-context';
import { isVendorAccount } from '@/lib/vendor';
import { DashboardModeSwitcher } from '@/components/layout/dashboard-mode-switcher';

const NAV_LINKS = [
  { label: 'Home', href: ROUTES.home },
  { label: 'Shop', href: ROUTES.shop },
  { label: 'Artisan Marketplace', href: ROUTES.artisans },
  { label: 'Bulk Orders', href: ROUTES.bulkOrders, badge: 'HOT' },
  { label: 'Become a Vendor', href: ROUTES.vendorShow },
  { label: 'About Us', href: ROUTES.about },
  { label: 'Contact Us', href: ROUTES.contact },
];

export function SiteHeader({ account, settings }: { account: ApiAccount | null; settings?: ApiSiteSettings }) {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const { itemCount } = useCart();
  // Falls back to the static logo file whenever Settings hasn't been given
  // a logo (or the feed couldn't be reached) — see src/lib/site-settings.ts.
  // logo-trimmed.png = public/logo.png with its empty margins cropped, so
  // the artwork fills the space instead of ~half of it.
  const logoSrc = settings?.site_logo || '/logo-trimmed.png';
  const siteName = settings?.site_name || 'CeylonHandicrafts.lk';

  return (
    <header className="sticky top-0 z-40 bg-white shadow-sm">
      {/* Top info bar */}
      <div className="hidden bg-navy-800 text-white lg:block">
        <div className="container-page flex h-9 items-center justify-between text-xs">
          <ul className="flex items-center gap-6 text-navy-100">
            <li className="flex items-center gap-1.5"><span aria-hidden="true">&#10003;</span> Authentic Sri Lankan Handicrafts</li>
            <li className="flex items-center gap-1.5"><span aria-hidden="true">&#128666;</span> Islandwide Delivery</li>
            <li className="flex items-center gap-1.5"><span aria-hidden="true">&#128100;</span> Direct Artisan Contact</li>
            <li className="flex items-center gap-1.5"><span aria-hidden="true">&#9742;</span> Customer Support</li>
          </ul>
          <ul className="flex items-center gap-6 font-medium">
            <li><Link href={ROUTES.vendorShow} className="text-gold-400 hover:text-gold-500">Sell With Us</Link></li>
            <li><Link href={ROUTES.bulkOrders} className="text-gold-400 hover:text-gold-500">Bulk Orders</Link></li>
          </ul>
        </div>
      </div>

      {/* Main header: logo, search, icons */}
      <div className="container-page flex h-20 items-center justify-between gap-6">
        <Link href={ROUTES.home} className="flex shrink-0 items-center">
          <Image
            src={logoSrc}
            alt={`${siteName} — Discover the Soul of Sri Lankan Crafts`}
            width={873}
            height={266}
            priority
            unoptimized={logoSrc !== '/logo-trimmed.png'}
            className="h-12 w-auto sm:h-14 lg:h-16"
          />
        </Link>

        <form action={ROUTES.shop} className="hidden flex-1 max-w-xl md:flex">
          <div className="flex w-full rounded-md border border-navy-100 overflow-hidden">
            <input
              type="text"
              name="q"
              placeholder="Search for handicrafts, artisans, products..."
              className="w-full border-0 px-4 py-2.5 text-sm focus:outline-none focus:ring-0"
            />
            <button type="submit" className="flex items-center justify-center bg-gold-500 px-5 text-navy-800 hover:bg-gold-600" aria-label="Search">
              <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth={2.2}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            </button>
          </div>
        </form>

        <div className="flex items-center gap-5 text-navy-800">
          <Link href={ROUTES.wishlist} className="hidden flex-col items-center text-xs sm:flex hover:text-gold-600">
            <svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.8}><path d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6c-2.5 4.5-9.5 9-9.5 9Z"/></svg>
            Wishlist
          </Link>
          {account ? (
            <div className="hidden flex-col items-center text-xs sm:flex">
              <Link href="/account" className="flex flex-col items-center hover:text-gold-600">
                <svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.8}><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 5-6 8-6s6.5 2 8 6"/></svg>
                {account.name.split(' ')[0] || 'My Account'}
              </Link>
              <form action={logoutAccount}>
                <button type="submit" className="mt-0.5 text-[10px] text-navy-400 underline hover:text-gold-600">
                  Sign Out
                </button>
              </form>
            </div>
          ) : (
            <Link href={ROUTES.login} className="hidden flex-col items-center text-xs sm:flex hover:text-gold-600">
              <svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.8}><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 5-6 8-6s6.5 2 8 6"/></svg>
              Sign In / Register
            </Link>
          )}
          <Link href={ROUTES.cart} className="relative hidden flex-col items-center text-xs sm:flex hover:text-gold-600">
            <svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.8}><path d="M3 4h2l2.5 12.5a2 2 0 0 0 2 1.5h7a2 2 0 0 0 2-1.6L21 8H6"/><circle cx="10" cy="20" r="1"/><circle cx="17" cy="20" r="1"/></svg>
            Cart
            {itemCount > 0 && (
              <span className="absolute -right-2 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-gold-500 text-[10px] font-bold text-navy-800">
                {itemCount}
              </span>
            )}
          </Link>

          <button onClick={() => setMobileOpen((open) => !open)} className="lg:hidden" aria-label="Toggle menu">
            <svg viewBox="0 0 24 24" className="h-7 w-7" fill="none" stroke="currentColor" strokeWidth={1.8}><path d="M4 7h16M4 12h16M4 17h16"/></svg>
          </button>
        </div>
      </div>

      {/* Customer/Vendor mode switcher — only for accounts that can act as both */}
      {account && isVendorAccount(account) && <DashboardModeSwitcher />}

      {/* Main nav */}
      <nav className="hidden border-t border-navy-100 bg-white lg:block">
        <div className="container-page flex h-12 items-center gap-8 text-sm font-semibold text-navy-800">
          <Link href={ROUTES.shop} className="flex items-center gap-2 rounded bg-gold-500 px-4 py-2 text-navy-800 hover:bg-gold-600">
            <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth={2}><path d="M4 6h16M4 12h16M4 18h16"/></svg>
            Browse Categories
          </Link>
          {NAV_LINKS.map((link) =>
            link.href === ROUTES.vendorShow ? (
              <Link
                key={link.href}
                href={link.href}
                className={`rounded px-3 py-1.5 tracking-wide ${
                  pathname === link.href
                    ? 'bg-gold-600 text-navy-800'
                    : 'bg-gold-500 text-navy-800 hover:bg-gold-600'
                }`}
              >
                {link.label.toUpperCase()}
              </Link>
            ) : (
              <Link
                key={link.href}
                href={link.href}
                className={`relative flex items-center gap-1.5 py-3 tracking-wide hover:text-gold-600 ${
                  pathname === link.href ? 'text-gold-600' : ''
                }`}
              >
                {link.label.toUpperCase()}
                {link.badge && (
                  <span className="rounded-full bg-red-600 px-1.5 py-0.5 text-[9px] font-bold text-white">{link.badge}</span>
                )}
              </Link>
            )
          )}
        </div>
      </nav>

      {/* Mobile menu */}
      {mobileOpen && (
        <div className="border-t border-navy-100 bg-white lg:hidden">
          <div className="container-page flex flex-col gap-1 py-3 text-sm font-semibold text-navy-800">
            <Link href={ROUTES.shop} className="py-2">Shop</Link>
            <Link href={ROUTES.artisans} className="py-2">Artisan Marketplace</Link>
            <Link href={ROUTES.bulkOrders} className="py-2">Bulk Orders</Link>
            <Link href={ROUTES.vendorShow} className="py-2">Become a Vendor</Link>
            <Link href={ROUTES.about} className="py-2">About Us</Link>
            <Link href={ROUTES.contact} className="py-2">Contact Us</Link>
            {account ? (
              <>
                <Link href="/account" className="py-2">My Account ({account.name.split(' ')[0]})</Link>
                {isVendorAccount(account) && (
                  <div className="flex gap-2 py-2">
                    <span className="text-xs text-navy-400">Viewing as:</span>
                    <Link href={ROUTES.account} className="text-xs font-semibold text-gold-600">Customer</Link>
                    <span className="text-xs text-navy-300">|</span>
                    <Link href={ROUTES.vendorDashboard} className="text-xs font-semibold text-gold-600">Vendor Dashboard</Link>
                  </div>
                )}
                <form action={logoutAccount}>
                  <button type="submit" className="w-full py-2 text-left">Sign Out</button>
                </form>
              </>
            ) : (
              <Link href={ROUTES.login} className="py-2">Sign In / Register</Link>
            )}
            <Link href={ROUTES.wishlist} className="py-2">Wishlist</Link>
            <Link href={ROUTES.cart} className="py-2">Cart{itemCount > 0 ? ` (${itemCount})` : ''}</Link>
          </div>
        </div>
      )}
    </header>
  );
}
