// 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 { fmtDate, fmtNumber } from '@/lib/format';
import { pageMetadata } from '@/lib/meta';
import { abs } from '@/lib/site';
import type { FirmPage } from '@/lib/types';
import { Breadcrumbs } from '@/components/Breadcrumbs';
import { JsonLd } from '@/components/JsonLd';
import { LawyerListItem } from '@/components/LawyerItems';
import { ReportForm } from '@/components/ReportForm';
import { Section } from '@/components/Section';
import { VerificationBadge } from '@/components/Badges';
import { Beacon } from '@/components/Beacon';
import { SaveButton } from '@/components/AccountWidgets';
import { BuildingIcon, CalendarIcon, GlobeIcon, MailIcon, MapPinIcon, PhoneIcon, PracticeAreaIcon, ScaleIcon, UsersIcon } from '@/components/Icons';

type Props = { params: Promise<{ slug: string }> };
const load = (slug: string) => api<FirmPage>(`/law-firms/${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.firm(slug), title: d.firm.name, description: d.firm.description ?? undefined });
}

export default async function FirmProfile({ params }: Props) {
  const { slug } = await params;
  const d = await load(slug);
  const f = d.firm;
  const facts = [
    { Icon: UsersIcon, label: 'Lawyers listed', value: fmtNumber(d.lawyers.length), num: true },
    f.foundedYear ? { Icon: CalendarIcon, label: 'Founded', value: String(f.foundedYear), num: true } : null,
    f.address ? { Icon: MapPinIcon, label: 'Main office', value: `${f.address}${d.city ? `, ${d.city.name}` : ''}` } : null,
    f.phone ? { Icon: PhoneIcon, label: 'Phone', value: f.phone, num: true, href: `tel:${f.phone.replace(/[^\d+]/g, '')}` } : null,
  ].filter(Boolean) as { Icon: typeof UsersIcon; label: string; value: string; num?: boolean; href?: string }[];

  return (
    <div className="mx-auto max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
      <Beacon event="page_view" entityType="firm" entityId={f.id} />
      <Breadcrumbs
        items={[
          { label: 'Home', href: '/' },
          ...(d.city ? [{ label: d.city.name, href: paths.city(d.city.country.slug, d.city.slug) }] : []),
          { label: f.name, href: paths.firm(f.slug) },
        ]}
      />
      <header className="card mt-6 p-6 sm:p-8">
        <div className="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-soft text-ledger">
            <BuildingIcon className="h-8 w-8" />
          </span>
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-center gap-3">
              <h1 className="font-serif text-3xl font-semibold tracking-tight sm:text-4xl">{f.name}</h1>
              <VerificationBadge status={f.verificationStatus} compact />
            </div>
            {f.description && <p className="mt-3 max-w-3xl text-lg leading-relaxed text-ink-2">{f.description}</p>}
          </div>
        </div>
        <dl className="mt-6 grid gap-4 border-t border-rule pt-6 text-sm sm:grid-cols-2 lg:grid-cols-4">
          {facts.map(({ Icon, label, value, num, href }) => (
            <div key={label} className="flex items-start gap-2.5">
              <Icon className="mt-0.5 h-4 w-4 text-muted" />
              <div className="flex min-w-0 flex-col-reverse">
                <dt className="text-xs text-muted">{label}</dt>
                <dd className={`font-semibold ${num ? 'num' : ''}`}>
                  {href ? (
                    <a href={href} className="hover:text-ledger hover:underline">
                      {value}
                    </a>
                  ) : (
                    value
                  )}
                </dd>
              </div>
            </div>
          ))}
        </dl>
        {(f.websiteUrl || f.email) && (
          <div className="mt-6 flex flex-wrap gap-2">
            {f.websiteUrl && (
              <a href={f.websiteUrl} target="_blank" rel="noopener nofollow" className="btn btn-primary">
                <GlobeIcon className="h-4 w-4" /> Visit firm website
              </a>
            )}
            {f.email && (
              <a href={`mailto:${f.email}`} className="btn btn-quiet">
                <MailIcon className="h-4 w-4" /> Email the firm
              </a>
            )}
          </div>
        )}
        <div className="mt-3">
          <SaveButton kind="firms" slug={f.slug} name={f.name} />
        </div>
      </header>
      <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_18rem]">
        <Section title="Lawyers" icon={<UsersIcon className="h-4 w-4" />} aside={<span className="num text-sm text-muted">{fmtNumber(d.lawyers.length)} listed</span>}>
          {d.lawyers.length ? (
            <ul>
              {d.lawyers.map((l) => (
                <LawyerListItem key={l.id} l={l} />
              ))}
            </ul>
          ) : (
            <p className="card p-5 text-ink-2">No published lawyer profiles are linked to this firm yet.</p>
          )}
        </Section>
        <aside className="space-y-10">
          {d.practiceAreas.length > 0 && (
            <Section title="Practice areas" icon={<ScaleIcon className="h-4 w-4" />}>
              <ul className="card divide-y divide-rule overflow-hidden text-sm">
                {d.practiceAreas.map((a) => (
                  <li key={a.slug}>
                    <Link href={paths.practiceArea(a.slug)} className="group flex items-center gap-2.5 px-4 py-2.5 transition-colors hover:bg-paper">
                      <PracticeAreaIcon slug={a.slug} className="h-4 w-4 text-muted group-hover:text-ledger" />
                      <span className="flex-1 group-hover:text-ledger">{a.name}</span>
                      <span className="num text-muted">{a.lawyers}</span>
                    </Link>
                  </li>
                ))}
              </ul>
            </Section>
          )}
          {!!d.publicOffices?.length && (
            <Section title="Office details" icon={<MapPinIcon className="h-4 w-4" />}>
              <ul className="card divide-y divide-rule text-sm">
                {d.publicOffices.map((o) => (
                  <li key={o.id} className="space-y-1 p-4">
                    <p className="font-semibold">{o.name}</p>
                    <p>{[o.address, o.city, o.region, o.postal_code].filter(Boolean).join(', ')}</p>
                    {o.phone && <p>{o.phone}</p>}
                    {o.email && <a href={`mailto:${o.email}`} className="text-ledger">{o.email}</a>}
                    <p className="text-xs text-muted">{o.lawyers} published lawyers in this city</p>
                  </li>
                ))}
              </ul>
            </Section>
          )}
          {d.offices.length > 0 && (
            <Section title="Offices" icon={<MapPinIcon className="h-4 w-4" />}>
              <ul className="flex flex-wrap gap-2">
                {d.offices.map((o) => (
                  <li key={o.path}>
                    <Link href={o.path} className="chip">
                      <MapPinIcon className="h-3.5 w-3.5 text-muted" />
                      {o.city} <span className="num text-xs text-muted">{o.lawyers}</span>
                    </Link>
                  </li>
                ))}
              </ul>
            </Section>
          )}
          <div className="text-sm text-muted">
            <p className="mb-3 inline-flex items-center gap-1.5">
              <CalendarIcon className="h-4 w-4" /> Profile updated {fmtDate(f.updatedAt)}.
            </p>
            <ReportForm entityType="firm" entityId={f.id} />
          </div>
        </aside>
      </div>
      <JsonLd
        data={{
          '@context': 'https://schema.org',
          '@type': 'LegalService',
          name: f.name,
          url: abs(paths.firm(f.slug)),
          ...(f.description ? { description: f.description } : {}),
          ...(f.address && d.city ? { address: { '@type': 'PostalAddress', streetAddress: f.address, addressLocality: d.city.name, addressCountry: d.city.country.iso2 } } : {}),
          ...(f.foundedYear ? { foundingDate: String(f.foundedYear) } : {}),
        }}
      />
    </div>
  );
}
