/**
 * Reports data layer — centralises all report lookups.
 *
 * Currently reads from the static JSON files in `@/data/`.
 * When the client delivers the live API, replace the body of each
 * function with a fetch call — the return shapes stay the same so
 * every consuming Server Component keeps working without changes.
 */

import hubData from "@/data/meticulous-report-hub.json"
import reportDetailData from "@/data/meticulous-report-details.json"

/* ------------------------------------------------------------------ */
/* Hub (listing) helpers                                               */
/* ------------------------------------------------------------------ */

export type HubData = typeof hubData
export type HubReport = HubData["resultsGrid"]["reports"][number]

/** Return the full hub payload (header, filters, grid, etc.). */
export function getHubData(): HubData {
  return hubData
}

/** Return every report entry from the grid (used for sitemaps, static params, etc.). */
export function getAllHubReports(): HubReport[] {
  return hubData.resultsGrid.reports
}

/* ------------------------------------------------------------------ */
/* Detail helpers                                                      */
/* ------------------------------------------------------------------ */

export type ReportDetail = typeof reportDetailData

/**
 * Derive a URL-safe slug from a hub report's title.
 *
 * Example: "Protein Bar Market — Global Opportunity Analysis & Forecast
 *           (2026–2036)" → "protein-bar-market"
 *
 * The slug captures only the first semantic segment (market name) so the
 * URL stays short and SEO-friendly.
 */
export function deriveSlug(title: string): string {
  return title
    .split("—")[0]           // keep the part before the em-dash
    .trim()
    .toLowerCase()
    .replace(/&/g, "and")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "")
}

/**
 * Build a map of all known slugs → report IDs.
 * Used by `generateStaticParams()` and the `/r/[reportId]` redirect.
 */
export function getSlugToIdMap(): Record<string, string> {
  const map: Record<string, string> = {}
  for (const report of hubData.resultsGrid.reports) {
    map[deriveSlug(report.title)] = report.id
  }
  return map
}

/**
 * Build a map of all known report IDs → slugs.
 * Used by the `/r/[reportId]` redirect handler.
 */
export function getIdToSlugMap(): Record<string, string> {
  const map: Record<string, string> = {}
  for (const report of hubData.resultsGrid.reports) {
    map[report.id] = deriveSlug(report.title)
  }
  return map
}

/**
 * Return the full detail payload for a given slug.
 *
 * Currently we only have ONE detail dataset (Protein Bar Market).
 * Once the API is connected, this function will fetch `/reports/{slug}`.
 */
export function getReportDetailBySlug(slug: string): ReportDetail | null {
  // Find a matching hub entry to confirm the slug exists
  const match = hubData.resultsGrid.reports.find(
    (r) => deriveSlug(r.title) === slug
  )
  if (!match) return null

  // For the single static dataset we only have protein-bar-market detail.
  // For every other known slug we return the same detail (demo only).
  // The API will return per-slug data once connected.
  return reportDetailData
}

/** Return all valid slugs (for `generateStaticParams`). */
export function getAllReportSlugs(): string[] {
  return hubData.resultsGrid.reports.map((r) => deriveSlug(r.title))
}

/* ------------------------------------------------------------------ */
/* Analyst helpers                                                    */
/* ------------------------------------------------------------------ */

export interface AnalystData {
  slug: string
  name: string
  role: string
  bio: string
  tenure: string
  publishedCount: number
  sectors: string[]
  quote: string
}

export function getAnalystBySlug(slug: string): AnalystData | null {
  const normalized = slug.toLowerCase().replace(/[^a-z0-9]+/g, "-")
  if (normalized === "priya-nair") {
    return {
      slug: "priya-nair",
      name: "Priya Nair",
      role: "Lead Analyst, Food & Nutrition",
      bio: "Priya Nair is the Lead Analyst for Food & Nutrition at Meticulous Research. With over 8 years of experience in market intelligence and primary food science research, she specializes in plant-based proteins, sugar reduction formulations, and active functional snacking categories. Priya holds a Master's degree in Food Science and is a frequent contributor to leading industry panels.",
      tenure: "8+ Years",
      publishedCount: 42,
      sectors: ["Food & Beverages", "Consumer Nutrition", "Plant-Based Ingredients"],
      quote: "The category's center of gravity has moved from the gym to the pantry. The brands that will own the next decade are reformulating for the everyday functional-snacking buyer — clean label, lower sugar, recognizable protein — without losing the macros that built the category."
    }
  }
  return null
}
