import Link from 'next/link'
import { serverGet } from '@/lib/api'
import type { Category, Brand } from '@/lib/types'

export const metadata = {
  title: 'All Categories',
  description: 'Shop by category — medicines, nutrition, personal care, devices, baby & mother care and more on Fitorza.',
  alternates: { canonical: '/categories' },
}

async function getCategories(): Promise<Category[]> {
  try { const r = await serverGet<{ data: Category[] } | Category[]>('/categories', 3600); return (r as { data?: Category[] }).data ?? (r as Category[]) } catch { return [] }
}
async function getBrands(): Promise<Brand[]> {
  try { const r = await serverGet<{ data: Brand[] } | Brand[]>('/brands', 3600); return (r as { data?: Brand[] }).data ?? (r as Brand[]) } catch { return [] }
}

function CatTile({ c }: { c: Category }) {
  return (
    <Link href={`/category/${c.slug ?? c.id}`} className="card card-hover flex h-full flex-col items-center gap-2.5 p-4 text-center">
      <div className="flex h-16 w-16 items-center justify-center overflow-hidden rounded-2xl bg-brand-tint">
        {c.image ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={c.image} alt={c.name} className="h-full w-full object-cover" loading="lazy" />
        ) : (
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" className="text-brand-strong"><rect x="3" y="3" width="18" height="18" rx="3" /><path d="M3 9h18" /></svg>
        )}
      </div>
      <span className="text-[12.5px] font-medium leading-tight">{c.name}</span>
    </Link>
  )
}

export default async function CategoriesPage() {
  const [categories, brands] = await Promise.all([getCategories(), getBrands()])
  // "Shop by concern" = second-level categories (conditions live one level down in a deep tree).
  const concerns: Category[] = []
  categories.forEach((c) => (c.children ?? []).forEach((ch) => concerns.push(ch)))

  return (
    <div className="container-x py-8">
      <h1 className="h-section">Shop by category</h1>

      <div className="mt-6 grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8">
        {categories.length === 0 ? <div className="col-span-full card p-12 text-center text-muted">Categories will appear here.</div> :
          categories.map((c) => <CatTile key={c.id} c={c} />)}
      </div>

      {concerns.length > 0 && (
        <section className="mt-10">
          <h2 className="h-card mb-4">Shop by concern</h2>
          <div className="flex flex-wrap gap-2">
            {concerns.slice(0, 24).map((c) => (
              <Link key={c.id} href={`/category/${c.slug ?? c.id}`} className="rounded-full border border-hair bg-white px-4 py-2 text-[13px] hover:border-brand hover:text-brand-strong">{c.name}</Link>
            ))}
          </div>
        </section>
      )}

      {brands.length > 0 && (
        <section className="mt-10">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="h-card">Popular brands</h2>
            <Link href="/brands" className="text-[13px] text-brand-strong hover:underline">View all</Link>
          </div>
          <div className="grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8">
            {brands.slice(0, 16).map((b) => (
              <Link key={b.id} href={`/brands/${b.slug ?? b.id}`} className="card card-hover flex h-20 items-center justify-center p-3">
                {b.logo ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={b.logo} alt={b.name} className="max-h-full max-w-full object-contain" loading="lazy" />
                ) : (
                  <span className="text-center text-[12px] font-medium text-muted">{b.name}</span>
                )}
              </Link>
            ))}
          </div>
        </section>
      )}
    </div>
  )
}
