'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useCart } from '@/lib/cart-context';
import { useAuth } from '@/lib/auth-context';
import { useWishlist } from '@/lib/wishlist-context';
import { useSalesChannel } from '@/lib/sales-channel-context';
import type { ThemeLogo, ShopwareCategory } from '@/lib/shopware-api';
import SearchBar from '@/components/ui/SearchBar';
import CategoryNav from '@/components/layout/CategoryNav';
import MobileCategoryNav from '@/components/layout/MobileCategoryNav';

interface HeaderProps {
  // Server-fetched main navigation, forwarded to CategoryNav for instant
  // first paint (see app/layout.tsx).
  initialCategories?: ShopwareCategory[];
}

export default function Header({ initialCategories = [] }: HeaderProps) {
  const { itemCount, toggleCart } = useCart();
  const { isLoggedIn, customer } = useAuth();
  const { itemCount: wishlistCount, isWishlistEnabled } = useWishlist();
  const { localizeHref } = useSalesChannel();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [themeLogo, setThemeLogo] = useState<ThemeLogo>({});

  const storeName = process.env.NEXT_PUBLIC_STORE_NAME || 'ReactWare';
  const logoUrl = process.env.NEXT_PUBLIC_LOGO_URL || null;

  // Get theme logos from environment variables
  // (Store API doesn't expose theme data for security reasons)
  useEffect(() => {
    const logos: ThemeLogo = {
      desktop: process.env.NEXT_PUBLIC_LOGO_DESKTOP || null,
      tablet: process.env.NEXT_PUBLIC_LOGO_TABLET || null,
      mobile: process.env.NEXT_PUBLIC_LOGO_MOBILE || null,
    };
    
    console.log('Environment variables:', {
      desktop: process.env.NEXT_PUBLIC_LOGO_DESKTOP ? '✓ Set' : '✗ Not set',
      tablet: process.env.NEXT_PUBLIC_LOGO_TABLET ? '✓ Set' : '✗ Not set',
      mobile: process.env.NEXT_PUBLIC_LOGO_MOBILE ? '✓ Set' : '✗ Not set',
      fallbackUrl: process.env.NEXT_PUBLIC_LOGO_URL ? '✓ Set' : '✗ Not set',
    });
    
    if (logos.desktop || logos.tablet || logos.mobile) {
      setThemeLogo(logos);
      console.log('Theme logos loaded from environment variables:', logos);
    } else {
      console.warn('No theme logos found in environment variables. Set NEXT_PUBLIC_LOGO_DESKTOP, NEXT_PUBLIC_LOGO_TABLET, and/or NEXT_PUBLIC_LOGO_MOBILE');
    }
  }, []);

  // ── Logo ──────────────────────────────────────────────────────────────────
  const logo = (
    <Link href={localizeHref('/')} className="flex items-center min-w-0">
      {/* Mobile logo */}
      {themeLogo.mobile ? (
        <Image
          src={themeLogo.mobile}
          alt={storeName}
          width={120}
          height={40}
          className="md:hidden h-8 w-auto object-contain"
          priority
        />
      ) : null}

      {/* Tablet logo (md breakpoint) */}
      {themeLogo.tablet ? (
        <Image
          src={themeLogo.tablet}
          alt={storeName}
          width={140}
          height={45}
          className="hidden md:block lg:hidden h-9 w-auto object-contain"
          priority
        />
      ) : null}

      {/* Desktop logo (lg breakpoint and up) */}
      {themeLogo.desktop ? (
        <Image
          src={themeLogo.desktop}
          alt={storeName}
          width={160}
          height={48}
          className="hidden lg:block h-10 w-auto object-contain"
          priority
        />
      ) : null}

      {/* Fallback: use NEXT_PUBLIC_LOGO_URL if theme logos not available */}
      {!themeLogo.mobile && !themeLogo.tablet && !themeLogo.desktop && logoUrl ? (
        <Image
          src={logoUrl}
          alt={storeName}
          width={160}
          height={48}
          className="h-9 md:h-10 w-auto object-contain"
          priority
        />
      ) : null}

      {/* Final fallback: show store name as text */}
      {!themeLogo.mobile && !themeLogo.tablet && !themeLogo.desktop && !logoUrl ? (
        <span className="text-xl font-bold whitespace-nowrap" style={{ color: 'var(--color-primary)' }}>
          {storeName}
        </span>
      ) : null}
    </Link>
  );

  // ── Action icons (search / wishlist / account / cart) ───────────────────────
  const actions = (
    <>
      <SearchBar />

      {isWishlistEnabled && (
        <Link
          href={localizeHref('/wishlist')}
          className="relative p-2 text-surface-600 hover:text-surface-900 transition-colors"
          aria-label="Wishlist"
          title="Wishlist"
        >
          <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z"
            />
          </svg>
          {wishlistCount > 0 && (
            <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold w-5 h-5 flex items-center justify-center rounded-full">
              {wishlistCount}
            </span>
          )}
        </Link>
      )}

      <Link
        href={localizeHref(isLoggedIn ? '/account' : '/account/login')}
        className="relative p-2 text-surface-600 hover:text-surface-900 transition-colors"
        aria-label={isLoggedIn ? 'My Account' : 'Login'}
        title={isLoggedIn ? `Hi, ${customer?.firstName}` : 'Login / Register'}
      >
        <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={1.5}
            d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
          />
        </svg>
        {isLoggedIn && (
          <span className="absolute top-1 right-1 w-2.5 h-2.5 bg-green-500 rounded-full border-2 border-white" />
        )}
      </Link>

      <button
        onClick={toggleCart}
        className="relative p-2 text-surface-600 hover:text-surface-900 transition-colors"
        aria-label="Shopping cart"
      >
        <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={1.5}
            d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"
          />
        </svg>
        {itemCount > 0 && (
          <span className="absolute -top-1 -right-1 bg-brand-500 text-white text-xs font-bold w-5 h-5 flex items-center justify-center rounded-full">
            {itemCount}
          </span>
        )}
      </button>
    </>
  );

  // ── Hamburger toggle (mobile only) ──────────────────────────────────────────
  const hamburger = (
    <button
      onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
      className="p-2 -ml-2 text-surface-600"
      aria-label="Menu"
      aria-expanded={isMobileMenuOpen}
    >
      <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        {isMobileMenuOpen ? (
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
        ) : (
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
        )}
      </svg>
    </button>
  );

  return (
    <header className="sticky top-0 z-50 bg-white/95 backdrop-blur-md border-b border-surface-100">
      <div className="relative max-w-7xl mx-auto px-6">
        {/* ── Desktop: single row ─────────────────────────────────────────── */}
        <div className="hidden md:flex items-center justify-between h-16">
          {logo}
          <div className="flex items-center gap-2">
            <CategoryNav initialCategories={initialCategories} />
          </div>
          <div className="flex items-center gap-3 shrink-0">{actions}</div>
        </div>

        {/* ── Mobile: centered logo row + nav row ──────────────────────────── */}
        <div className="md:hidden">
          <div className="flex items-center justify-center h-14">{logo}</div>
          <div className="flex items-center justify-between h-12 border-t border-surface-100">
            {hamburger}
            <div className="flex items-center gap-1">{actions}</div>
          </div>
        </div>

        {isMobileMenuOpen && (
          <nav className="md:hidden absolute left-0 right-0 top-full z-50 bg-white border-t border-surface-100 shadow-lg px-6 pb-4 max-h-[80vh] overflow-y-auto animate-fade-in">
            <Link
              href={localizeHref(isLoggedIn ? '/account' : '/account/login')}
              onClick={() => setIsMobileMenuOpen(false)}
              className="block py-3 text-surface-600 hover:text-surface-900 text-sm font-medium"
            >
              {isLoggedIn ? `My Account (${customer?.firstName})` : 'Login / Register'}
            </Link>

            <MobileCategoryNav onNavigate={() => setIsMobileMenuOpen(false)} />
          </nav>
        )}
      </div>
    </header>
  );
}
