import { defaultParentCourseOverviewContent } from "./defaultContent";
import { buildDefaultSections } from "./buildSections";
import { parsePcoStyle } from "./pcoTheme";
import type {
  ParentCourseOverviewContent,
  ParsedParentCourseOverview,
  PCOSection,
  PCOStyle,
} from "./types";

function str(v: unknown, fallback = ""): string {
  return typeof v === "string" ? v : fallback;
}

function ensureSections(raw: unknown, legacy: ParentCourseOverviewContent): PCOSection[] {
  if (Array.isArray(raw) && raw.length > 0) {
    return raw.map((s, i) => {
      const o = s as Record<string, unknown>;
      return {
        id: str(o.id, `section-${i}`),
        type: (str(o.type, "text") as PCOSection["type"]),
        enabled: o.enabled !== false,
        number: str(o.number) || undefined,
        title: str(o.title, "Section"),
        body: str(o.body) || undefined,
        bodySecondary: str(o.bodySecondary) || undefined,
        relatedSuffix: str(o.relatedSuffix) || undefined,
        tableHeaders: Array.isArray(o.tableHeaders) ? o.tableHeaders.map(String) : undefined,
        tableRows: Array.isArray(o.tableRows)
          ? o.tableRows.map((r) => (Array.isArray(r) ? r.map(String) : [String(r)]))
          : undefined,
        learnerItems: Array.isArray(o.learnerItems)
          ? o.learnerItems.map((item) => {
              const x = item as Record<string, unknown>;
              return {
                text: str(x.text),
                detail: str(x.detail) || undefined,
                icon: str(x.icon) || undefined,
                backgroundColor: str(x.backgroundColor) || undefined,
                textColor: str(x.textColor) || undefined,
                borderColor: str(x.borderColor) || undefined,
              };
            })
          : undefined,
        portraitLabels: Array.isArray(o.portraitLabels) ? o.portraitLabels.map(String) : undefined,
        portraitScores: Array.isArray(o.portraitScores) ? o.portraitScores.map((n) => Number(n) || 70) : undefined,
        portraitSubtitle: str(o.portraitSubtitle) || undefined,
        portraitNote: str(o.portraitNote) || undefined,
        style: parsePcoStyle(o.style),
      };
    });
  }
  return buildDefaultSections(legacy);
}

/** Normalize content for editor + rendering. Migrates legacy flat schema to sections. */
export function normalizeParentCourseOverviewContent(
  content?: Record<string, unknown>
): ParentCourseOverviewContent & { sections: PCOSection[]; hero: NonNullable<ParentCourseOverviewContent["hero"]>; footer: NonNullable<ParentCourseOverviewContent["footer"]> } {
  const c = (content ?? {}) as ParentCourseOverviewContent;
  const d = defaultParentCourseOverviewContent;
  const merged: ParentCourseOverviewContent = { ...d, ...c };

  const sections = ensureSections(c.sections, merged);
  const gradeBand = str(c.hero?.gradeBand ?? c.gradeBand, d.gradeBand);
  const course = str(c.hero?.course ?? c.course, d.course);

  return {
    ...merged,
    cardColor: str(c.cardColor, d.cardColor ?? "#f8fbfd"),
    cardBorderColor: str(c.cardBorderColor, d.cardBorderColor ?? "#d8e3ea"),
    globalStyle: parsePcoStyle(c.globalStyle),
    hero: {
      eyebrow: str(c.hero?.eyebrow, "Orion STEM Schools | Parent-Facing Course Overview | Grades {gradeBand}"),
      course,
      promise: str(c.hero?.promise ?? c.promise, d.promise),
      gradeBand,
      style: parsePcoStyle(c.hero?.style),
    },
    sections,
    footer: {
      text: str(c.footer?.text ?? c.footerNote, d.footerNote),
      style: parsePcoStyle(c.footer?.style),
    },
  };
}

export function parseParentCourseOverviewContent(content?: Record<string, unknown>): ParsedParentCourseOverview {
  const n = normalizeParentCourseOverviewContent(content);
  return {
    cardColor: n.cardColor ?? "#f8fbfd",
    cardBorderColor: n.cardBorderColor ?? "#d8e3ea",
    globalStyle: n.globalStyle ?? {},
    hero: {
      eyebrow: n.hero!.eyebrow ?? "Orion STEM Schools | Parent-Facing Course Overview | Grades {gradeBand}",
      course: n.hero!.course ?? "",
      promise: n.hero!.promise ?? "",
      gradeBand: n.hero!.gradeBand ?? "K-5",
      style: n.hero!.style ?? {},
    },
    sections: (n.sections ?? []).filter((s) => s.enabled !== false),
    footer: {
      text: n.footer!.text ?? "",
      style: n.footer!.style ?? {},
    },
  };
}

export function interpolateTemplate(template: string, vars: Record<string, string>): string {
  return template.replace(/\{(\w+)\}/g, (_, key: string) => vars[key] ?? `{${key}}`);
}
