'use client';

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

interface MobileCategoryNavProps {
  onNavigate: () => void;
}

export default function MobileCategoryNav({ onNavigate }: MobileCategoryNavProps) {
  const { localizeHref } = useSalesChannel();
  const catHref = (c: Parameters<typeof getCategoryUrl>[0]) =>
    localizeHref(getCategoryUrl(c));
  const [categories, setCategories] = useState<ShopwareCategory[]>([]);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());

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

        const excludeIds = new Set<string>();
        for (const item of [...(footerNav || []), ...(serviceNav || [])]) {
          if ((item as any).parentId) excludeIds.add((item as any).parentId);
        }

        setCategories((mainNav || []).filter((c) => !excludeIds.has(c.id)));
      } catch (e) {
        console.error('Failed to load mobile nav:', e);
      }
    }
    load();
  }, []);

  const toggleExpanded = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

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

  return (
    <div className="border-t border-surface-100">
      <p className="text-xs font-semibold text-surface-400 uppercase tracking-wider px-2 pt-3 pb-2">
        Categories
      </p>
      {categories.map((cat) => {
        const name = cat.translated?.name || cat.name;
        const hasChildren = cat.children && cat.children.length > 0;
        const isExpanded = expandedIds.has(cat.id);

        return (
          <div key={cat.id}>
            <div className="flex items-center justify-between">
              <Link
                href={catHref(cat)}
                onClick={onNavigate}
                className="flex-1 py-3 px-2 text-surface-600 hover:text-surface-900 text-sm font-medium"
              >
                {name}
              </Link>
              {hasChildren && (
                <button
                  onClick={() => toggleExpanded(cat.id)}
                  className="p-3 text-surface-400"
                >
                  <svg
                    className={`w-4 h-4 transition-transform ${isExpanded ? '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 && isExpanded && (
              <div className="pl-4 pb-2">
                {cat.children!.map((child) => (
                  <Link
                    key={child.id}
                    href={catHref(child)}
                    onClick={onNavigate}
                    className="block py-2 px-2 text-sm text-surface-500 hover:text-surface-800 transition-colors"
                  >
                    {child.translated?.name || child.name}
                  </Link>
                ))}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
