// Briques partagées entre les blocks WordPress.
// Reprend les patterns visuels des sections existantes (eyebrow, titre satoshi
// black avec span d'accent, CTA pill cta-gradient) sans les modifier.

import {
  ArrowRight,
  Award,
  Building2,
  CheckCircle2,
  Clock,
  CloudSun,
  Droplets,
  Euro,
  Factory,
  FileText,
  Gauge,
  HardHat,
  Leaf,
  MapPin,
  PaintRoller,
  Phone,
  Ruler,
  School,
  ShieldCheck,
  Snowflake,
  SprayCan,
  Store,
  Sun,
  ThermometerSnowflake,
  ThermometerSun,
  Tractor,
  TrendingDown,
  TrendingUp,
  Users,
  Warehouse,
  Wind,
  Wrench,
  Zap,
  type LucideIcon,
} from "lucide-react";
import { parseAccent, rewriteWpUrls } from "@/lib/wp/mappers";
import { sanitizeWpHtml } from "@/lib/sanitizeHtml";
import type { WpCta, WpEntete } from "@/lib/wp/types";

// ---------------------------------------------------------------------------
// Icônes lucide autorisées (select `icone` du SCHEMA)
// ---------------------------------------------------------------------------

const icons: Record<string, LucideIcon> = {
  "thermometer-sun": ThermometerSun,
  "thermometer-snowflake": ThermometerSnowflake,
  droplets: Droplets,
  "shield-check": ShieldCheck,
  clock: Clock,
  euro: Euro,
  leaf: Leaf,
  factory: Factory,
  warehouse: Warehouse,
  store: Store,
  "building-2": Building2,
  school: School,
  tractor: Tractor,
  sun: Sun,
  snowflake: Snowflake,
  wrench: Wrench,
  "hard-hat": HardHat,
  "check-circle-2": CheckCircle2,
  "trending-down": TrendingDown,
  "trending-up": TrendingUp,
  zap: Zap,
  wind: Wind,
  "cloud-sun": CloudSun,
  gauge: Gauge,
  ruler: Ruler,
  "paint-roller": PaintRoller,
  "spray-can": SprayCan,
  "map-pin": MapPin,
  phone: Phone,
  "file-text": FileText,
  award: Award,
  users: Users,
};

export function iconFor(name?: string | null): LucideIcon | null {
  if (!name) return null;
  return icons[name] ?? null;
}

// ---------------------------------------------------------------------------
// Titre avec spans d'accent (convention `*accent*`)
// Sections claires : accent en text-foreground/30 (cf. ConstatSection).
// Sections sombres : accent en text-teal-vivid (cf. Testimonials, WinterObjection).
// ---------------------------------------------------------------------------

export function AccentTitle({
  titre,
  accentClass = "text-foreground/30",
}: {
  titre?: string | null;
  accentClass?: string;
}) {
  if (!titre) return null;
  return (
    <>
      {parseAccent(titre).map((seg, i) =>
        seg.accent ? (
          <span key={i} className={accentClass}>
            {seg.text}
          </span>
        ) : (
          <span key={i}>{seg.text}</span>
        )
      )}
    </>
  );
}

// ---------------------------------------------------------------------------
// Entête de section (clone_entete_section) — pattern eyebrow + h2 + intro
// repris des sections existantes (PriceComparisonSection, SectorsGrid…).
// ---------------------------------------------------------------------------

export function SectionHeading({
  entete,
  dark = false,
  centered = true,
  className = "",
}: {
  entete?: WpEntete | null;
  dark?: boolean;
  centered?: boolean;
  className?: string;
}) {
  if (!entete?.badge && !entete?.titre && !entete?.intro) return null;
  return (
    <div
      className={`${centered ? "text-center max-w-3xl mx-auto" : "max-w-3xl"} mb-12 lg:mb-16 ${className}`}
    >
      {entete.badge && (
        <p
          className={`text-[10px] uppercase tracking-[0.25em] font-semibold font-body mb-6 ${
            dark ? "text-teal-vivid" : "text-primary/50"
          }`}
        >
          {entete.badge}
        </p>
      )}
      {entete.titre && (
        <h2
          className={`font-satoshi text-3xl sm:text-4xl lg:text-[3rem] font-black !leading-[1.05] ${
            dark ? "text-white" : "text-foreground"
          }`}
          style={{ letterSpacing: "-0.03em" }}
        >
          <AccentTitle
            titre={entete.titre}
            accentClass={dark ? "text-teal-vivid" : "text-foreground/30"}
          />
        </h2>
      )}
      {entete.intro && (
        <p
          className={`${centered ? "max-w-2xl mx-auto" : "max-w-2xl"} text-base lg:text-lg mt-5 font-body leading-relaxed ${
            dark ? "text-white/60" : "text-foreground/60"
          }`}
        >
          {entete.intro}
        </p>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// CTA (clone_cta) — pill cta-gradient / bordée / lien fléché, repris du repo.
// ---------------------------------------------------------------------------

export function BlockCta({
  cta,
  dark = false,
}: {
  cta?: WpCta | null;
  dark?: boolean;
}) {
  if (!cta?.label || !cta?.lien) return null;
  const style = cta.style ?? "primary";

  if (style === "ghost") {
    return (
      <a
        href={cta.lien}
        className={`inline-flex items-center gap-2 font-semibold hover:gap-3 transition-all text-sm ${
          dark ? "text-teal-vivid" : "text-primary"
        }`}
      >
        {cta.label} <ArrowRight className="w-4 h-4" />
      </a>
    );
  }

  if (style === "secondary") {
    return (
      <a
        href={cta.lien}
        className={`group inline-flex items-center gap-2 rounded-full font-semibold pl-6 pr-2 py-2 transition-all duration-500 ease-[cubic-bezier(0.32,0.72,0,1)] ${
          dark
            ? "border border-white/30 text-white hover:bg-white/10 hover:border-white/50"
            : "border-2 border-[#991437] text-[#991437] hover:bg-[#991437]/5"
        }`}
      >
        <span className="text-sm">{cta.label}</span>
        <span
          className={`flex items-center justify-center w-8 h-8 rounded-full transition-transform duration-500 ease-[cubic-bezier(0.32,0.72,0,1)] group-hover:translate-x-0.5 group-hover:scale-105 ${
            dark ? "bg-white/10 group-hover:bg-white/20" : "bg-[#991437]/15"
          }`}
        >
          <ArrowRight className="w-3.5 h-3.5" />
        </span>
      </a>
    );
  }

  return (
    <a
      href={cta.lien}
      className="group inline-flex items-center gap-2 cta-gradient text-white font-semibold pl-6 pr-2 py-2 rounded-full"
    >
      <span className="text-sm">{cta.label}</span>
      <span className="flex items-center justify-center w-8 h-8 rounded-full bg-white/20 transition-transform duration-500 ease-[cubic-bezier(0.32,0.72,0,1)] group-hover:translate-x-0.5 group-hover:scale-105">
        <ArrowRight className="w-3.5 h-3.5" />
      </span>
    </a>
  );
}

// ---------------------------------------------------------------------------
// HTML wysiwyg (WordPress) — réécrit l'origine des médias et applique le
// styling éditorial des sections existantes (SEOContent).
// ---------------------------------------------------------------------------

export function WysiwygHtml({
  html,
  className = "",
  dark = false,
}: {
  html?: string | null;
  className?: string;
  dark?: boolean;
}) {
  if (!html) return null;
  return (
    <div
      className={`font-body leading-relaxed space-y-4 ${
        dark ? "text-white/60 [&_strong]:text-white" : "text-foreground/70 [&_strong]:text-foreground"
      } [&_a]:text-primary [&_a]:font-semibold [&_a:hover]:underline [&_ul]:list-disc [&_ul]:pl-6 [&_ul]:space-y-2 [&_ol]:list-decimal [&_ol]:pl-6 [&_ol]:space-y-2 [&_h3]:font-satoshi [&_h3]:text-2xl [&_h3]:font-bold [&_h3]:mt-6 [&_img]:rounded-xl ${className}`}
      dangerouslySetInnerHTML={{ __html: sanitizeWpHtml(rewriteWpUrls(html)) }}
    />
  );
}

// ---------------------------------------------------------------------------
// Vidéo : conversion d'une URL YouTube (watch / youtu.be / embed) en embed.
// Repris de src/views/ReferenceDetail.tsx.
// ---------------------------------------------------------------------------

export function getYoutubeId(url?: string | null): string | null {
  if (!url) return null;
  const match = url.match(/(?:watch\?v=|embed\/|youtu\.be\/)([^&?/]+)/);
  return match?.[1] ?? null;
}

export function getEmbedUrl(url: string): string {
  const videoId = getYoutubeId(url);
  return videoId ? `https://www.youtube.com/embed/${videoId}` : url;
}
