import type { ZoneData, PageType, VilleReference } from "@/data/zones";
import type { WpFicheLieu, WpLieu, WpLieuReference } from "@/lib/wp/types";
import { mapImage } from "@/lib/wp/mappers";

type WpScalar = string | string[] | number | null | undefined;

const text = (value: WpScalar): string => {
  if (Array.isArray(value)) return value[0] ?? "";
  return value == null ? "" : String(value);
};

const num = (value: WpScalar): number => Number(text(value)) || 0;

function climate(value: WpScalar): "H1" | "H2" | "H3" {
  const normalized = text(value);
  return normalized === "H2" || normalized === "H3" ? normalized : "H1";
}

function pageType(value: WpScalar): PageType {
  const normalized = text(value);
  if (normalized === "departement" || normalized === "region") return normalized;
  return "ville";
}

function refs(items: WpLieuReference[] | null | undefined): VilleReference[] {
  return (items ?? [])
    .filter((item) => item?.nom && item?.slug)
    .map((item) => ({
      nom: text(item.nom),
      slug: text(item.slug),
      typeZone: text(item.typeZone),
    }));
}

function optionalSeoContent(fiche: WpFicheLieu): ZoneData["seoContent"] | undefined {
  const seo = fiche.seoContent;
  if (!seo?.h2 && !seo?.intro && !seo?.sections?.length) return undefined;

  return {
    h2: text(seo?.h2),
    intro: text(seo?.intro),
    sections: (seo?.sections ?? []).map((section) => ({
      h3: text(section?.h3),
      content: text(section?.content),
    })),
  };
}

function optionalIntroSection(fiche: WpFicheLieu): ZoneData["introSection"] | undefined {
  const intro = fiche.introSection;
  if (!intro) return undefined;

  return {
    hook: text(intro.hook),
    accroche: text(intro.accroche),
    kpis: (intro.kpis ?? []).map((kpi) => ({
      value: text(kpi?.value),
      label: text(kpi?.label),
    })),
    contexte: text(intro.contexte),
    coutCache: text(intro.coutCache),
    trustLine: text(intro.trustLine),
    urgenceLine: text(intro.urgenceLine),
  };
}

function optionalContent(fiche: WpFicheLieu): ZoneData["content"] | undefined {
  const content = fiche.content;
  if (!content) return undefined;

  return {
    activitesIntro: text(content.activitesIntro),
    secteurs: (content.secteurs ?? []).map((secteur) => {
      const mappedImage =
        typeof secteur?.image === "string" ? null : mapImage(secteur?.image);
      return {
        label: text(secteur?.label),
        image:
          (typeof secteur?.image === "string" ? text(secteur.image) : mappedImage?.sourceUrl) ||
          undefined,
        imageAlt: mappedImage?.altText || undefined,
        stat: text(secteur?.stat),
        description: text(secteur?.description),
      };
    }),
    problemeTitlePart1: text(content.problemeTitlePart1),
    problemeTitlePart2: text(content.problemeTitlePart2),
    problemeParagraph: text(content.problemeParagraph),
    solutionTitlePart1: text(content.solutionTitlePart1),
    solutionTitlePart2: text(content.solutionTitlePart2),
    solutionParagraph: text(content.solutionParagraph),
    preuveBigStat1: text(content.preuveBigStat1),
    preuveBigStat2: text(content.preuveBigStat2),
    preuveParagraph: text(content.preuveParagraph),
  };
}

export function wpLieuToZoneData(lieu: WpLieu): ZoneData {
  const fiche = lieu.ficheLieu;
  if (!fiche) {
    throw new Error(`CPT lieu sans ficheLieu : ${lieu.slug ?? lieu.id}`);
  }

  const type = pageType(fiche.pageType);
  const heroImage = mapImage(fiche.heroImage);

  return {
    ville: text(fiche.ville) || undefined,
    departement: text(fiche.departement),
    departementNom: text(fiche.departementNom),
    departementNum: text(fiche.departementNum),
    region: text(fiche.region),
    villesDepartement: refs(fiche.villesDepartement),
    villesProches: (fiche.villesProches ?? []).map((item) => text(item?.nom)).filter(Boolean),
    maillage: refs(fiche.maillage),
    maillageScope: text(fiche.maillageScope) || undefined,
    typeZone: text(fiche.typeZone),
    climatDescription: text(fiche.climatDescription),
    zoneClimatique: climate(fiche.zoneClimatique),
    slugVille: text(fiche.slugVille) || undefined,
    slugDepartement: text(fiche.slugDepartement),
    slugRegion: text(fiche.slugRegion) || undefined,
    isDepartementPage: Boolean(fiche.isDepartementPage ?? type === "departement"),
    pageType: type,
    pays: text(fiche.pays) || "FR",
    heroImage: heroImage
      ? {
          src: heroImage.sourceUrl,
          alt: heroImage.altText,
          width: heroImage.width,
          height: heroImage.height,
          credit: text(fiche.heroImageCredit) || undefined,
          source: text(fiche.heroImageSource) || undefined,
        }
      : undefined,
    zoneClimatiqueCEE: climate(fiche.zoneClimatiqueCee),
    descriptionClimatique: text(fiche.descriptionClimatique),
    joursSup30C: num(fiche.joursSup30c),
    tempMoyEstivale: num(fiche.tempMoyEstivale),
    picHistorique: num(fiche.picHistorique),
    joursSup30C10ans: num(fiche.joursSup30c10ans),
    tempMoyEstivale10ans: num(fiche.tempMoyEstivale10ans),
    joursSup30C20ans: num(fiche.joursSup30c20ans),
    tempMoyEstivale20ans: num(fiche.tempMoyEstivale20ans),
    reductionSousToiture: num(fiche.reductionSousToiture),
    seoContent: optionalSeoContent(fiche),
    introSection: optionalIntroSection(fiche),
    content: optionalContent(fiche),
  };
}
