"use client";

/**
 * Section Renderer
 * ─────────────────
 * Maps section types from the Analysis object to React components.
 * Reusable across different analysis templates.
 */

import type { Analysis } from "@/lib/services/analysis-schema";
import { CaveatBanners } from "./sections/caveat-banners";
import { KpiCards } from "./sections/kpi-cards";
import { FindingsSection } from "./sections/findings";
import { ChartSection } from "./sections/chart";
import { DataTableSection } from "./sections/data-table";
import { TimelineSection } from "./sections/timeline";
import { PredictionsSection } from "./sections/predictions";
import { RecommendationsSection } from "./sections/recommendations";
import { SourceFooter } from "./sections/source-footer";
import { MethodologySection } from "./sections/methodology";
import { MissingDataSection } from "./sections/missing-data";

export type SectionType =
  | "caveats"
  | "kpis"
  | "findings"
  | "chart"
  | "table"
  | "timeline"
  | "predictions"
  | "recommendations"
  | "methodology"
  | "sources";

export interface SectionConfig {
  type: SectionType;
  /** Index into the analysis arrays (for chart/table which can have multiple) */
  index?: number;
}

/**
 * Render all sections from an Analysis object in order.
 * Pass a custom `sections` array to control which sections render and in what order.
 * If omitted, renders all non-empty sections in default order.
 */
export function renderSections(analysis: Analysis, sections?: SectionConfig[]) {
  const config = sections ?? defaultSections(analysis);
  return config.map((sec, i) => (
    <AnalysisSection key={`${sec.type}-${sec.index ?? 0}-${i}`} analysis={analysis} section={sec} />
  ));
}

function AnalysisSection({ analysis, section }: { analysis: Analysis; section: SectionConfig }) {
  switch (section.type) {
    case "caveats":
      return analysis.caveats.length > 0 ? <CaveatBanners caveats={analysis.caveats} /> : null;

    case "kpis":
      return analysis.kpis.length > 0 ? <KpiCards kpis={analysis.kpis} periodLabel={analysis.period.label ? `${analysis.period.start} → ${analysis.period.end}` : undefined} /> : <MissingDataSection label="KPIs" reason="No metrics available for this period" />;

    case "findings":
      return analysis.findings.length > 0 ? <FindingsSection findings={analysis.findings} brandId={analysis.brandId} /> : null;

    case "chart": {
      const chart = analysis.charts[section.index ?? 0];
      return chart ? <ChartSection chart={chart} /> : <MissingDataSection label="Chart" reason="No chart data available" />;
    }

    case "table": {
      const table = analysis.tables[section.index ?? 0];
      return table ? <DataTableSection table={table} /> : null;
    }

    case "timeline":
      return analysis.timeline.length > 0 ? <TimelineSection events={analysis.timeline} /> : null;

    case "predictions":
      return analysis.predictions.length > 0 ? <PredictionsSection predictions={analysis.predictions} brandId={analysis.brandId} /> : null;

    case "recommendations":
      return analysis.recommendations.length > 0 ? <RecommendationsSection recs={analysis.recommendations} brandId={analysis.brandId} /> : null;

    case "methodology":
      return analysis.narrative?.methodology ? <MethodologySection text={analysis.narrative.methodology} /> : null;

    case "sources":
      return <SourceFooter sources={analysis.sources} />;

    default:
      return null;
  }
}

function defaultSections(analysis: Analysis): SectionConfig[] {
  const sections: SectionConfig[] = [
    { type: "caveats" },
    { type: "kpis" },
  ];

  // Add each chart
  for (let i = 0; i < analysis.charts.length; i++) {
    sections.push({ type: "chart", index: i });
  }

  sections.push({ type: "findings" });
  sections.push({ type: "timeline" });

  // Add each table
  for (let i = 0; i < analysis.tables.length; i++) {
    sections.push({ type: "table", index: i });
  }

  sections.push({ type: "predictions" });
  sections.push({ type: "recommendations" });
  sections.push({ type: "methodology" });
  sections.push({ type: "sources" });

  return sections;
}
