'use client'

import { useState } from 'react'
import ProductCard from '@/components/frontend/ProductCard'
import type { CatalogProduct } from '@/lib/db/queries/getProductCatalog'

export interface ProductTab {
  key: string
  label: string
  products: CatalogProduct[]
}

// Tab switching only — every tab's products were already fetched server-side
// (ProductTabs.tsx), so switching is instant and each list is in the HTML.
export default function ProductTabsClient({ tabs, ariaLabel }: { tabs: ProductTab[]; ariaLabel: string }) {
  const [active, setActive] = useState(tabs[0]?.key)
  const current = tabs.find((t) => t.key === active) ?? tabs[0]
  if (!current) return null

  return (
    <div>
      {tabs.length > 1 && (
        <div role="tablist" aria-label={ariaLabel} className="mb-6 flex gap-2 overflow-x-auto pb-1 [scrollbar-width:none]">
          {tabs.map((tab) => {
            const selected = tab.key === current.key
            return (
              <button
                key={tab.key}
                type="button"
                role="tab"
                id={`home-tab-${tab.key}`}
                aria-selected={selected}
                aria-controls={`home-tabpanel-${tab.key}`}
                onClick={() => setActive(tab.key)}
                className={`shrink-0 rounded-full px-5 py-2.5 text-sm font-semibold transition-all duration-300 ${
                  selected
                    ? 'bg-dark text-white shadow-lg shadow-black/10'
                    : 'bg-white text-gray-custom border border-gray-200 hover:border-dark hover:text-dark'
                }`}
              >
                {tab.label}
              </button>
            )
          })}
        </div>
      )}

      {tabs.map((tab) => (
        <div
          key={tab.key}
          id={`home-tabpanel-${tab.key}`}
          role="tabpanel"
          aria-labelledby={`home-tab-${tab.key}`}
          hidden={tab.key !== current.key}
          className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6"
        >
          {tab.products.map((product) => (
            <ProductCard
              key={product.id}
              id={product.id}
              title={product.title}
              price={product.price}
              oldPrice={product.oldPrice}
              rating={product.ratingAverage}
              reviews={product.ratingCount}
              image={product.imageUrl ?? '📦'}
              slug={product.slug}
              productType={product.type}
              brand={product.brand}
            />
          ))}
        </div>
      ))}
    </div>
  )
}
