import type { Metadata } from "next";
import Link from "next/link";

import { Container } from "@/components/Container";
import { PageHeader } from "@/components/PageHeader";
import { DraftBanner } from "@/components/consentiq/DraftBanner";
import { ProceduresExplorer } from "@/components/consentiq/ProceduresExplorer";
import {
  listPublishedPublicProcedures,
} from "@/lib/consentiq/queries";
import {
  procedures as staticProcedures,
  allRegions as staticRegions,
} from "@/data/consentiq/procedures";

export const metadata: Metadata = {
  title: "ConsentIQ · Procedure library",
  description:
    "Browse the ConsentIQ procedure library and open the consent builder for any orthopaedic operation.",
};

export const dynamic = "force-dynamic";

export default async function ConsentIQProceduresPage() {
  // DB is the source of truth — admins add/edit procedures from /admin/consentiq.
  // Fall back to the static seed only if the DB is unreachable or empty.
  const dbProcedures = await listPublishedPublicProcedures().catch(() => []);
  const procedures =
    dbProcedures.length > 0 ? dbProcedures : staticProcedures;
  const regions =
    dbProcedures.length > 0
      ? Array.from(new Set(dbProcedures.map((p) => p.region))).sort()
      : staticRegions();

  return (
    <>
      <PageHeader
        eyebrow="ConsentIQ · Procedure library"
        title="Pick a procedure to build a consent."
        lede={`${procedures.length} orthopaedic operations, each with its own structured risks, benefits, alternatives and recovery template. Pick one to open the builder.`}
      />
      <Container className="pb-14 md:pb-16">
        <DraftBanner className="mb-8" />
        <ProceduresExplorer procedures={procedures} regions={regions} />
        <div className="mt-12 flex flex-wrap items-center gap-4 text-[13px] text-[var(--color-slate)]">
          <Link
            href="/products/consentiq"
            className="font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
          >
            ← Back to ConsentIQ overview
          </Link>
          <span aria-hidden>·</span>
          <Link
            href="/products/consentiq/templates"
            className="font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
          >
            See the template structure →
          </Link>
        </div>
      </Container>
    </>
  );
}
