// Backend content is fetched only when a request arrives.
export const dynamic = 'force-dynamic';

import Link from 'next/link';
import type { Metadata } from 'next';
import { paths } from '@justice-choice/seo-engine';
import { api } from '@/lib/api';
import { fmtNumber } from '@/lib/format';
import { pageMetadata } from '@/lib/meta';
import type { SeoMeta } from '@/lib/types';
import { Breadcrumbs } from '@/components/Breadcrumbs';
import { Faq } from '@/components/Faq';
import { Section } from '@/components/Section';
import { ArrowRightIcon, BookOpenIcon, LayersIcon, MapPinIcon, PracticeAreaIcon, TrendingUpIcon } from '@/components/Icons';

type Data = {
  practiceArea: { id: number; name: string; slug: string; description: string | null; guidance: string | null; faqs: { q: string; a: string }[] };
  parent: { name: string; slug: string } | null;
  children: { name: string; slug: string }[];
  cities: { id: number; name: string; slug: string; country: string; country_slug: string; lawyers: number; verified: number; eligible: boolean; path: string }[];
  seo: SeoMeta | null;
};
type Props = { params: Promise<{ slug: string }> };
const load = (slug: string) => api<Data>(`/practice-areas/${encodeURIComponent(slug)}`);

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const d = await load(slug);
  return pageMetadata(d.seo, { path: paths.practiceArea(slug), title: `${d.practiceArea.name} lawyers` });
}

export default async function PracticeAreaPage({ params }: Props) {
  const { slug } = await params;
  const d = await load(slug);
  const pa = d.practiceArea;
  const byCountry = d.cities.reduce<Record<string, Data['cities']>>((acc, c) => ((acc[c.country] ??= []).push(c), acc), {});
  return (
    <div className="mx-auto max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
      <Breadcrumbs
        items={[
          { label: 'Home', href: '/' },
          { label: 'Practice areas', href: '/practice-areas/' },
          ...(d.parent ? [{ label: d.parent.name, href: paths.practiceArea(d.parent.slug) }] : []),
          { label: pa.name, href: paths.practiceArea(pa.slug) },
        ]}
      />
      <header className="mt-6 flex flex-col gap-5 sm:flex-row sm:items-start">
        <span className="grid h-16 w-16 shrink-0 place-items-center rounded-2xl bg-ledger text-ledger-ink shadow-md">
          <PracticeAreaIcon slug={pa.slug} className="h-8 w-8" />
        </span>
        <div className="max-w-3xl">
          <h1 className="font-serif text-[2.25rem] font-semibold leading-[1.1] tracking-tight sm:text-[2.75rem]">{pa.name} lawyers</h1>
          {pa.description && <p className="mt-3 text-lg leading-relaxed text-ink-2">{pa.description}</p>}
          <p className="num mt-3 text-sm text-muted">
            Ranked in {d.cities.length} {d.cities.length === 1 ? 'city' : 'cities'} across {Object.keys(byCountry).length} {Object.keys(byCountry).length === 1 ? 'country' : 'countries'}
          </p>
        </div>
      </header>
      <div className="mt-10 grid gap-12 lg:grid-cols-[1.3fr_1fr]">
        <Section title="Rankings by city" icon={<TrendingUpIcon className="h-4 w-4" />}>
          {Object.entries(byCountry).map(([country, cities]) => (
            <div key={country} className="mb-6">
              <h3 className="mb-2 text-xs font-bold uppercase tracking-[0.08em] text-muted">{country}</h3>
              <ul className="card divide-y divide-rule overflow-hidden">
                {cities.map((c) => (
                  <li key={c.path}>
                    <Link href={c.path} className="group flex items-center gap-3 px-4 py-3 transition-colors hover:bg-paper">
                      <MapPinIcon className="h-4 w-4 text-muted group-hover:text-ledger" />
                      <span className="flex-1 font-medium group-hover:text-ledger">
                        {pa.name} lawyers in {c.name}
                      </span>
                      <span className="num text-sm text-muted">{fmtNumber(c.lawyers)}</span>
                      <ArrowRightIcon className="h-4 w-4 text-muted opacity-0 transition-all group-hover:translate-x-0.5 group-hover:text-ledger group-hover:opacity-100" />
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          ))}
          {!d.cities.length && <p className="card p-5 text-ink-2">No city rankings for {pa.name.toLowerCase()} yet.</p>}
        </Section>
        <div className="space-y-10">
          {pa.guidance && (
            <Section title={`Choosing a ${pa.name.toLowerCase()} lawyer`} icon={<BookOpenIcon className="h-4 w-4" />}>
              <div className="card p-5">
                <p className="leading-relaxed text-ink-2">{pa.guidance}</p>
              </div>
            </Section>
          )}
          {d.children.length > 0 && (
            <Section title="Specialisms" icon={<LayersIcon className="h-4 w-4" />}>
              <ul className="flex flex-wrap gap-2">
                {d.children.map((c) => (
                  <li key={c.slug}>
                    <Link href={paths.practiceArea(c.slug)} className="chip">
                      <PracticeAreaIcon slug={c.slug} className="h-3.5 w-3.5 text-ledger" />
                      {c.name}
                    </Link>
                  </li>
                ))}
              </ul>
            </Section>
          )}
        </div>
      </div>
      <div className="mt-14">
        <Faq items={pa.faqs} />
      </div>
    </div>
  );
}
