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

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

function flatten(cats: Category[]): Category[] {
  const flat: Category[] = []
  const walk = (list: Category[]) => list.forEach((c) => { flat.push(c); if (c.children) walk(c.children) })
  walk(cats)
  return flat
}

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const flat = flatten(await getTree())
  const cat = flat.find((c) => String(c.slug) === params.slug || String(c.id) === params.slug)
  return {
    title: cat?.name ?? 'Category',
    description: `Shop ${cat?.name ?? 'products'} online at Fitorza — authentic products from verified sellers.`,
    alternates: { canonical: `/category/${params.slug}` },
    openGraph: {
      title: `${cat?.name ?? 'Shop'} · Fitorza`,
      description: `Shop ${cat?.name ?? 'products'} online at Fitorza — authentic products from verified sellers.`,
      type: 'website',
      url: `/category/${params.slug}`,
    },
  }
}

export default async function CategoryPage({ params }: { params: { slug: string } }) {
  const tree = await getTree()
  const flat = flatten(tree)
  const cat = flat.find((c) => String(c.slug) === params.slug || String(c.id) === params.slug)
  const children = cat?.children ?? flat.filter((c) => c.parent_id === cat?.id)
  const query = cat ? `?category_id=${cat.id}` : `?q=${encodeURIComponent(params.slug)}`

  return (
    <div className="container-x py-6">
      <nav className="mb-4 flex flex-wrap items-center gap-1.5 text-[13px] text-accent">
        <Link href="/" className="hover:underline">Home</Link>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m9 18 6-6-6-6" /></svg>
        <Link href="/categories" className="hover:underline">Categories</Link>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m9 18 6-6-6-6" /></svg>
        <span className="font-semibold">{cat?.name ?? params.slug.replace(/-/g, ' ')}</span>
      </nav>
      <h1 className="mb-5 text-2xl font-medium capitalize text-ink">{cat?.name ?? params.slug.replace(/-/g, ' ')}</h1>

      {children.length > 0 && (
        <div className="mb-6 flex flex-wrap gap-2.5">
          {children.map((ch) => (
            <Link key={ch.id} href={`/category/${ch.slug ?? ch.id}`} className="rounded-lg border border-hair bg-white px-4 py-2 text-[13px] font-medium text-ink hover:border-brand hover:text-brand">{ch.name}</Link>
          ))}
        </div>
      )}

      <CatalogBrowser baseQuery={query} />
    </div>
  )
}
