//  File:    page.tsx
//  Path:    apps/web/app/ranking/page.tsx
//  Project: AI Risk Index — airiskindex.io
//  Author:  Simon-Pierre Boucher
//  Contact: contact@spboucher.ai
//  Copyright © 2026 Simon-Pierre Boucher. All rights reserved.
//
//  Description: Full index — every scored occupation ranked, paginated by 50.

import Link from "next/link";
import { prisma } from "@airiskindex/db";
import { ScoreBar } from "@/components/score-marks";
import { formatWage } from "@/lib/soc-groups";

export const dynamic = "force-dynamic";

export const metadata = {
  title: "Full index — AI Risk Index",
  description: "Every scored occupation ranked by substitution pressure, with confidence intervals.",
};

const PER_PAGE = 50;

export default async function RankingPage({
  searchParams,
}: {
  searchParams: { page?: string };
}): Promise<JSX.Element> {
  const run = await prisma.scoreRun.findFirst({ orderBy: { createdAt: "desc" } });
  const total = run ? await prisma.occupationScore.count({ where: { runId: run.id } }) : 0;
  const pages = Math.max(1, Math.ceil(total / PER_PAGE));
  const page = Math.min(pages, Math.max(1, Number(searchParams.page ?? "1") || 1));

  const rows = run
    ? await prisma.occupationScore.findMany({
        where: { runId: run.id },
        orderBy: { substitution: "desc" },
        skip: (page - 1) * PER_PAGE,
        take: PER_PAGE,
        include: {
          occupation: {
            select: { code: true, title: true, medianWageCents: true, employment: true },
          },
        },
      })
    : [];

  const pager = (
    <div className="flex flex-wrap items-center justify-between gap-3 text-sm">
      <div className="flex gap-2">
        <Link
          href={`/ranking?page=${page - 1}`}
          aria-disabled={page <= 1}
          className={`card px-4 py-2 font-medium ${page <= 1 ? "pointer-events-none opacity-40" : "card-hover"}`}
        >
          ← Previous
        </Link>
        <Link
          href={`/ranking?page=${page + 1}`}
          aria-disabled={page >= pages}
          className={`card px-4 py-2 font-medium ${page >= pages ? "pointer-events-none opacity-40" : "card-hover"}`}
        >
          Next →
        </Link>
      </div>
      <p className="text-[var(--muted)]">
        Page {page} / {pages} · ranks {(page - 1) * PER_PAGE + 1}–
        {Math.min(total, page * PER_PAGE)} of {total.toLocaleString("en-US")}
      </p>
    </div>
  );

  return (
    <main className="mx-auto max-w-4xl px-4 py-10 sm:px-6 sm:py-14">
      <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[var(--muted)]">
        Full index{run ? ` · run ${run.indexVersion} · ${run.createdAt.toISOString().slice(0, 10)}` : ""}
      </p>
      <h1 className="mt-2 text-3xl font-bold tracking-tight sm:text-4xl">
        All {total.toLocaleString("en-US")} scored occupations
      </h1>
      <p className="mt-3 max-w-2xl text-[var(--ink-2)]">
        Ranked by composite substitution pressure (0–100). The whisker is the confidence interval
        from rater disagreement. Wages are U.S. national medians (BLS OEWS).
      </p>

      <div className="mt-8">{pager}</div>

      <ol className="card mt-4 overflow-hidden">
        {rows.map((row, index) => {
          const rank = (page - 1) * PER_PAGE + index + 1;
          const wage = formatWage(row.occupation.medianWageCents);
          return (
            <li key={row.occupationCode} className="border-b border-[var(--grid)] last:border-b-0">
              <Link
                href={`/occupations/${row.occupationCode}`}
                className="block px-4 py-3.5 transition-colors hover:bg-[var(--wash)] sm:px-5"
              >
                <div className="flex items-baseline gap-3">
                  <span className="w-8 shrink-0 text-right text-sm tabular-nums text-[var(--muted)]">
                    {rank}
                  </span>
                  <span className="min-w-0 truncate font-medium">{row.occupation.title}</span>
                  <span className="ml-auto shrink-0 pl-3 text-sm font-semibold tabular-nums">
                    {row.substitution.toFixed(0)}
                  </span>
                </div>
                <div className="mt-2 pl-11">
                  <ScoreBar
                    band={{
                      low: row.substitutionLow,
                      score: row.substitution,
                      high: row.substitutionHigh,
                    }}
                    thick={8}
                  />
                  <p className="mt-1.5 text-xs text-[var(--muted)]">
                    CI {row.substitutionLow.toFixed(0)}–{row.substitutionHigh.toFixed(0)} ·
                    exposure {row.exposure.toFixed(0)} · augmentation{" "}
                    {row.augmentation.toFixed(0)}
                    {wage && <> · {wage}</>}
                    {row.occupation.employment != null && (
                      <> · {row.occupation.employment.toLocaleString("en-US")} employed</>
                    )}
                  </p>
                </div>
              </Link>
            </li>
          );
        })}
      </ol>

      <div className="mt-4">{pager}</div>
    </main>
  );
}
