import { Warehouse, Plane, Building2, Thermometer, BriefcaseBusiness, Landmark, ArrowRight } from "lucide-react";
import type { ReactNode } from "react";
import ScrollReveal from './ScrollReveal';

/* ── Linkify secteur keywords ── */

const SECTEUR_LINKS: Array<{ pattern: RegExp; href: string }> = [
  { pattern: /\b(logistiques?)\b/i, href: '/cool-roof-logistique' },
  { pattern: /\b(tertiaires?)\b/i, href: '/cool-roof-tertiaire' },
  { pattern: /\b(distribution)\b/i, href: '/cool-roof-distribution' },
  { pattern: /\b(collectivités?|collectivité)\b/i, href: '/cool-roof-collectivites' },
];

function linkifySecteurKeywords(text: string): ReactNode[] {
  const linkedKeywords = new Set<string>();
  let result: ReactNode[] = [text];

  for (const { pattern, href } of SECTEUR_LINKS) {
    const nextResult: ReactNode[] = [];
    for (const segment of result) {
      if (typeof segment !== 'string') { nextResult.push(segment); continue; }
      const match = segment.match(pattern);
      if (!match || linkedKeywords.has(href)) { nextResult.push(segment); continue; }
      linkedKeywords.add(href);
      const idx = match.index!;
      const before = segment.slice(0, idx);
      const matched = match[0];
      const after = segment.slice(idx + matched.length);
      if (before) nextResult.push(before);
      nextResult.push(<a key={href} href={href} className="text-foreground/80 hover:underline transition-colors">{matched}</a>);
      if (after) nextResult.push(after);
    }
    result = nextResult;
  }
  return result;
}

/* ── Sector block data ── */

interface SectorBlock {
  name: string;
  icon: typeof Building2;
  accroche: string;
  description: string;
}

const SECTOR_BLOCKS: Record<string, SectorBlock> = {
  'Logistique': {
    name: 'Logistique',
    icon: Warehouse,
    accroche: 'Entrepôts & plateformes de distribution',
    description: 'Toitures bac acier de 5 000 à 50 000 m², marchandises thermosensibles, chaîne du froid sous tension. Le cool roof réduit la température sous toiture de 8 à 12 °C sans arrêt d\u2019exploitation.',
  },
  'Aéroportuaire': {
    name: 'Aéroportuaire',
    icon: Plane,
    accroche: 'Terminaux, hangars & zones de fret',
    description: 'Activité 24h/24, normes strictes, toitures à forte inertie thermique amplifiées par l\u2019effet tarmac. Le revêtement CovaTherm résiste aux contraintes spécifiques des zones aéroportuaires.',
  },
  'Industriel': {
    name: 'Industriel',
    icon: Building2,
    accroche: 'Sites de production & usines',
    description: 'Chaleur de process cumulée à la surchauffe estivale, toitures métalliques de grande surface. Le cool roof réduit la charge thermique globale et améliore les conditions de travail.',
  },
  'Tertiaire': {
    name: 'Tertiaire',
    icon: BriefcaseBusiness,
    accroche: 'Bureaux, sièges sociaux & ERP',
    description: 'Confort des occupants, conformité au Décret tertiaire, réduction de 15 à 40 % de la climatisation. Le cool roof contribue directement aux objectifs 2030.',
  },
  'Agroalimentaire': {
    name: 'Agroalimentaire',
    icon: Thermometer,
    accroche: 'Usines & entrepôts frigorifiques',
    description: 'Normes HACCP, chaîne du froid permanente, volumes réfrigérés massifs. Le cool roof réduit la charge thermique et la facture de froid de 20 à 35 %.',
  },
  'Port fluvial': {
    name: 'Port fluvial',
    icon: Landmark,
    accroche: 'Infrastructures portuaires & stockage',
    description: 'Toitures exposées en bord de voie navigable, stockage de marchandises sensibles. Le cool roof protège les entrepôts portuaires de la surchauffe estivale.',
  },
};

function getSectorBlocks(typeZone: string): SectorBlock[] {
  // Split "Logistique / Aéroportuaire" → ["Logistique", "Aéroportuaire"]
  const parts = typeZone.includes(' / ')
    ? typeZone.split(' / ').map((s) => s.trim())
    : [typeZone];

  return parts
    .map((p) => SECTOR_BLOCKS[p])
    .filter((b): b is SectorBlock => !!b);
}

/* ── Intro paragraphs ── */

function getIntroParagraph(
  typeZone: string,
  ville: string | undefined,
  departement: string | undefined,
  climatDescription: string,
  isDepartementPage: boolean
): string {
  if (isDepartementPage) {
    return `Le parc bâti professionnel du ${departement} présente une diversité de typologies — logistique, industrielle, tertiaire — toutes concernées par les enjeux de surchauffe estivale. ${climatDescription}.`;
  }
  if (typeZone.includes(" / ")) {
    return `Le tissu économique de ${ville} mêle activités ${typeZone}, avec des typologies de bâtiments variées toutes concernées par les enjeux de surchauffe estivale. ${climatDescription}.`;
  }
  if (typeZone === "Logistique") {
    return `Les entrepôts logistiques de ${ville} présentent des toitures bac acier de grande surface, particulièrement exposées au rayonnement solaire. ${climatDescription}.`;
  }
  if (typeZone === "Aéroportuaire") {
    return `Les bâtiments aéroportuaires de ${ville} combinent continuité d'activité 24/7 et toitures vastes à forte inertie thermique. ${climatDescription}.`;
  }
  if (typeZone === "Industriel") {
    return `Les sites industriels de ${ville} cumulent chaleur de process interne et surchauffe estivale des toitures. ${climatDescription}.`;
  }
  if (typeZone === "Tertiaire") {
    return `Les bâtiments tertiaires de ${ville} voient leurs performances énergétiques impactées par la surchauffe estivale. ${climatDescription}.`;
  }
  return `Le tissu économique de ${ville} mêle activités ${typeZone}, avec des typologies de bâtiments variées toutes concernées par les enjeux de surchauffe estivale. ${climatDescription}.`;
}

/* ── Props ── */

interface SecteurIndustrielSectionProps {
  typeZone: string;
  ville?: string;
  departement?: string;
  region?: string;
  climatDescription: string;
  pageType: 'ville' | 'departement' | 'region';
}

/* ── Component ── */

const SecteurIndustrielSection = ({
  typeZone,
  ville,
  departement,
  region,
  climatDescription,
  pageType,
}: SecteurIndustrielSectionProps) => {
  const isDepartementPage = pageType === 'departement' || pageType === 'region';
  const intro = getIntroParagraph(typeZone, ville, departement, climatDescription, isDepartementPage);
  const blocks = getSectorBlocks(typeZone);

  const heading = pageType === 'region'
    ? `Le cool roof en ${region}`
    : pageType === 'departement'
      ? `Le cool roof dans le ${departement}`
      : `Le cool roof à ${ville}`;

  return (
    <section className="py-20 lg:py-28">
      <div className="container mx-auto px-4 lg:px-8">

        {/* Header */}
        <ScrollReveal>
          <div className="max-w-5xl mx-auto mb-14">
            <p className="text-[10px] uppercase tracking-[0.25em] font-semibold text-primary/50 font-body mb-6">
              Un contexte local que nous connaissons
            </p>
            <h2
              className="font-satoshi text-3xl sm:text-4xl lg:text-[3rem] font-black text-foreground !leading-[1.05]"
              style={{ letterSpacing: '-0.03em' }}
            >
              {heading}
              <span className="text-foreground/30">
                {isDepartementPage
                  ? ' : des toitures à protéger'
                  : ` : secteur ${typeZone}.`}
              </span>
            </h2>
            <p className="max-w-3xl text-foreground/60 text-base lg:text-lg mt-5 font-body leading-relaxed">
              {linkifySecteurKeywords(intro)}
            </p>
          </div>
        </ScrollReveal>

        {/* Sector blocks — big cards */}
        <ScrollReveal stagger>
          <div className={`max-w-5xl mx-auto grid grid-cols-1 ${blocks.length > 1 ? 'lg:grid-cols-2' : ''} gap-5 lg:gap-6`}>
            {blocks.map((block) => {
              const Icon = block.icon;
              return (
                <div
                  key={block.name}
                  className="group relative bg-[#192A3A] rounded-2xl overflow-hidden p-8 lg:p-10 flex flex-col justify-between min-h-[260px] transition-all duration-500 hover:shadow-[0_20px_60px_-15px_rgba(26,42,58,0.4)]"
                >
                  {/* Ambient blob */}
                  <div className="absolute top-0 right-0 w-40 h-40 bg-[radial-gradient(circle_at_100%_0%,_rgba(32,150,140,0.12)_0%,_transparent_70%)] pointer-events-none" />
                  <div className="absolute bottom-0 left-0 w-32 h-32 bg-[radial-gradient(circle_at_0%_100%,_rgba(32,150,140,0.06)_0%,_transparent_70%)] pointer-events-none" />

                  {/* Top — icon + name */}
                  <div className="relative">
                    <div className="flex items-center gap-4 mb-5">
                      <div className="w-12 h-12 rounded-xl bg-white/10 flex items-center justify-center transition-colors duration-300 group-hover:bg-white/15">
                        <Icon className="w-6 h-6 text-teal-vivid" strokeWidth={1.8} />
                      </div>
                      <div>
                        <h3
                          className="font-satoshi font-black text-white text-xl lg:text-2xl !leading-tight"
                          style={{ letterSpacing: '-0.02em' }}
                        >
                          {block.name}
                        </h3>
                        <p className="text-white/40 text-sm font-body mt-0.5">
                          {block.accroche}
                        </p>
                      </div>
                    </div>

                    <p className="text-white/55 font-body text-[15px] leading-relaxed">
                      {block.description}
                    </p>
                  </div>

                  {/* Bottom — CTA link */}
                  <div className="relative mt-6">
                    <a
                      href="/diagnostic"
                      className="group/link inline-flex items-center gap-2 text-teal-vivid font-satoshi font-bold text-sm transition-transform duration-300 hover:translate-x-1"
                    >
                      <span>Estimer mon projet</span>
                      <ArrowRight className="w-4 h-4" strokeWidth={2.5} />
                    </a>
                  </div>
                </div>
              );
            })}
          </div>
        </ScrollReveal>
      </div>
    </section>
  );
};

export default SecteurIndustrielSection;
