import { headers } from "next/headers";
import Link from "next/link";
import Image from "next/image";
import { storefrontApi } from "@/lib/api";
import { getLocaleFromCookie, getTranslations } from "@/lib/i18n";
import { categoryDisplayName, resolveMediaUrl } from "@/lib/utils";
import type { Category } from "@/types";

export const revalidate = 300;

function getCategoryPlaceholderIcon(categoryName: string) {
  const name = categoryName.toLowerCase();
  
  if (name.includes("electronics") || name.includes("إلكترونيات")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
      </svg>
    );
  }
  
  if (name.includes("fashion") || name.includes("clothing") || name.includes("apparel") || name.includes("ملابس") || name.includes("أزياء")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
      </svg>
    );
  }
  
  if (name.includes("food") || name.includes("grocery") || name.includes("طعام") || name.includes("بقالة")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
      </svg>
    );
  }
  
  if (name.includes("book") || name.includes("كتب")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
      </svg>
    );
  }
  
  if (name.includes("home") || name.includes("furniture") || name.includes("منزل") || name.includes("أثاث")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
      </svg>
    );
  }
  
  if (name.includes("sport") || name.includes("fitness") || name.includes("رياضة")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    );
  }
  
  if (name.includes("beauty") || name.includes("cosmetic") || name.includes("جمال") || name.includes("تجميل")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z" />
      </svg>
    );
  }
  
  if (name.includes("toy") || name.includes("kids") || name.includes("children") || name.includes("ألعاب") || name.includes("أطفال")) {
    return (
      <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    );
  }
  
  return (
    <svg className="w-16 h-16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
    </svg>
  );
}

export default async function CategoriesPage() {
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "default";
  const cookieHeader = headersList.get("cookie") ?? "";
  const locale = getLocaleFromCookie(cookieHeader);
  const t = getTranslations(locale);

  let categories: Category[] = [];

  try {
    const res = await storefrontApi.getCategories(tenantSlug);
    categories = (res.categories ?? []).filter(
      (cat) => cat.product_count && cat.product_count > 0
    );
  } catch {
    // fall through to empty state
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-10">
        <nav className="breadcrumb mb-3">
          <Link href="/">{t.common.home}</Link>
          <span className="breadcrumb-separator">
            <svg
              className="w-3 h-3"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
            </svg>
          </span>
          <span className="text-gray-900 font-medium">{t.nav.categories}</span>
        </nav>

        <div className="mb-8 lg:mb-10">
          <h1 className="section-heading">
            {t.categories.title}
          </h1>
          <p className="section-subheading">
            {t.categories.shopByCategory}
          </p>
        </div>

        {categories.length === 0 ? (
          <div className="text-center py-20 lg:py-32 bg-white rounded-xl border border-gray-200">
            <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-6">
              <svg
                className="w-10 h-10 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.5}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
                />
              </svg>
            </div>
            <h3 className="text-lg font-bold text-gray-900 mb-2">
              {t.categories.noCategories}
            </h3>
            <p className="text-sm text-gray-500 mb-8">
              {t.categories.browseAll}
            </p>
            <Link
              href="/products"
              className="btn-refined btn-refined-primary inline-flex"
            >
              {t.nav.products}
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-5 lg:gap-6">
            {categories.map((cat) => (
              <Link
                key={cat.id}
                href={`/categories/${cat.id}`}
                className="group bg-white rounded-xl border border-gray-200 overflow-hidden card-hover-lift"
              >
                <div className="aspect-square relative overflow-hidden bg-gray-50">
                  {resolveMediaUrl(cat.image_url) ? (
                    <Image
                      src={resolveMediaUrl(cat.image_url)!}
                      alt={categoryDisplayName(cat, locale)}
                      fill
                      className="object-cover group-hover:scale-105 transition-transform duration-500"
                      sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 20vw"
                    />
                  ) : (
                    <div
                      className="w-full h-full flex flex-col items-center justify-center relative gap-3"
                      style={{
                        background: `linear-gradient(135deg, color-mix(in srgb, var(--color-primary) 12%, white), color-mix(in srgb, var(--color-secondary) 8%, white))`,
                      }}
                    >
                      <div className="opacity-30" style={{ color: "var(--color-primary)" }}>
                        {getCategoryPlaceholderIcon(categoryDisplayName(cat, locale))}
                      </div>
                      <p className="text-xs font-semibold text-gray-500 opacity-60">
                        {categoryDisplayName(cat, locale)}
                      </p>
                    </div>
                  )}
                </div>
                <div className="p-4 text-center">
                  <p
                    className="text-sm font-semibold text-gray-900 group-hover:text-gray-700 transition-colors line-clamp-2 leading-snug mb-1"
                    dir={locale?.startsWith("ar") ? "rtl" : undefined}
                  >
                    {categoryDisplayName(cat, locale)}
                  </p>
                  {cat.product_count !== undefined && (
                    <p className="text-xs text-gray-500 font-medium">
                      {cat.product_count} {t.categories.items}
                    </p>
                  )}
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
