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

import Link from 'next/link';
import { permanentRedirect } from 'next/navigation';
import type { Metadata } from 'next';
import { paths } from '@justice-choice/seo-engine';
import { SCORE_COMPONENT_LABELS, type ComponentScores, type ScoreComponent } from '@justice-choice/types';
import { api } from '@/lib/api';
import { fmtDate, fmtNumber } from '@/lib/format';
import { pageMetadata } from '@/lib/meta';
import { abs } from '@/lib/site';
import type { LawyerProfile } from '@/lib/types';
import { Breadcrumbs } from '@/components/Breadcrumbs';
import { JsonLd } from '@/components/JsonLd';
import { LeadForm } from '@/components/LeadForm';
import { ReportForm } from '@/components/ReportForm';
import { CompareToggle, SaveButton } from '@/components/AccountWidgets';
import { ReviewForm } from '@/components/ReviewForm';
import { ScoreLedger } from '@/components/ScoreLedger';
import { Section } from '@/components/Section';
import { Monogram, StarRow, Stars, VerificationBadge } from '@/components/Badges';
import { Beacon } from '@/components/Beacon';
import { COMPONENT_COLOR } from '@/components/ledger';
import {
  ArrowRightIcon,
  AwardIcon,
  BadgeCheckIcon,
  BookOpenIcon,
  BuildingIcon,
  CalendarIcon,
  ChartIcon,
  ChevronDownIcon,
  ClockIcon,
  DatabaseIcon,
  FileTextIcon,
  GavelIcon,
  GlobeIcon,
  HistoryIcon,
  InfoIcon,
  LanguagesIcon,
  MapPinIcon,
  MessageIcon,
  PhoneIcon,
  ShieldCheckIcon,
  StarIcon,
  TrendingUpIcon,
  UserIcon,
  ExternalLinkIcon,
} from '@/components/Icons';

type Props = { params: Promise<{ slug: string }> };
const load = (slug: string) => api<LawyerProfile>(`/lawyers/${encodeURIComponent(slug)}`);

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

const SOURCE_TYPE: Record<string, string> = {
  bar_registry: 'Licensing registry',
  court_records: 'Court records',
  review_platform: 'Review source',
  firm_website: 'Firm website',
  self_reported: 'Self-reported',
  editorial: 'Editorial research',
  publication: 'Publication',
};

function HistoryTable({ points }: { points: { date: string; rank: number; cohort: number; score: number; version: string }[] }) {
  if (!points.length) return null;
  const rows = points.slice(0, 6);
  return (
    <div className="card mt-3 max-w-lg overflow-hidden">
      <table className="w-full text-left text-sm">
        <thead className="bg-paper text-xs uppercase tracking-wide text-muted">
          <tr>
            <th className="px-4 py-2.5 font-semibold">Calculated</th>
            <th className="px-4 py-2.5 font-semibold">Position</th>
            <th className="px-4 py-2.5 text-right font-semibold">Score</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-rule">
          {rows.map((p, i) => (
            <tr key={i} className="transition-colors hover:bg-paper">
              <td className="px-4 py-2.5">{fmtDate(p.date)}</td>
              <td className="num px-4 py-2.5">
                <span className="font-semibold">#{p.rank}</span> <span className="text-muted">of {p.cohort}</span>
              </td>
              <td className="num px-4 py-2.5 text-right font-semibold">{p.score.toFixed(1)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default async function LawyerPage({ params }: Props) {
  const { slug } = await params;
  const d = await load(slug);
  if (d.redirectTo) permanentRedirect(d.redirectTo);
  const consent = await api<{ text: string; direct?: string }>('/leads/consent-text', { revalidate: 300 });
  const primary = d.rankings[0];
  const components = primary ? (Object.fromEntries(primary.breakdown.map((b) => [b.component, b.score])) as ComponentScores) : null;
  const weights = primary ? (Object.fromEntries(primary.breakdown.map((b) => [b.component, b.weight])) as ComponentScores) : null;
  const primaryLoc = d.locations.find((l) => l.isPrimary) ?? d.locations[0];
  // Most recent first: sort explicitly rather than trusting API order
  // and collapse repeat runs on the same day that produced the same result
  const seenRuns = new Set<string>();
  const historyFor = primary
    ? d.rankingHistory
        .filter((h) => h.area === primary.practiceArea && h.city === primary.city)
        .sort((a, b) => +new Date(b.date) - +new Date(a.date))
        .filter((h) => {
          const key = `${String(h.date).slice(0, 10)}|${h.rank}|${h.score.toFixed(1)}`;
          return seenRuns.has(key) ? false : (seenRuns.add(key), true);
        })
    : [];
  const firstName = d.name.split(' ')[0];

  return (
    <div className="mx-auto max-w-6xl px-4 py-8 sm:px-6 sm:py-10">
      <Beacon event="profile_view" entityType="lawyer" entityId={d.id} />
      <Breadcrumbs
        items={[
          { label: 'Home', href: '/' },
          ...(primaryLoc ? [{ label: primaryLoc.city, href: paths.city(primaryLoc.countrySlug, primaryLoc.citySlug) }] : []),
          { label: d.name, href: paths.lawyer(d.slug) },
        ]}
      />

      <header className="card mt-6 overflow-hidden">
        <div className="h-20 bg-gradient-to-r from-ledger/15 via-ledger-tint to-brass/15 sm:h-24" aria-hidden />
        <div className="flex flex-col gap-6 px-5 pb-6 sm:flex-row sm:items-end sm:px-8">
          <div className="-mt-12 rounded-full bg-surface p-1.5 shadow-md sm:-mt-14">
            {d.photoUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={d.photoUrl} alt={`Photo of ${d.name}`} width={96} height={96} className="h-24 w-24 rounded-full object-cover" />
            ) : (
              <Monogram name={d.name} size={96} />
            )}
          </div>
          <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">{d.name}</h1>
              <VerificationBadge status={d.verificationStatus} />
            </div>
            <p className="mt-1 text-lg text-ink-2">
              {[d.title, d.firm?.name].filter(Boolean).join(', ') || 'Lawyer'}
              {primaryLoc && (
                <span className="ml-2 inline-flex items-center gap-1 text-base text-muted">
                  <MapPinIcon className="h-4 w-4" />
                  {primaryLoc.city}
                </span>
              )}
            </p>
          </div>
          <div className="flex flex-wrap gap-2 sm:pb-1">
            {d.acceptsLeads && (
              <a href="#contact" className="btn btn-primary">
                <MessageIcon className="h-4 w-4" /> Contact {firstName}
              </a>
            )}
            {d.websiteUrl && (
              <a href={d.websiteUrl} rel="noopener nofollow" target="_blank" className="btn btn-quiet">
                <GlobeIcon className="h-4 w-4" /> Website
              </a>
            )}
            <CompareToggle slug={d.slug} name={d.name} />
            <SaveButton kind="lawyers" slug={d.slug} name={d.name} />
          </div>
        </div>
        <div className="border-t border-rule px-5 py-4 sm:px-8">
          <div className="flex flex-wrap gap-1.5">
            {d.practiceAreas.map((a) => (
              <Link
                key={a.slug}
                href={paths.practiceArea(a.slug)}
                className={`rounded-md px-2.5 py-1 text-sm transition-colors ${a.isPrimary ? 'bg-ledger-soft font-semibold text-ledger hover:bg-ledger hover:text-ledger-ink' : 'bg-sunken text-ink-2 hover:bg-rule hover:text-ink'}`}
              >
                {a.name}
              </Link>
            ))}
          </div>
          <dl className="mt-5 grid grid-cols-2 gap-x-6 gap-y-4 text-sm sm:grid-cols-4">
            {[
              [ClockIcon, 'In practice', <span key="y" className="num">{d.yearsExperience != null ? `${d.yearsExperience} years` : 'Not stated'}</span>],
              [LanguagesIcon, 'Languages', d.languages.join(', ') || '—'],
              [
                StarIcon,
                'Reviews',
                d.reviews.average != null ? (
                  <span key="r" className="inline-flex items-center gap-1.5">
                    <Stars value={d.reviews.average} /> <span className="num font-normal text-muted">({d.reviews.total})</span>
                  </span>
                ) : (
                  'None yet'
                ),
              ],
              [ShieldCheckIcon, 'Last verified', fmtDate(d.lastVerifiedAt)],
            ].map(([Icon, label, value]) => {
              const I = Icon as typeof ClockIcon;
              return (
                <div key={label as string} className="flex items-start gap-2.5">
                  <I 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 as string}</dt>
                    <dd className="font-semibold text-ink">{value as React.ReactNode}</dd>
                  </div>
                </div>
              );
            })}
          </dl>
        </div>
      </header>

      <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_20rem]">
        <div className="min-w-0 space-y-14">
          {d.bio && (
            <Section title="About" icon={<UserIcon className="h-4 w-4" />}>
              <div className="prose-legal leading-relaxed text-ink-2">
                <p>{d.bio}</p>
              </div>
              {d.videoUrl && (
                <a href={d.videoUrl} target="_blank" rel="noopener noreferrer nofollow" className="link mt-3 inline-flex items-center gap-1 text-sm">
                  Watch {firstName}’s introduction video <ExternalLinkIcon className="h-3.5 w-3.5" />
                </a>
              )}
            </Section>
          )}

          <Section title="Rankings" id="rankings" icon={<TrendingUpIcon className="h-4 w-4" />}>
            {d.rankings.length ? (
              <ul className="card divide-y divide-rule overflow-hidden">
                {d.rankings.map((r) => (
                  <li key={r.path}>
                    <Link href={r.path} className="group flex items-center gap-4 px-5 py-3.5 transition-colors hover:bg-paper">
                      <span className="rank-figure w-12 text-3xl">{r.rank}</span>
                      <span className="flex-1 font-medium group-hover:text-ledger">
                        {r.practiceArea} lawyers in {r.city}
                      </span>
                      <span className="num rounded-md bg-sunken px-2 py-0.5 text-sm font-semibold">{r.score.toFixed(1)}</span>
                      <ArrowRightIcon className="h-4 w-4 text-muted transition-all group-hover:translate-x-0.5 group-hover:text-ledger" />
                    </Link>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="card flex items-start gap-2 p-4 text-ink-2">
                <InfoIcon className="mt-1 h-4 w-4 text-muted" /> Not currently ranked. Rankings require an active licence on record.
              </p>
            )}
          </Section>

          {primary && components && (
            <Section
              title="Score ledger"
              id="score"
              icon={<ChartIcon className="h-4 w-4" />}
              aside={
                <span className="text-sm text-muted">
                  {primary.practiceArea} in {primary.city} · ranking <span className="num">{primary.version}</span>
                </span>
              }
            >
              <div className="card p-5">
                <ScoreLedger components={components} weights={weights} total={primary.score} size="lg" label="Score" />
                <p className="mt-3 text-sm leading-relaxed text-ink-2">Each row shows the component score (0–100), its weight and the points it adds. Open a row to see the records it is based on.</p>
              </div>
              <div className="card mt-4 divide-y divide-rule overflow-hidden">
                {primary.breakdown.map((b) => (
                  <details key={b.component} className="group">
                    <summary className="grid list-none grid-cols-[1fr_auto_auto] items-center gap-x-4 gap-y-2 px-5 py-3.5 transition-colors hover:bg-paper group-open:bg-paper sm:grid-cols-[13rem_1fr_5.5rem_3.5rem_1.25rem]">
                      <span className="flex items-center gap-2 font-medium">
                        <span aria-hidden className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm" style={{ background: COMPONENT_COLOR[b.component as ScoreComponent] }} />
                        {SCORE_COMPONENT_LABELS[b.component as ScoreComponent]}
                      </span>
                      <span className="order-last col-span-3 h-1.5 overflow-hidden rounded-full bg-sunken sm:order-none sm:col-span-1">
                        <span className="block h-full rounded-full" style={{ width: `${b.score}%`, background: COMPONENT_COLOR[b.component as ScoreComponent] }} />
                      </span>
                      <span className="num text-right text-sm text-muted">
                        {b.score.toFixed(0)} × {Math.round(b.weight * 100)}%
                      </span>
                      <span className="num hidden text-right font-semibold sm:block">{b.contribution.toFixed(1)}</span>
                      <ChevronDownIcon className="disclosure-chevron h-4 w-4 text-muted" />
                    </summary>
                    <div className="space-y-2 bg-paper px-5 pb-4 pl-9 text-sm">
                      <p className="leading-relaxed text-ink-2">{b.explanation}</p>
                      {b.evidence.length > 0 && (
                        <ul className="space-y-1 text-muted">
                          {b.evidence.slice(0, 8).map((e, i) => (
                            <li key={i} className="flex items-start gap-2">
                              <FileTextIcon className="mt-0.5 h-3.5 w-3.5" />
                              {e.label}
                            </li>
                          ))}
                          {b.evidence.length > 8 && <li className="pl-5 text-xs">+{b.evidence.length - 8} more records</li>}
                        </ul>
                      )}
                    </div>
                  </details>
                ))}
              </div>
              {historyFor.length > 0 && (
                <div className="mt-8">
                  <h3 className="flex items-center gap-2 font-semibold">
                    <HistoryIcon className="h-4 w-4 text-muted" /> Ranking history
                  </h3>
                  <p className="mt-0.5 text-sm text-muted">
                    Position in {primary.practiceArea.toLowerCase()} rankings in {primary.city}, most recent first.
                  </p>
                  <HistoryTable points={historyFor} />
                </div>
              )}
            </Section>
          )}

          <Section title="Licences and qualifications" id="credentials" icon={<BadgeCheckIcon className="h-4 w-4" />}>
            {d.licenses.length ? (
              <div className="card overflow-x-auto">
                <table className="w-full min-w-[36rem] text-left text-sm">
                  <thead className="border-b border-rule bg-paper text-xs uppercase tracking-wide text-muted">
                    <tr>
                      <th className="px-4 py-3 font-semibold">Jurisdiction</th>
                      <th className="px-4 py-3 font-semibold">Issuing body</th>
                      <th className="px-4 py-3 font-semibold">Number</th>
                      <th className="px-4 py-3 font-semibold">Admitted</th>
                      <th className="px-4 py-3 font-semibold">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-rule">
                    {d.licenses.map((l) => (
                      <tr key={l.id} className="align-top transition-colors hover:bg-paper">
                        <td className="px-4 py-3 font-medium">{l.jurisdiction}</td>
                        <td className="px-4 py-3 text-ink-2">{l.issuingBody}</td>
                        <td className="num px-4 py-3">{l.licenseNumber ?? '—'}</td>
                        <td className="num px-4 py-3">{l.admittedYear ?? '—'}</td>
                        <td className="px-4 py-3">
                          <span className={`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-semibold capitalize ${l.status === 'active' ? 'bg-ledger-soft text-ledger' : 'bg-danger-soft text-danger'}`}>
                            <span className="h-1.5 w-1.5 rounded-full bg-current" />
                            {l.status}
                          </span>
                          <span className="mt-1 block text-xs text-muted">{l.verification === 'verified' ? `Verified ${fmtDate(l.verifiedAt)}` : l.verification === 'pending' ? 'Verification pending' : 'Not verified'}</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="card p-4 text-ink-2">No licence on record yet.</p>
            )}
            {d.education.length > 0 && (
              <ul className="mt-5 space-y-2 text-sm">
                {d.education.map((e, i) => (
                  <li key={i} className="flex items-start gap-2.5">
                    <BookOpenIcon className="mt-0.5 h-4 w-4 text-muted" />
                    <span>
                      <span className="font-medium">{e.degree}</span>, {e.institution}
                      {e.graduationYear && <span className="num text-muted"> ({e.graduationYear})</span>}
                      {e.verified && (
                        <span className="ml-2 inline-flex items-center gap-1 text-xs font-semibold text-ledger">
                          <BadgeCheckIcon className="h-3.5 w-3.5" /> verified
                        </span>
                      )}
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </Section>

          {(d.awards.length > 0 || d.trackRecords.length > 0) && (
            <div className="grid gap-10 md:grid-cols-2">
              {d.awards.length > 0 && (
                <Section title="Recognition" icon={<AwardIcon className="h-4 w-4" />}>
                  <ul className="space-y-3 text-sm">
                    {d.awards.map((a, i) => (
                      <li key={i} className="card p-4">
                        <p className="font-medium">
                          {a.name} <span className="num text-muted">({a.year})</span>
                        </p>
                        <p className="mt-0.5 text-muted">{a.issuer}</p>
                        {(a.isPayToPlay || !a.verified) && (
                          <span className={`mt-2 inline-block rounded px-1.5 py-0.5 text-xs font-medium ${a.isPayToPlay ? 'bg-brass-soft text-brass' : 'bg-sunken text-muted'}`}>
                            {a.isPayToPlay ? 'Paid listing — not scored' : 'Unverified'}
                          </span>
                        )}
                      </li>
                    ))}
                  </ul>
                </Section>
              )}
              {d.trackRecords.length > 0 && (
                <Section title="Sourced matters" icon={<GavelIcon className="h-4 w-4" />}>
                  <ul className="space-y-3 text-sm">
                    {d.trackRecords.map((t, i) => (
                      <li key={i} className="card p-4">
                        <p className="font-medium">{t.title}</p>
                        <p className="mt-0.5 text-muted">{[t.forum, t.year, t.practiceArea].filter(Boolean).join(' · ')}</p>
                        {!t.verified && <span className="mt-2 inline-block rounded bg-sunken px-1.5 py-0.5 text-xs font-medium text-muted">Unverified</span>}
                      </li>
                    ))}
                  </ul>
                </Section>
              )}
            </div>
          )}

          <Section title="Reviews" id="reviews" icon={<StarIcon className="h-4 w-4" />} aside={<ReviewForm lawyerId={d.id} lawyerName={firstName} />}>
            {d.reviews.total ? (
              <>
                <div className="card mb-6 flex flex-wrap items-center gap-6 p-5">
                  <div>
                    <p className="num font-serif text-4xl font-semibold leading-none">{d.reviews.average?.toFixed(1) ?? '—'}</p>
                    {d.reviews.average != null && <StarRow value={d.reviews.average} />}
                    <p className="mt-1 text-xs text-muted">{plural(d.reviews.total, 'review')}</p>
                  </div>
                  <ul className="grid flex-1 gap-3 sm:grid-cols-2">
                    {d.reviews.bySource.map((s) => (
                      <li key={s.source} className="rounded-lg bg-paper p-3 text-sm">
                        <p className="font-medium">{s.source}</p>
                        <p className="mt-1 flex flex-wrap items-center gap-x-2 text-ink-2">
                          <Stars value={s.average} /> <span className="text-muted">from {plural(s.count, 'review')}, {s.verified} verified</span>
                        </p>
                      </li>
                    ))}
                  </ul>
                </div>
                <ul className="space-y-4">
                  {d.reviews.latest.map((r) => (
                    <li key={r.id} className="border-b border-rule pb-4 last:border-b-0">
                      <div className="flex flex-wrap items-center gap-3 text-sm">
                        <StarRow value={r.rating} className="h-3.5 w-3.5" />
                        <span className="font-medium text-ink">{r.author ?? 'Client'}</span>
                        <span className="text-muted">{fmtDate(r.date)}</span>
                        <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${r.verified ? 'bg-ledger-soft text-ledger' : 'bg-sunken text-muted'}`}>
                          {r.verified && <BadgeCheckIcon className="h-3 w-3" />}
                          {r.verified ? 'Verified client' : 'Unverified'}
                        </span>
                      </div>
                      {r.text && <p className="mt-2 leading-relaxed text-ink-2">{r.text}</p>}
                    </li>
                  ))}
                </ul>
              </>
            ) : (
              <p className="card flex items-center gap-2 p-4 text-ink-2">
                <StarIcon className="h-4 w-4 text-muted" /> No published reviews yet.
              </p>
            )}
          </Section>

          <Section title="Offices" icon={<BuildingIcon className="h-4 w-4" />}>
            <ul className="grid gap-3 sm:grid-cols-2">
              {d.locations.map((l, i) => (
                <li key={i} className="card flex gap-3 p-4 text-sm">
                  <MapPinIcon className="mt-0.5 h-4 w-4 text-ledger" />
                  <div className="min-w-0">
                    <p className="font-medium">
                      <Link href={paths.city(l.countrySlug, l.citySlug)} className="hover:text-ledger hover:underline">
                        {l.city}
                      </Link>
                      {l.isPrimary && <span className="ml-2 rounded bg-ledger-soft px-1.5 py-0.5 text-xs font-semibold text-ledger">Main office</span>}
                    </p>
                    {l.firm && <p className="text-ink-2">{l.firm}</p>}
                    {l.address && <p className="text-muted">{[l.address, l.postalCode].filter(Boolean).join(', ')}</p>}
                  </div>
                </li>
              ))}
            </ul>
            <div className="mt-4 flex flex-wrap gap-2">
              {d.websiteUrl && (
                <a href={d.websiteUrl} rel="noopener nofollow" target="_blank" className="btn btn-quiet btn-sm">
                  <GlobeIcon className="h-4 w-4" /> Official website
                </a>
              )}
              {d.firm && (
                <Link href={paths.firm(d.firm.slug)} className="btn btn-quiet btn-sm">
                  <BuildingIcon className="h-4 w-4" /> {d.firm.name}
                </Link>
              )}
              {d.phone && (
                <a href={`tel:${d.phone.replace(/[^\d+]/g, '')}`} className="btn btn-quiet btn-sm num">
                  <PhoneIcon className="h-4 w-4" /> {d.phone}
                </a>
              )}
            </div>
          </Section>

          <Section title="Data sources" id="sources" icon={<DatabaseIcon className="h-4 w-4" />}>
            <p className="mb-4 max-w-2xl text-sm leading-relaxed text-ink-2">
              Every fact on this profile is linked to the record it came from. Profile last changed <span className="inline-flex items-center gap-1"><CalendarIcon className="h-3.5 w-3.5" /> {fmtDate(d.updatedAt)}</span>.
            </p>
            <ul className="card divide-y divide-rule overflow-hidden text-sm">
              {d.sources.map((s, i) => (
                <li key={i} className="flex flex-wrap items-center justify-between gap-2 px-4 py-3 transition-colors hover:bg-paper">
                  <span className="flex items-center gap-2">
                    <FileTextIcon className="h-4 w-4 text-muted" />
                    {s.name}
                    <span className="rounded bg-sunken px-1.5 py-0.5 text-xs text-muted">{SOURCE_TYPE[s.type ?? ''] ?? s.type}</span>
                  </span>
                  <span className="num text-muted">{plural(s.records, 'record')}</span>
                </li>
              ))}
            </ul>
            <div className="mt-5">
              <ReportForm entityType="lawyer" entityId={d.id} />
            </div>
          </Section>
        </div>

        <aside className="sticky-panel lead-panel space-y-4 lg:sticky lg:top-[calc(var(--header-h)+1.5rem)] lg:self-start" id="contact">
          {d.acceptsLeads ? (
            <LeadForm
              heading={`Contact ${firstName}`}
              intro="Your message goes to this lawyer only. Expect a reply by email or phone."
              lawyerSlug={d.slug}
              sourcePath={paths.lawyer(d.slug)}
              consentText={consent.direct ?? consent.text}
            />
          ) : (
            <div className="card flex items-start gap-3 p-5 text-sm text-ink-2">
              <InfoIcon className="mt-0.5 h-4 w-4 text-muted" />
              This lawyer is not accepting enquiries through Justice Choice right now.
            </div>
          )}
          <div className="card p-4 text-sm">
            <p className="font-semibold text-ink">Is this you?</p>
            <p className="mt-1 text-xs leading-relaxed text-muted">Claim the profile to correct details and respond to enquiries.</p>
            <Link href={`/claim/${d.slug}/`} rel="nofollow" className="link mt-2 inline-flex items-center gap-1 text-sm">
              Claim this profile <ArrowRightIcon className="h-3.5 w-3.5" />
            </Link>
          </div>
        </aside>
      </div>

      <JsonLd
        data={{
          '@context': 'https://schema.org',
          '@type': 'Person',
          name: d.name,
          jobTitle: d.title ?? 'Lawyer',
          url: abs(paths.lawyer(d.slug)),
          ...(d.firm ? { worksFor: { '@type': 'LegalService', name: d.firm.name, url: abs(paths.firm(d.firm.slug)) } } : {}),
          ...(primaryLoc ? { workLocation: { '@type': 'Place', address: { '@type': 'PostalAddress', addressLocality: primaryLoc.city, addressCountry: primaryLoc.country } } } : {}),
          knowsLanguage: d.languages,
          knowsAbout: d.practiceAreas.map((a) => a.name),
        }}
      />
    </div>
  );
}

function plural(n: number, w: string) {
  return `${fmtNumber(n)} ${n === 1 ? w : `${w}s`}`;
}
