// ConsentIQ procedure library — 321 rich, read-only consent documents
// imported from the OrthoGlobe ConsentIQ platform HTML. Content is
// reviewed by Professor Mohamed A. Imam and is provided as clinical
// reference material, not as a finalised legal consent document.

import libraryJson from "./library.json";

export type LibraryRiskItem = {
  risk: string;
  detail: string;
  freq?: string;
};

export type LibraryFaqItem = {
  q: string;
  a: string;
};

export type LibrarySection = {
  title: string;
  icon?: string;
  content?: string;
  isRisk?: boolean;
  isFaq?: boolean;
  isWarning?: boolean;
  items?: LibraryRiskItem[] | LibraryFaqItem[];
};

export type LibraryProcedure = {
  slug: string;
  name: string;
  region: string;
  tag: string;
  reviewer: string;
  reviewed: string;
  nextReview: string;
  version: string;
  overview: string;
  sections: LibrarySection[];
};

type LibraryMap = Record<string, Omit<LibraryProcedure, "slug">>;

const raw = libraryJson as LibraryMap;

export const libraryProcedures: LibraryProcedure[] = Object.entries(raw)
  .map(([slug, data]) => ({ slug, ...data }))
  .sort((a, b) => a.name.localeCompare(b.name));

export function getLibraryProcedure(slug: string): LibraryProcedure | undefined {
  const entry = raw[slug];
  if (!entry) return undefined;
  return { slug, ...entry };
}

export function getLibraryRegions(): { name: string; count: number }[] {
  const counts = new Map<string, number>();
  for (const p of libraryProcedures) {
    counts.set(p.region, (counts.get(p.region) ?? 0) + 1);
  }
  return [...counts.entries()]
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count);
}

export function getLibraryProceduresByRegion(region: string): LibraryProcedure[] {
  return libraryProcedures.filter((p) => p.region === region);
}
