// Mapper de la vue monolithique src/views/PrimeCEECoolRoof.tsx.
// Rows WP de page--bat-en-112 : hero, composant_react `estimation` (titre),
// grille_cards "dispositif", 2 tableau_comparatif (barème zones / exemples —
// par position), 2 texte_image (éligibilité / produits — par position),
// chiffres (encart CovaTherm), etapes (process), faq, cta final, contenu_seo
// (sections[0] = titre + intro SEO, suivantes = blocs, sources = liens).
// Icônes des conditions reprises de l'original par position ; valeur absente
// => undefined (le défaut de la vue prend le relais).

import {
  AlertTriangle,
  Building2,
  ClipboardCheck,
  FileCheck2,
  ShieldCheck,
  Sparkles,
  ThermometerSun,
} from "lucide-react";
import { arr, mapImage } from "../mappers";
import type {
  ChiffresBlock,
  ComposantReactBlock,
  ContenuSeoBlock,
  CtaBlock,
  EtapesBlock,
  FaqBlock,
  GrilleCardsBlock,
  HeroBlock,
  TableauComparatifBlock,
  TexteImageBlock,
  WpSection,
} from "../types";
import type {
  CeeExample,
  CeeFaqItem,
  CeeProcessStep,
  CeeSeoBloc,
  CeeSeoSource,
  CeeZone,
  EligibilityCondition,
  PrimeCEECoolRoofProps,
  ZoneKey,
} from "@/views/PrimeCEECoolRoof";
import { byLayout, nthLayout, plainTitle, stripHtml, u } from "./shared";

/** Icônes des conditions d'éligibilité de l'original, par position. */
const ELIG_ICONS = [
  Building2,
  ThermometerSun,
  ShieldCheck,
  FileCheck2,
  Building2,
  Sparkles,
  ClipboardCheck,
  AlertTriangle,
];

/** Cellule n d'une ligne de tableau comparatif, plain-text. */
const cell = (
  ligne: { cellules?: { texte?: string | null }[] | null } | undefined,
  index: number,
): string => stripHtml(arr(ligne?.cellules)[index]?.texte) ?? "";

/**
 * Découpe le texte_apres du tableau "exemples" en titre + texte + note
 * (les trois paragraphes de l'encart "Dans le Sud" de l'original) :
 * 1re phrase = titre, 2e = texte, le reste = note.
 */
const splitSud = (
  texte?: string | null,
): { titre?: string; texte?: string; note?: string } => {
  const plain = stripHtml(texte);
  if (!plain) return {};
  const sentences = plain.match(/[^.]+\./g)?.map((s) => s.trim()) ?? [plain];
  if (sentences.length < 3) return { titre: sentences[0], texte: sentences[1] };
  return {
    titre: sentences[0],
    texte: sentences[1],
    note: sentences.slice(2).join(" "),
  };
};

/** Retire le préfixe "Label : " d'un texte WP (ex. "La formule : …", "Attention : …"). */
const afterColon = (texte?: string | null): string | undefined => {
  const plain = stripHtml(texte);
  if (!plain) return undefined;
  const sep = plain.indexOf(" : ");
  return sep >= 0 ? plain.slice(sep + 3) : plain;
};

export function mapPrimeCEECoolRoofProps(sections: WpSection[]): PrimeCEECoolRoofProps {
  const hero = nthLayout<HeroBlock>(sections, "HeroLayout");
  const estimation = byLayout<ComposantReactBlock>(sections, "ComposantReactLayout").find(
    (c) => c.composant === "estimation",
  );
  const dispositif = nthLayout<GrilleCardsBlock>(sections, "GrilleCardsLayout");
  const tableaux = byLayout<TableauComparatifBlock>(sections, "TableauComparatifLayout");
  const [bareme, exemples] = tableaux;
  const textesImages = byLayout<TexteImageBlock>(sections, "TexteImageLayout");
  const [eligibilite, produits] = textesImages;
  const chiffres = nthLayout<ChiffresBlock>(sections, "ChiffresLayout");
  const etapes = nthLayout<EtapesBlock>(sections, "EtapesLayout");
  const faq = nthLayout<FaqBlock>(sections, "FaqLayout");
  const cta = nthLayout<CtaBlock>(sections, "CtaLayout");
  const contenuSeo = nthLayout<ContenuSeoBlock>(sections, "ContenuSeoLayout");

  const heroImage = mapImage(hero?.image);

  const dispositifCardsWp = arr(dispositif?.cards);
  const dispositifCards: [string, string][] | undefined = dispositifCardsWp.length
    ? dispositifCardsWp.map((card) => [
        plainTitle(card?.titre) ?? "",
        stripHtml(card?.texte) ?? "",
      ])
    : undefined;

  const zonesWp = arr(bareme?.lignesComparatif);
  const zones: CeeZone[] | undefined = zonesWp.length
    ? zonesWp.map((ligne) => ({
        zone: cell(ligne, 0) as ZoneKey,
        regions: cell(ligne, 1),
        note: cell(ligne, 2),
        kwh: Number(cell(ligne, 3)) || 0,
      }))
    : undefined;

  const exemplesWp = arr(exemples?.lignesComparatif);
  const examples: CeeExample[] | undefined = exemplesWp.length
    ? exemplesWp.map((ligne) => ({
        zone: cell(ligne, 0),
        calc: cell(ligne, 1),
        amount: cell(ligne, 2),
        perM2: cell(ligne, 3),
      }))
    : undefined;

  const sud = splitSud(exemples?.texteApres);

  const eligListe = arr(eligibilite?.liste);
  const eligConditions: EligibilityCondition[] | undefined = eligListe.length
    ? eligListe.map((item, i) => ({
        icon: ELIG_ICONS[i] ?? Building2,
        text: stripHtml(item?.texte) ?? "",
      }))
    : undefined;

  const productTypesWp = arr(produits?.liste)
    .map((item) => stripHtml(item?.texte) ?? "")
    .filter(Boolean);

  const figures = arr(chiffres?.figures);
  const covaFigures: [string, string][] | undefined = figures.length
    ? figures.map((f) => [f?.value ?? "", f?.label ?? ""])
    : undefined;

  const etapesWp = arr(etapes?.etapes);
  const processSteps: CeeProcessStep[] | undefined = etapesWp.length
    ? etapesWp.map((etape, i) => ({
        num: String(i + 1).padStart(2, "0"),
        title: plainTitle(etape?.titre) ?? "",
        text: stripHtml(etape?.texte) ?? "",
      }))
    : undefined;

  const questions = arr(faq?.questions);
  const faqs: CeeFaqItem[] | undefined = questions.length
    ? questions.map((q) => ({
        q: q?.question ?? "",
        a: stripHtml(q?.reponse) ?? "",
      }))
    : undefined;

  const reassurancesWp = arr(cta?.reassurances)
    .map((item) => item?.texte ?? "")
    .filter(Boolean);

  // contenu_seo : la 1re section porte le h2 + l'intro, les suivantes les h3.
  const seoSections = arr(contenuSeo?.sections);
  const [seoIntroSection, ...seoBlocSections] = seoSections;
  const seoBlocs: CeeSeoBloc[] | undefined = seoBlocSections.length
    ? seoBlocSections.map((s) => ({
        titre: plainTitle(s?.titre) ?? "",
        texte: stripHtml(s?.contenu) ?? "",
      }))
    : undefined;

  const sourcesWp = arr(contenuSeo?.sources);
  const seoSources: CeeSeoSource[] | undefined = sourcesWp.length
    ? sourcesWp.map((s) => ({ label: s?.label ?? "", url: s?.url ?? "" }))
    : undefined;

  return {
    heroEyebrow: u(hero?.eyebrow),
    heroTitre: plainTitle(hero?.titre),
    heroIntro: stripHtml(hero?.lead),
    heroImage: heroImage?.sourceUrl,
    heroImageAlt: u(heroImage?.altText),
    heroCtaLabel: u(hero?.ctaPrimaire?.label),
    heroCtaHref: u(hero?.ctaPrimaire?.lien),
    heroSecondaireLabel: u(hero?.ctaSecondaire?.label),
    heroSecondaireHref: u(hero?.ctaSecondaire?.lien),
    estimTitre: u(estimation?.titre),
    dispositifBadge: u(dispositif?.entete?.badge),
    dispositifTitre: plainTitle(dispositif?.entete?.titre),
    dispositifIntro: stripHtml(dispositif?.entete?.intro),
    dispositifCards,
    zones,
    baremeBadge: u(bareme?.entete?.badge),
    baremeTitre: plainTitle(bareme?.entete?.titre),
    baremeIntro: stripHtml(bareme?.entete?.intro),
    formuleTexte: afterColon(bareme?.texteApres)?.replace(/\.$/, ""),
    exemplesIntro: stripHtml(exemples?.entete?.intro),
    examples,
    sudTitre: sud.titre,
    sudTexte: sud.texte,
    sudNote: sud.note,
    sudCtaLabel: u(exemples?.cta?.label),
    sudCtaHref: u(exemples?.cta?.lien),
    eligBadge: u(eligibilite?.entete?.badge),
    eligTitre: plainTitle(eligibilite?.entete?.titre),
    eligIntro: stripHtml(eligibilite?.contenu),
    eligConditions,
    eligCtaLabel: u(eligibilite?.cta?.label),
    eligCtaHref: u(eligibilite?.cta?.lien),
    produitsBadge: u(produits?.entete?.badge),
    produitsTitre: plainTitle(produits?.entete?.titre),
    produitsIntro: stripHtml(produits?.contenu),
    productTypes: productTypesWp.length ? productTypesWp : undefined,
    produitsNote: afterColon(produits?.note),
    covaLabel: plainTitle(chiffres?.entete?.titre),
    covaFigures,
    covaTexte: stripHtml(chiffres?.entete?.intro),
    processBadge: u(etapes?.entete?.badge),
    processTitre: plainTitle(etapes?.entete?.titre),
    processSteps,
    processAlerte: stripHtml(etapes?.reassurance),
    faqBadge: u(faq?.entete?.badge),
    faqTitre: plainTitle(faq?.entete?.titre),
    faqs,
    faqCtaLabel: u(faq?.cta?.label),
    faqCtaHref: u(faq?.cta?.lien),
    ctaTitre: plainTitle(cta?.titre),
    ctaTexte: stripHtml(cta?.texte),
    ctaLabel: u(cta?.ctaPrimaire?.label),
    ctaHref: u(cta?.ctaPrimaire?.lien),
    ctaSecondaireLabel: u(cta?.ctaSecondaire?.label),
    ctaSecondaireHref: u(cta?.ctaSecondaire?.lien),
    ctaReassurances: reassurancesWp.length ? reassurancesWp : undefined,
    seoTitre: plainTitle(seoIntroSection?.titre),
    seoIntroTexte: stripHtml(seoIntroSection?.contenu),
    seoBlocs,
    seoSources,
  };
}
