"use client";

import { useState } from 'react';
import { AlertTriangle, Check, X } from 'lucide-react';
import type { ReactNode } from 'react';
import ScrollReveal from '@/components/ScrollReveal';
import { type Locale } from '@/config/i18nRoutes';
import { useLocale } from '@/components/blocks/localeContext';

// Libellés statiques de compatibilité (jamais fournis par WP) → traduits.
const COMPAT_I18N: Record<Locale, { compatible: string; nonCompatible: string; warning: (p: string) => ReactNode }> = {
  fr: {
    compatible: 'Compatible',
    nonCompatible: 'Non compatible',
    warning: (p) => (
      <>
        <strong className="text-red-900">Ne pas appliquer {p} sur du vitrage.</strong>{' '}
        Sur verre, verrière ou véranda, un <strong>film solaire intérieur collé</strong> offre un bien meilleur rendu esthétique et une durabilité supérieure. Pour les polymères translucides (polycarbonate, polyester), {p} reste la solution adaptée.
      </>
    ),
  },
  en: {
    compatible: 'Compatible',
    nonCompatible: 'Not compatible',
    warning: (p) => (
      <>
        <strong className="text-red-900">Do not apply {p} on glazing.</strong>{' '}
        On glass, glass roofs or verandas, an <strong>interior bonded solar film</strong> delivers a far better finish and greater durability. For translucent polymers (polycarbonate, polyester), {p} remains the right solution.
      </>
    ),
  },
  es: {
    compatible: 'Compatible',
    nonCompatible: 'No compatible',
    warning: (p) => (
      <>
        <strong className="text-red-900">No aplicar {p} sobre acristalamientos.</strong>{' '}
        En vidrio, cubiertas acristaladas o galerías, una <strong>lámina solar interior adhesiva</strong> ofrece un acabado mucho mejor y una mayor durabilidad. Para polímeros translúcidos (policarbonato, poliéster), {p} sigue siendo la solución adecuada.
      </>
    ),
  },
};

interface CompatibleRoof {
  type: string;
  detail: string;
  incompatible?: boolean;
  image?: string;
}

interface Props {
  productName: string;
  compatibleRoofs: CompatibleRoof[];
  badge?: string;
  titre?: ReactNode;
  intro?: ReactNode;
  coverageNote?: string;
  footerNote?: ReactNode;
}

/**
 * Section « Les supports compatibles ».
 * Desktop : liste d'onglets cliquables (thumbnail + label) à gauche, image
 * large + détail de la sélection active à droite.
 * Mobile : strip horizontal scrollable de miniatures + panneau actif en
 * dessous (pattern galerie photo).
 * Traitement visuel dédié (rouge + callout d'avertissement) pour les
 * entrées `incompatible: true`.
 */
const CompatibilityTabs = ({
  productName,
  compatibleRoofs,
  badge = 'Compatibilité',
  titre,
  intro,
  coverageNote,
  footerNote,
}: Props) => {
  const locale = useLocale();
  const tc = COMPAT_I18N[locale];
  const [active, setActive] = useState(0);
  const current = compatibleRoofs[active];
  const currentCompatibleIndex = current.incompatible
    ? null
    : compatibleRoofs.slice(0, active + 1).filter((x) => !x.incompatible).length;

  return (
    <section className="relative py-16 lg:py-24 bg-teal-light overflow-hidden">
      {/* Header — shared */}
      <div className="relative container mx-auto px-4 lg:px-8 max-w-5xl">
        <ScrollReveal>
          <div className="max-w-2xl mb-8 lg:mb-14">
            <p className="text-[10px] uppercase tracking-[0.25em] font-semibold text-primary/65 font-body mb-3">
              {badge}
            </p>
            <h2
              className="font-satoshi text-3xl sm:text-4xl lg:text-5xl font-black text-foreground !leading-[1.05] mb-5"
              style={{ letterSpacing: '-0.03em' }}
            >
              {titre ?? (<>
              Les supports compatibles
              <br />
              <span className="text-foreground/45">avec {productName}.</span>
              </>)}
            </h2>
            {intro && (
              <div className="text-sm text-foreground/75 font-body leading-relaxed space-y-3">
                {intro}
              </div>
            )}
            {coverageNote && (
              <p className="text-xs text-foreground/55 font-body italic mt-3">{coverageNote}</p>
            )}
          </div>
        </ScrollReveal>
      </div>

      {/* Mobile — strip horizontal pleine largeur (lg:hidden) */}
      <div className="lg:hidden">
        <ScrollReveal>
          <div
            className="flex overflow-x-auto gap-2.5 px-4 pb-3 snap-x"
            style={{ scrollbarWidth: 'none' }}
          >
            {compatibleRoofs.map((r, i) => {
              const isActive = i === active;
              return (
                <button
                  key={i}
                  onClick={() => setActive(i)}
                  aria-pressed={isActive}
                  className={`group shrink-0 flex flex-col items-center snap-start transition-all ${
                    isActive ? '' : 'opacity-60'
                  }`}
                >
                  <div
                    className={`w-[72px] h-[72px] rounded-xl overflow-hidden relative border-2 ${
                      r.incompatible
                        ? isActive ? 'border-red-500' : 'border-red-200'
                        : isActive ? 'border-foreground' : 'border-transparent'
                    }`}
                  >
                    {r.image && (
                      <img
                        src={r.image}
                        alt={`Illustration ${r.type}`}
                        className={`w-full h-full object-cover ${
                          r.incompatible ? 'saturate-50' : ''
                        }`}
                        loading="lazy"
                      />
                    )}
                    {r.incompatible && (
                      <div className="absolute inset-0 flex items-center justify-center bg-red-500/20">
                        <X className="w-5 h-5 text-red-600" strokeWidth={3} />
                      </div>
                    )}
                  </div>
                  <span
                    className={`mt-1.5 text-[11px] font-satoshi font-bold leading-tight max-w-[80px] text-center line-clamp-2 ${
                      r.incompatible
                        ? 'text-red-700'
                        : isActive
                        ? 'text-foreground'
                        : 'text-foreground/60'
                    }`}
                  >
                    {r.type}
                  </span>
                </button>
              );
            })}
          </div>
        </ScrollReveal>
      </div>

      {/* Container avec le panneau actif (mobile + desktop) + les tabs desktop */}
      <div className="relative container mx-auto px-4 lg:px-8 max-w-5xl mt-4 lg:mt-0">
        <ScrollReveal>
          <div className="grid grid-cols-1 lg:grid-cols-[4fr_6fr] gap-6 lg:gap-10 items-start">
            {/* Desktop tabs — hidden sur mobile */}
            <div className="hidden lg:flex flex-col gap-2">
              {compatibleRoofs.map((r, i) => {
                const isActive = i === active;
                const compatibleIndex = r.incompatible
                  ? null
                  : compatibleRoofs.slice(0, i + 1).filter((x) => !x.incompatible).length;
                return (
                  <button
                    key={i}
                    onClick={() => setActive(i)}
                    className={`group flex items-center gap-4 text-left rounded-xl p-3 border transition-all ${
                      r.incompatible
                        ? isActive
                          ? 'border-red-500 bg-red-50 shadow-[0_4px_20px_rgba(220,38,38,0.12)]'
                          : 'border-red-200 bg-red-50/30 hover:border-red-300 hover:bg-red-50/60'
                        : isActive
                        ? 'border-foreground bg-white shadow-[0_4px_20px_rgba(26,42,58,0.06)]'
                        : 'border-foreground/10 bg-white/60 hover:border-foreground/25 hover:bg-white'
                    }`}
                  >
                    <div className="shrink-0 w-14 h-14 rounded-lg overflow-hidden bg-foreground/5 relative">
                      {r.image && (
                        <img
                          src={r.image}
                          alt={`Illustration ${r.type}`}
                          className={`w-full h-full object-cover ${
                            r.incompatible ? 'saturate-50 opacity-60' : ''
                          }`}
                          loading="lazy"
                        />
                      )}
                      {r.incompatible && (
                        <div className="absolute inset-0 flex items-center justify-center bg-red-500/20">
                          <X className="w-7 h-7 text-red-600" strokeWidth={3} />
                        </div>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-0.5">
                        {r.incompatible ? (
                          <span className="inline-flex items-center gap-1 text-[9px] font-bold uppercase tracking-[0.15em] text-red-600">
                            <AlertTriangle className="w-2.5 h-2.5" strokeWidth={2.5} />
                            {tc.nonCompatible}
                          </span>
                        ) : (
                          <span className="text-[10px] font-mono font-bold tabular-nums text-foreground/45">
                            {String(compatibleIndex!).padStart(2, '0')}
                          </span>
                        )}
                      </div>
                      <p className={`text-sm font-satoshi font-bold leading-snug truncate ${
                        r.incompatible ? 'text-red-900' : 'text-foreground'
                      }`}>
                        {r.type}
                      </p>
                    </div>
                  </button>
                );
              })}
            </div>

            {/* Panneau actif — shared mobile + desktop */}
            <div>
              <div className={`relative aspect-[4/3] rounded-2xl overflow-hidden mb-4 lg:mb-5 ${
                current.incompatible
                  ? 'bg-red-50 ring-2 ring-red-500'
                  : 'bg-foreground/5'
              }`}>
                {current.image && (
                  <img
                    src={current.image}
                    alt={`Illustration ${current.type}`}
                    className={`w-full h-full object-cover ${
                      current.incompatible ? 'saturate-50 opacity-70' : ''
                    }`}
                    loading="lazy"
                  />
                )}
                {current.incompatible && (
                  <>
                    <div className="absolute inset-0 bg-red-600/10" />
                    <div
                      aria-hidden="true"
                      className="absolute inset-0 opacity-[0.12] pointer-events-none"
                      style={{
                        backgroundImage:
                          'repeating-linear-gradient(45deg, rgb(220 38 38) 0, rgb(220 38 38) 12px, transparent 12px, transparent 28px)',
                      }}
                    />
                  </>
                )}
                <div className="absolute top-3 left-3 lg:top-4 lg:left-4">
                  {current.incompatible ? (
                    <span className="inline-flex items-center gap-1.5 bg-red-600 text-white text-[10px] lg:text-[11px] font-bold uppercase tracking-[0.15em] px-2.5 lg:px-3 py-1 lg:py-1.5 rounded-full shadow-[0_4px_16px_rgba(220,38,38,0.35)]">
                      <AlertTriangle className="w-3 h-3 lg:w-3.5 lg:h-3.5" strokeWidth={2.75} />
                      {tc.nonCompatible}
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1.5 bg-teal-vivid text-white text-[10px] lg:text-[11px] font-bold uppercase tracking-[0.15em] px-2.5 lg:px-3 py-1 lg:py-1.5 rounded-full shadow-[0_4px_16px_rgba(58,173,173,0.30)]">
                      <Check className="w-3 h-3 lg:w-3.5 lg:h-3.5" strokeWidth={2.75} />
                      {tc.compatible}
                    </span>
                  )}
                </div>
                {!current.incompatible && currentCompatibleIndex !== null && (
                  <span className="absolute top-3 right-3 lg:top-4 lg:right-4 inline-flex items-center bg-white/90 backdrop-blur-sm text-foreground text-[10px] font-mono font-bold tabular-nums px-2.5 py-1 rounded-full">
                    {String(currentCompatibleIndex).padStart(2, '0')}
                  </span>
                )}
              </div>

              <h3 className={`font-satoshi text-xl lg:text-3xl font-black mb-2 lg:mb-3 !leading-[1.1] ${
                current.incompatible ? 'text-red-900' : 'text-foreground'
              }`} style={{ letterSpacing: '-0.02em' }}>
                {current.type}
              </h3>
              <p className={`text-sm lg:text-base font-body leading-relaxed ${
                current.incompatible ? 'text-red-900/75' : 'text-foreground/70'
              }`}>
                {current.detail}
              </p>

              {current.incompatible && (
                <div className="mt-4 lg:mt-5 rounded-xl border border-red-200 bg-red-50/70 p-3 lg:p-4 flex gap-2.5 lg:gap-3">
                  <AlertTriangle className="w-4 h-4 lg:w-5 lg:h-5 text-red-600 shrink-0 mt-0.5" strokeWidth={2.25} />
                  <div className="text-xs lg:text-sm text-red-900/85 font-body leading-relaxed">
                    {tc.warning(productName)}
                  </div>
                </div>
              )}
            </div>
          </div>
          {footerNote && (
            <p className="text-xs text-foreground/70 font-body leading-relaxed mt-8 lg:mt-10 max-w-2xl">{footerNote}</p>
          )}
        </ScrollReveal>
      </div>
    </section>
  );
};

export default CompatibilityTabs;
