'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { getNavigation, getCategoryUrl, ShopwareCategory } from '@/lib/shopware-api';
import { useSalesChannel } from '@/lib/sales-channel-context';

interface CategoryNavProps {
  // Navigation fetched on the server (in the root layout) so the nav ships in
  // the SSR HTML and paints with the rest of the page — no post-hydration
  // fetch, no skeleton flash. Empty array → fall back to client fetch below.
  initialCategories?: ShopwareCategory[];
}

export default function CategoryNav({ initialCategories = [] }: CategoryNavProps) {
  const { localizeHref } = useSalesChannel();
  const catHref = (c: Parameters<typeof getCategoryUrl>[0]) =>
    localizeHref(getCategoryUrl(c));
  const [categories, setCategories] = useState<ShopwareCategory[]>(initialCategories);
  const [loading, setLoading] = useState(initialCategories.length === 0);
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Server already supplied the nav (and a language switch does a full reload,
    // re-rendering it server-side), so there's nothing to fetch on the client.
    if (initialCategories.length > 0) return;

    async function loadCategories() {
      try {
        const [mainNav, footerNav, serviceNav] = await Promise.all([
          getNavigation('main-navigation', 3),
          getNavigation('footer-navigation', 1).catch(() => []),
          getNavigation('service-navigation', 1).catch(() => []),
        ]);

        // Collect root IDs of footer/service navigations so we can exclude them
        // from the main nav (Shopware sometimes puts them as siblings in the tree).
        const excludeIds = new Set<string>();
        for (const item of [...(footerNav || []), ...(serviceNav || [])]) {
          if ((item as any).parentId) excludeIds.add((item as any).parentId);
        }

        const filtered = (mainNav || []).filter((c) => !excludeIds.has(c.id));
        setCategories(filtered);
      } catch (e) {
        console.error('Failed to load navigation:', e);
      } finally {
        setLoading(false);
      }
    }
    loadCategories();
  }, [initialCategories.length]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setOpenDropdown(null);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  if (loading) {
    return (
      <div className="flex items-center gap-6">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-4 w-16 bg-surface-100 rounded animate-pulse" />
        ))}
      </div>
    );
  }

  if (categories.length === 0) {
    return null;
  }

  return (
    <nav className="flex items-center gap-1" ref={dropdownRef}>
      {categories.map((category) => {
        const name = category.translated?.name || category.name;
        const hasChildren = category.children && category.children.length > 0;
        const isOpen = openDropdown === category.id;

        return (
          <div key={category.id} className="relative">
                <div className="flex items-center">
              <Link
                href={catHref(category)}
                className="text-sm font-medium text-surface-600 hover:text-surface-900 transition-colors px-3 py-2 rounded-lg hover:bg-surface-50"
                onClick={() => setOpenDropdown(null)}
              >
                {name}
              </Link>
              {hasChildren && (
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    setOpenDropdown(isOpen ? null : category.id);
                  }}
                  className="p-1.5 text-surface-500 hover:text-surface-700 transition-colors -ml-1"
                  aria-label={`Toggle ${name} submenu`}
                >
                  <svg
                    className={`w-3.5 h-3.5 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>
              )}
            </div>

            {hasChildren && isOpen && (
              <div className="absolute top-full left-0 mt-1 w-56 bg-white rounded-xl shadow-lg border border-surface-100 py-2 z-50 animate-fade-in">
                <Link
                  href={catHref(category)}
                  onClick={() => setOpenDropdown(null)}
                  className="block px-4 py-2.5 text-sm font-semibold text-brand-600 hover:bg-brand-50 transition-colors border-b border-surface-100 mb-1"
                >
                  All {name}
                </Link>

                {category.children!.map((child) => {
                  const childName = child.translated?.name || child.name;
                  const hasGrandChildren = child.children && child.children.length > 0;

                  return (
                    <div key={child.id} className="group">
                      <Link
                        href={catHref(child)}
                        onClick={() => setOpenDropdown(null)}
                        className="flex items-center justify-between px-4 py-2.5 text-sm text-surface-600 hover:text-surface-900 hover:bg-surface-50 transition-colors"
                      >
                        <span>{childName}</span>
                        {hasGrandChildren && (
                          <svg className="w-3.5 h-3.5 text-surface-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                          </svg>
                        )}
                      </Link>

                      {hasGrandChildren && (
                        <div className="hidden group-hover:block absolute left-full top-0 ml-0.5 w-52 bg-white rounded-xl shadow-lg border border-surface-100 py-2">
                          <Link
                            href={catHref(child)}
                            onClick={() => setOpenDropdown(null)}
                            className="block px-4 py-2.5 text-sm font-semibold text-brand-600 hover:bg-brand-50 transition-colors border-b border-surface-100 mb-1"
                          >
                            All {childName}
                          </Link>
                          {child.children!.map((grandChild) => (
                            <Link
                              key={grandChild.id}
                              href={catHref(grandChild)}
                              onClick={() => setOpenDropdown(null)}
                              className="block px-4 py-2.5 text-sm text-surface-600 hover:text-surface-900 hover:bg-surface-50 transition-colors"
                            >
                              {grandChild.translated?.name || grandChild.name}
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
    </nav>
  );
}
