const { useState, useEffect, useRef, createContext, useContext } = React;

// — i18n ————————————————————————————————————————————————
const I18N = {
  en: {
    eyebrow: 'Operational blueprints',
    title: 'Systems in motion',
    subtitle: 'Diagnostics and operating systems for marketing, sales, operations, delivery, and AI risk — built after mapping the process, not before.',
    all: 'All',
    selectSystem: 'Select system',
    selectIndustry: 'Select industry',
    showing: 'Showing',
    of: 'of',
    clearSelection: 'Clear selection',
    noResults: 'No systems match those filters.',
    noResultsHint: 'Try clearing one of the dropdowns to see more blueprints.',
    reset: 'Reset filters',
    metaRow: 'Process · Risk · Automation',
    detail: {
      back: 'Back to all systems',
      overview: 'Overview',
      challenge: 'The challenge',
      approach: 'Our approach',
      outcomes: 'Outcomes',
      stack: 'Tools in play',
      duration: 'Engagement',
      zone: 'Location',
      cta: 'Book a diagnostic call',
      ctaSub: 'Every build starts with a diagnostic. We don\'t propose tooling before mapping the process.',
    },
    ctaEyebrow: 'The method',
    ctaTitle: ['Your process ', '+', ' our orchestration ', '=', ' scalable operations.'],
    ctaPrimary: 'Book a diagnostic call',
    ctaSecondary: 'See how diagnosis works →',
    sys: {
      Diagnostic: 'Diagnostic',
      Marketing: 'Marketing',
      Sales: 'Sales',
      Operations: 'Operations',
      Delivery: 'Delivery',
      'Cyber Security': 'Cyber Security',
      WhatsApp: 'WhatsApp',
      'CRM / Sheets': 'CRM / Sheets',
    },
    ind: {
      'B2B Services': 'B2B Services',
      'Aesthetic Clinic': 'Aesthetic Clinic',
      'Real Estate': 'Real Estate',
      Education: 'Education',
      Dental: 'Dental',
      Healthcare: 'Healthcare',
    },
    cta: {
      diagnostic: 'Explore diagnostic',
      system: 'Explore system',
      pipeline: 'Explore pipeline',
      flow: 'Explore flow',
      review: 'Explore review',
    },
    ctaPerCase: {
      1: 'Want clarity before automating?',
      2: 'Want your leads to arrive with context, not just questions?',
      3: 'Want your pipeline to stop living in WhatsApp?',
      4: 'Want to operate with control without burdening your team?',
      5: 'Want delivery not to end when the appointment ends?',
      6: 'Want to automate without opening unnecessary risks?',
    },
  },
  es: {
    eyebrow: 'Blueprints operativos',
    title: 'Sistemas en movimiento',
    subtitle: 'Diagnósticos y sistemas operativos para marketing, ventas, operaciones, delivery y riesgo de IA — construidos después de mapear el proceso, no antes.',
    all: 'Todos',
    selectSystem: 'Seleccionar sistema',
    selectIndustry: 'Seleccionar industria',
    showing: 'Mostrando',
    of: 'de',
    clearSelection: 'Limpiar selección',
    noResults: 'Ningún sistema coincide con esos filtros.',
    noResultsHint: 'Prueba a limpiar uno de los menús para ver más blueprints.',
    reset: 'Restablecer filtros',
    metaRow: 'Proceso · Riesgo · Automatización',
    detail: {
      back: 'Volver a todos los sistemas',
      overview: 'Visión general',
      challenge: 'El reto',
      approach: 'Nuestro enfoque',
      outcomes: 'Resultados',
      stack: 'Herramientas en juego',
      duration: 'Engagement',
      zone: 'Ubicación',
      cta: 'Agenda una llamada diagnóstica',
      ctaSub: 'Todo build empieza con diagnóstico. No proponemos tooling antes de mapear el proceso.',
    },
    ctaEyebrow: 'El método',
    ctaTitle: ['Tu proceso ', '+', ' nuestra orquestación ', '=', ' operaciones que escalan.'],
    ctaPrimary: 'Agenda una llamada diagnóstica',
    ctaSecondary: 'Conoce cómo funciona el diagnóstico →',
    sys: {
      Diagnostic: 'Diagnóstico',
      Marketing: 'Marketing',
      Sales: 'Ventas',
      Operations: 'Operaciones',
      Delivery: 'Delivery',
      'Cyber Security': 'Cyber Security',
      WhatsApp: 'WhatsApp',
      'CRM / Sheets': 'CRM / Sheets',
    },
    ind: {
      'B2B Services': 'Servicios B2B',
      'Aesthetic Clinic': 'Clínica estética',
      'Real Estate': 'Inmobiliario',
      Education: 'Educación',
      Dental: 'Dental',
      Healthcare: 'Salud',
    },
    cta: {
      diagnostic: 'Explorar diagnóstico',
      system: 'Explorar sistema',
      pipeline: 'Explorar pipeline',
      flow: 'Explorar flujo',
      review: 'Explorar revisión',
    },
    ctaPerCase: {
      1: '¿Quieres claridad antes de automatizar?',
      2: '¿Quieres que tus leads lleguen con contexto, no solo con preguntas?',
      3: '¿Quieres que tu pipeline deje de vivir en WhatsApp?',
      4: '¿Quieres operar con control sin complicar al equipo?',
      5: '¿Quieres que la entrega no termine cuando termina la cita?',
      6: '¿Quieres automatizar sin abrir riesgos innecesarios?',
    },
  },
};

const LangCtx = createContext({ lang: 'es', t: I18N.es });
const useLang = () => useContext(LangCtx);

// — Filter options ——————————————————————————————————————
const SYSTEMS = ['Diagnostic', 'Marketing', 'Sales', 'Operations', 'Delivery', 'Cyber Security', 'WhatsApp', 'CRM / Sheets'];
const INDUSTRIES = ['B2B Services', 'Aesthetic Clinic', 'Real Estate', 'Education', 'Dental', 'Healthcare'];

// Areas — primary badge label
const AREA = {
  Diagnostic: { en: 'DIAGNOSTIC', es: 'DIAGNÓSTICO' },
  Marketing: { en: 'MARKETING', es: 'MARKETING' },
  Sales: { en: 'SALES', es: 'VENTAS' },
  Operations: { en: 'OPERATIONS', es: 'OPERACIONES' },
  Delivery: { en: 'DELIVERY', es: 'DELIVERY' },
  'Cyber Security': { en: 'CYBER SECURITY', es: 'CYBER SECURITY' },
};

// Secondary badge — short label
const SYS_BADGE = {
  1: { en: 'OPERATIONAL MAPPING', es: 'MAPEO OPERATIVO' },
  2: { en: 'WHATSAPP CAPTURE', es: 'CAPTACIÓN WHATSAPP' },
  3: { en: 'WHATSAPP PIPELINE', es: 'PIPELINE WHATSAPP' },
  4: { en: 'LIGHT CRM', es: 'CRM LIGERO' },
  5: { en: 'POST-SERVICE', es: 'POST-SERVICIO' },
  6: { en: 'RISK REVIEW', es: 'RISK REVIEW' },
};

const STUDIES = [
  // 1 — Diagnostic — B2B services, Del Valle CDMX
  {
    id: 1,
    area: 'Diagnostic',
    industry: 'B2B Services',
    system: 'Diagnostic',
    zone: { en: 'Del Valle, Mexico City', es: 'Del Valle, Ciudad de México' },
    title: { en: 'Operational map for a company that grew faster than its processes', es: 'Mapa operativo para una empresa que creció más rápido que sus procesos' },
    description: { en: 'A diagnostic to clarify how leads come in, who handles them, where information gets lost, and which systems must exist before automating.', es: 'Un diagnóstico para ordenar cómo entran los leads, quién los atiende, dónde se pierde información y qué sistemas deben existir antes de automatizar.' },
    ctaKey: 'diagnostic',
  },
  // 2 — Marketing — Aesthetic clinic, Laureles Medellín
  {
    id: 2,
    area: 'Marketing',
    industry: 'Aesthetic Clinic',
    system: 'WhatsApp',
    zone: { en: 'Laureles, Medellín', es: 'Laureles, Medellín' },
    title: { en: 'Lead-capture flow for prospects asking about treatments and disappearing', es: 'Flujo de captación para leads que preguntan por tratamientos y desaparecen' },
    description: { en: 'A conversational system that receives inquiries, identifies real interest, answers initial questions, and structures every prospect before handing them to the team.', es: 'Un sistema conversacional que recibe consultas, identifica interés real, responde dudas iniciales y ordena cada prospecto antes de pasarlo al equipo.' },
    ctaKey: 'system',
  },
  // 3 — Sales — Real estate, Carretera a El Salvador, Guatemala
  {
    id: 3,
    area: 'Sales',
    industry: 'Real Estate',
    system: 'WhatsApp',
    zone: { en: 'Carretera a El Salvador, Guatemala', es: 'Carretera a El Salvador, Guatemala' },
    title: { en: 'Commercial pipeline for real estate prospects arriving by chat', es: 'Pipeline comercial para prospectos inmobiliarios que llegan por chat' },
    description: { en: 'A flow that classifies buyers, renters, and investors by budget, area, urgency, and the next commercial action.', es: 'Un flujo que clasifica compradores, rentistas e inversionistas por presupuesto, zona, urgencia y siguiente acción comercial.' },
    ctaKey: 'pipeline',
  },
  // 4 — Operations — Private academy, Núñez Buenos Aires
  {
    id: 4,
    area: 'Operations',
    industry: 'Education',
    system: 'CRM / Sheets',
    zone: { en: 'Núñez, Buenos Aires', es: 'Núñez, Buenos Aires' },
    title: { en: 'Operational dashboard to coordinate students, payments, schedules, and follow-up', es: 'Panel operativo para coordinar alumnos, pagos, horarios y seguimiento' },
    description: { en: 'A simple control layer so administration can see each student\'s status without depending on scattered messages between coordination, sales, and teachers.', es: 'Una capa de control simple para que administración vea el estado de cada alumno sin depender de mensajes sueltos entre coordinación, ventas y profesores.' },
    ctaKey: 'system',
  },
  // 5 — Delivery — Dental, Providencia Guadalajara
  {
    id: 5,
    area: 'Delivery',
    industry: 'Dental',
    system: 'WhatsApp',
    zone: { en: 'Providencia, Guadalajara', es: 'Providencia, Guadalajara' },
    title: { en: 'Post-consultation follow-up for patients who need continuity', es: 'Seguimiento post-consulta para pacientes que necesitan continuidad' },
    description: { en: 'A post-visit flow that accompanies the patient, reminds them of next steps, and surfaces questions before treatment continuity is lost.', es: 'Un flujo posterior a la visita que acompaña al paciente, recuerda próximos pasos y detecta dudas antes de que se pierda la continuidad del tratamiento.' },
    ctaKey: 'flow',
  },
  // 6 — Cyber Security — Healthcare business, Chapinero Bogotá
  {
    id: 6,
    area: 'Cyber Security',
    industry: 'Healthcare',
    system: 'Cyber Security',
    zone: { en: 'Chapinero, Bogotá', es: 'Chapinero, Bogotá' },
    title: { en: 'Risk review before connecting AI to sensitive data', es: 'Revisión de riesgo antes de conectar IA con datos sensibles' },
    description: { en: 'A pre-implementation review to surface accesses, exposed data, critical dependencies, and control points before scaling automation.', es: 'Una revisión pre-implementación para detectar accesos, datos expuestos, dependencias críticas y puntos de control antes de escalar automatización.' },
    ctaKey: 'review',
  },
];

// — Infinity glyph ——————————————————————————————————————
function InfinityMark({ className = '', size = 14 }) {
  return (
    <svg width={size} height={size * 0.5} viewBox="0 0 28 14" fill="none" className={className}>
      <path
        d="M7 7c0-2.5 2-4.5 4.5-4.5S14 4.5 14 7s2 4.5 4.5 4.5S23 9.5 23 7s-2-4.5-4.5-4.5S14 4.5 14 7s-2 4.5-4.5 4.5S5 9.5 5 7z"
        stroke="currentColor" strokeWidth="1.25" strokeLinecap="round"
      />
    </svg>
  );
}

// — Language toggle ————————————————————————————————————
function LangToggle({ lang, setLang }) {
  return (
    <div
      role="group"
      aria-label="Language"
      className="inline-flex items-center h-9 p-1 rounded-full border border-[#E2E2DC] bg-white text-[12px] font-medium tracking-wide"
    >
      {['en', 'es'].map((code) => (
        <button
          key={code}
          onClick={() => setLang(code)}
          aria-pressed={lang === code}
          className={
            "h-7 px-3 rounded-full transition-colors uppercase " +
            (lang === code ? "bg-[#0A0A0A] text-white" : "text-[#6B6B66] hover:text-[#0A0A0A]")
          }
        >
          {code}
        </button>
      ))}
    </div>
  );
}

// — Custom dropdown ————————————————————————————————————
function Dropdown({ label, value, displayValue, options, renderOption, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const { t } = useLang();

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className={
          "flex items-center justify-between gap-3 h-11 px-4 min-w-[210px] rounded-full border text-sm transition-colors " +
          (value
            ? "border-[#0A0A0A] bg-[#0A0A0A] text-white"
            : "border-[#E2E2DC] bg-white text-[#0A0A0A] hover:border-[#0A0A0A]")
        }
      >
        <span className={value ? "font-medium" : "text-[#6B6B66]"}>
          {value ? displayValue : label}
        </span>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" className={"transition-transform " + (open ? "rotate-180" : "")}>
          <path d="M3 5l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>

      {open && (
        <div className="absolute z-20 mt-2 left-0 w-[280px] rounded-2xl border border-[#E8E8E3] bg-white shadow-[0_8px_28px_-12px_rgba(10,10,10,0.18)] overflow-hidden py-1.5">
          {value && (
            <button
              onClick={() => { onChange(null); setOpen(false); }}
              className="w-full text-left px-4 py-2 text-sm text-[#6B6B66] hover:bg-[#F4F4EF]"
            >
              {t.clearSelection}
            </button>
          )}
          {options.map((opt) => (
            <button
              key={opt}
              onClick={() => { onChange(opt); setOpen(false); }}
              className={
                "w-full text-left px-4 py-2 text-sm transition-colors " +
                (opt === value ? "bg-[#F4F4EF] text-[#0A0A0A] font-medium" : "text-[#0A0A0A] hover:bg-[#F4F4EF]")
              }
            >
              {renderOption ? renderOption(opt) : opt}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// — Card ————————————————————————————————————————————————
function CaseStudyCard({ study, onOpen }) {
  const { lang, t } = useLang();
  return (
    <article
      onClick={() => onOpen(study)}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(study); } }}
      className="group relative flex flex-col justify-between rounded-3xl border border-[#E8E8E3] bg-white p-8 md:p-10 transition-all duration-300 hover:border-[#0A0A0A] hover:-translate-y-0.5 hover:shadow-[0_24px_60px_-30px_rgba(20,20,40,0.35)] cursor-pointer overflow-hidden focus:outline-none focus:ring-2 focus:ring-[#0A0A0A] focus:ring-offset-2 focus:ring-offset-[#FAFAF7]"
      style={{ minHeight: 360 }}
    >
      <svg
        className="absolute -right-24 -bottom-24 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none"
        width="320" height="320" viewBox="0 0 320 320" fill="none" aria-hidden="true"
      >
        <ellipse cx="160" cy="160" rx="150" ry="60" stroke="#0A0A0A" strokeWidth="0.6" opacity="0.25" />
        <ellipse cx="160" cy="160" rx="150" ry="60" stroke="#0A0A0A" strokeWidth="0.6" opacity="0.18" transform="rotate(35 160 160)" />
        <circle cx="160" cy="160" r="2" fill="#0A0A0A" opacity="0.4" />
      </svg>

      <div className="relative">
        <div className="flex flex-wrap items-center gap-2 mb-3">
          <span className="inline-flex items-center h-7 px-3 rounded-full bg-[#F4F4EF] text-[#3A3A35] text-[11px] font-medium tracking-[0.08em] uppercase">
            {AREA[study.area][lang]}
          </span>
          <span className="inline-flex items-center h-7 px-3 rounded-full border border-[#E8E8E3] text-[#6B6B66] text-[11px] font-medium tracking-[0.08em] uppercase">
            {SYS_BADGE[study.id][lang]}
          </span>
        </div>

        <div className="flex items-center gap-1.5 mb-6 text-[11px] tracking-[0.08em] uppercase text-[#9A9A92]">
          <svg width="10" height="12" viewBox="0 0 10 12" fill="none" aria-hidden="true">
            <path d="M5 11s4-3.6 4-7a4 4 0 1 0-8 0c0 3.4 4 7 4 7z" stroke="currentColor" strokeWidth="1" />
            <circle cx="5" cy="4" r="1.3" stroke="currentColor" strokeWidth="1" />
          </svg>
          <span>{study.zone[lang]}</span>
        </div>

        <h3 className="font-serif text-[26px] md:text-[30px] leading-[1.15] text-[#0A0A0A] mb-4 text-pretty">
          {study.title[lang]}
        </h3>

        <p className="text-[15px] leading-[1.6] text-[#5A5A55] text-pretty max-w-[46ch]">
          {study.description[lang]}
        </p>
      </div>

      <div className="relative mt-8 flex items-center justify-between gap-3">
        <button
          type="button"
          onClick={(e) => { e.stopPropagation(); onOpen(study); }}
          className="flex items-center gap-2 text-[14px] font-medium text-[#0A0A0A]"
        >
          <InfinityMark className="text-[#0A0A0A] opacity-70" size={16} />
          <span>{t.cta[study.ctaKey]}</span>
          <span className="inline-flex items-center justify-center w-7 h-7 rounded-full border border-[#E8E8E3] transition-all group-hover:bg-[#0A0A0A] group-hover:border-[#0A0A0A] group-hover:text-white">
            <svg width="11" height="11" viewBox="0 0 11 11" fill="none">
              <path d="M2 9L9 2M9 2H3.5M9 2V7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </span>
        </button>
        <span className="text-[10.5px] tracking-[0.14em] uppercase text-[#9A9A92]">
          {t.metaRow}
        </span>
      </div>
    </article>
  );
}

// — Detail modal ————————————————————————————————————————
function StudyDetailModal({ study, onClose }) {
  const { lang, t } = useLang();
  const detail = (window.STUDY_DETAILS || {})[study.id];

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);

  if (!detail) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onClick={onClose}>
        <div className="bg-white rounded-2xl p-8 max-w-md text-center" onClick={(e) => e.stopPropagation()}>
          <p className="text-[#5A5A55] mb-4">No detail available for this study yet.</p>
          <button onClick={onClose} className="h-10 px-5 rounded-full bg-[#0A0A0A] text-white text-sm font-medium">Close</button>
        </div>
      </div>
    );
  }

  const ctaHeadline = t.ctaPerCase[study.id];

  return (
    <div
      className="fixed inset-0 z-50 bg-black/45 backdrop-blur-sm overflow-y-auto"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
    >
      <div className="min-h-full flex items-start justify-center p-4 md:p-10">
        <div
          className="relative w-full max-w-[960px] bg-[#FAFAF7] rounded-[28px] shadow-[0_30px_80px_-20px_rgba(0,0,0,0.4)] overflow-hidden"
          onClick={(e) => e.stopPropagation()}
        >
          <button
            onClick={onClose}
            aria-label="Close"
            className="absolute top-5 right-5 z-10 inline-flex items-center justify-center w-10 h-10 rounded-full bg-white border border-[#E8E8E3] hover:bg-[#0A0A0A] hover:text-white hover:border-[#0A0A0A] transition-colors"
          >
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
            </svg>
          </button>

          <div className="relative bg-white border-b border-[#E8E8E3] px-8 md:px-14 pt-12 pb-10 overflow-hidden">
            <svg
              className="absolute -right-16 -top-16 opacity-[0.06] pointer-events-none"
              width="380" height="380" viewBox="0 0 380 380" fill="none" aria-hidden="true"
            >
              <circle cx="190" cy="190" r="189" stroke="#0A0A0A" />
              <circle cx="190" cy="190" r="140" stroke="#0A0A0A" />
              <circle cx="190" cy="190" r="90" stroke="#0A0A0A" />
            </svg>

            <button
              onClick={onClose}
              className="relative inline-flex items-center gap-2 text-[12px] tracking-[0.14em] uppercase text-[#6B6B66] hover:text-[#0A0A0A] mb-6"
            >
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                <path d="M7.5 2L3 6l4.5 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              {t.detail.back}
            </button>

            <div className="relative flex flex-wrap items-center gap-2 mb-3">
              <span className="inline-flex items-center h-7 px-3 rounded-full bg-[#F4F4EF] text-[#3A3A35] text-[11px] font-medium tracking-[0.08em] uppercase">
                {AREA[study.area][lang]}
              </span>
              <span className="inline-flex items-center h-7 px-3 rounded-full border border-[#E8E8E3] text-[#6B6B66] text-[11px] font-medium tracking-[0.08em] uppercase">
                {SYS_BADGE[study.id][lang]}
              </span>
              <span className="inline-flex items-center h-7 px-3 rounded-full border border-[#E8E8E3] text-[#6B6B66] text-[11px] font-medium tracking-[0.08em] uppercase">
                {t.ind[study.industry]}
              </span>
            </div>

            <div className="relative flex items-center gap-1.5 mb-6 text-[11px] tracking-[0.08em] uppercase text-[#9A9A92]">
              <svg width="10" height="12" viewBox="0 0 10 12" fill="none" aria-hidden="true">
                <path d="M5 11s4-3.6 4-7a4 4 0 1 0-8 0c0 3.4 4 7 4 7z" stroke="currentColor" strokeWidth="1" />
                <circle cx="5" cy="4" r="1.3" stroke="currentColor" strokeWidth="1" />
              </svg>
              <span>{study.zone[lang]}</span>
            </div>

            <h2 className="relative font-serif text-[36px] md:text-[52px] leading-[1.05] tracking-[-0.01em] text-[#0A0A0A] mb-6 text-pretty max-w-[28ch]">
              {study.title[lang]}
            </h2>

            <p className="relative text-[16px] md:text-[17px] leading-[1.6] text-[#3A3A35] max-w-[60ch] text-pretty">
              {study.description[lang]}
            </p>

            <div className="relative mt-10 grid grid-cols-2 md:grid-cols-3 gap-6 pt-8 border-t border-[#E8E8E3]">
              <div>
                <div className="text-[10.5px] tracking-[0.14em] uppercase text-[#9A9A92] mb-1.5">{t.detail.duration}</div>
                <div className="text-[15px] font-medium text-[#0A0A0A] mt-1">{detail.duration[lang]}</div>
              </div>
              <div>
                <div className="text-[10.5px] tracking-[0.14em] uppercase text-[#9A9A92] mb-1.5">{t.detail.zone}</div>
                <div className="text-[15px] font-medium text-[#0A0A0A] mt-1">{study.zone[lang]}</div>
              </div>
              <div className="col-span-2 md:col-span-1">
                <div className="text-[10.5px] tracking-[0.14em] uppercase text-[#9A9A92] mb-1.5">{t.detail.stack}</div>
                <div className="flex flex-wrap gap-1.5 mt-1">
                  {detail.stack.map((s) => (
                    <span key={s} className="inline-flex items-center h-6 px-2.5 rounded-md bg-[#F4F4EF] text-[#3A3A35] text-[11px] font-medium">{s}</span>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="px-8 md:px-14 py-12 space-y-12">
            <Section label={t.detail.overview} body={detail.overview[lang]} />
            <Section label={t.detail.challenge} body={detail.challenge[lang]} />

            <div>
              <SectionLabel>{t.detail.approach}</SectionLabel>
              <ol className="space-y-4">
                {detail.approach.map((step, i) => (
                  <li key={i} className="flex gap-4">
                    <span className="font-serif text-[24px] leading-none text-[#9A9A92] w-8 shrink-0 pt-1">{String(i + 1).padStart(2, '0')}</span>
                    <span className="text-[16px] leading-[1.6] text-[#3A3A35] text-pretty pt-1.5">{step[lang]}</span>
                  </li>
                ))}
              </ol>
            </div>

            <div>
              <SectionLabel>{t.detail.outcomes}</SectionLabel>
              <ul className="space-y-3">
                {detail.outcomes.map((o, i) => (
                  <li key={i} className="flex gap-3 items-start">
                    <span className="mt-2.5 inline-block w-1.5 h-1.5 rounded-full bg-[#0A0A0A] shrink-0"></span>
                    <span className="text-[16px] leading-[1.6] text-[#3A3A35] text-pretty">{o[lang]}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>

          <div className="relative bg-[#0A0A0A] text-white px-8 md:px-14 py-12 overflow-hidden">
            <svg
              className="absolute -right-10 -bottom-20 opacity-[0.08] pointer-events-none"
              width="320" height="320" viewBox="0 0 320 320" fill="none" aria-hidden="true"
            >
              <circle cx="160" cy="160" r="159" stroke="white" />
              <circle cx="160" cy="160" r="110" stroke="white" />
              <circle cx="160" cy="160" r="60" stroke="white" />
            </svg>
            <div className="relative flex flex-col md:flex-row md:items-center md:justify-between gap-6">
              <div className="max-w-[40ch]">
                <h3 className="font-serif text-[26px] md:text-[30px] leading-[1.15] mb-2 text-pretty">{ctaHeadline}</h3>
                <p className="text-[14px] text-white/60 text-pretty">{t.detail.ctaSub}</p>
              </div>
              <a href="https://calendly.com/ceo-neooagency/30min" target="_blank" rel="noopener noreferrer" className="group inline-flex items-center gap-3 h-12 pl-6 pr-2 rounded-full bg-white text-[#0A0A0A] text-[15px] font-medium hover:bg-[#F4F4EF] transition-colors self-start md:self-center shrink-0">
                {t.detail.cta}
                <span className="inline-flex items-center justify-center w-9 h-9 rounded-full bg-[#0A0A0A] text-white transition-transform group-hover:translate-x-0.5">
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                    <path d="M2 10L10 2M10 2H4M10 2V8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function SectionLabel({ children }) {
  return (
    <div className="flex items-center gap-3 mb-5">
      <span className="w-6 h-px bg-[#0A0A0A]"></span>
      <span className="text-[11px] tracking-[0.18em] uppercase text-[#0A0A0A] font-medium">{children}</span>
    </div>
  );
}

function Section({ label, body }) {
  return (
    <div>
      <SectionLabel>{label}</SectionLabel>
      <p className="text-[16px] md:text-[17px] leading-[1.65] text-[#3A3A35] text-pretty max-w-[68ch]">{body}</p>
    </div>
  );
}

// — Main section ————————————————————————————————————————
function NEOOCaseStudiesSection() {
  const [lang, setLang] = useState('es');
  const [system, setSystem] = useState(null);
  const [industry, setIndustry] = useState(null);
  const [openStudy, setOpenStudy] = useState(null);
  const t = I18N[lang];

  const filtered = STUDIES.filter((s) => {
    if (system && s.system !== system && s.area !== system) return false;
    if (industry && s.industry !== industry) return false;
    return true;
  });

  const allActive = !system && !industry;

  return (
    <LangCtx.Provider value={{ lang, t }}>
      <section className="bg-[#FAFAF7] text-[#0A0A0A] font-sans">
        <div className="mx-auto max-w-[1240px] px-6 md:px-10 py-20 md:py-28">

          <div className="flex justify-end mb-10">
            <LangToggle lang={lang} setLang={setLang} />
          </div>

          <header className="max-w-3xl mb-16 md:mb-20">
            <div className="flex items-center gap-2 mb-6 text-[12px] tracking-[0.18em] uppercase text-[#6B6B66]">
              <span className="w-6 h-px bg-[#6B6B66]"></span>
              <InfinityMark className="text-[#6B6B66]" size={14} />
              <span>{t.eyebrow}</span>
            </div>
            <h1 className="font-serif text-[56px] md:text-[88px] leading-[0.98] tracking-[-0.02em] mb-6 text-pretty">
              {t.title}
            </h1>
            <p className="text-[17px] md:text-[19px] leading-[1.55] text-[#3A3A35] max-w-[58ch] text-pretty">
              {t.subtitle}
            </p>
          </header>

          <div className="flex flex-wrap items-center gap-3 mb-10 md:mb-14">
            <button
              onClick={() => { setSystem(null); setIndustry(null); }}
              className={
                "h-11 px-6 rounded-full text-sm font-medium border transition-colors " +
                (allActive
                  ? "bg-[#0A0A0A] border-[#0A0A0A] text-white"
                  : "bg-white border-[#E2E2DC] text-[#0A0A0A] hover:border-[#0A0A0A]")
              }
            >
              {t.all}
              <span className={"ml-2 text-[12px] " + (allActive ? "text-white/70" : "text-[#6B6B66]")}>
                {STUDIES.length}
              </span>
            </button>

            <Dropdown
              label={t.selectSystem}
              value={system}
              displayValue={system ? t.sys[system] : ''}
              options={SYSTEMS}
              renderOption={(opt) => t.sys[opt]}
              onChange={setSystem}
            />

            <Dropdown
              label={t.selectIndustry}
              value={industry}
              displayValue={industry ? t.ind[industry] : ''}
              options={INDUSTRIES}
              renderOption={(opt) => t.ind[opt]}
              onChange={setIndustry}
            />

            <div className="ml-auto text-[13px] text-[#6B6B66]">
              {t.showing} <span className="text-[#0A0A0A] font-medium">{filtered.length}</span> {t.of} {STUDIES.length}
            </div>
          </div>

          {filtered.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5 md:gap-6">
              {filtered.map((s) => <CaseStudyCard key={s.id} study={s} onOpen={setOpenStudy} />)}
            </div>
          ) : (
            <div className="rounded-3xl border border-dashed border-[#E2E2DC] bg-white py-20 px-6 text-center">
              <p className="font-serif text-2xl mb-2">{t.noResults}</p>
              <p className="text-[#6B6B66] text-sm mb-6">{t.noResultsHint}</p>
              <button
                onClick={() => { setSystem(null); setIndustry(null); }}
                className="h-10 px-5 rounded-full bg-[#0A0A0A] text-white text-sm font-medium hover:bg-[#1F1F1A] transition-colors"
              >
                {t.reset}
              </button>
            </div>
          )}

          <div className="mt-24 md:mt-32">
            <div className="relative overflow-hidden rounded-[28px] bg-[#0A0A0A] text-white px-8 md:px-16 py-16 md:py-24">
              <svg
                className="absolute -right-20 -bottom-32 opacity-[0.07] pointer-events-none"
                width="560" height="560" viewBox="0 0 560 560" fill="none" aria-hidden="true"
              >
                <circle cx="280" cy="280" r="279" stroke="white" strokeWidth="1" />
                <circle cx="280" cy="280" r="220" stroke="white" strokeWidth="1" />
                <circle cx="280" cy="280" r="160" stroke="white" strokeWidth="1" />
                <circle cx="280" cy="280" r="100" stroke="white" strokeWidth="1" />
              </svg>
              <svg
                className="absolute -left-24 top-1/2 -translate-y-1/2 opacity-[0.06] pointer-events-none"
                width="520" height="260" viewBox="0 0 520 260" fill="none" aria-hidden="true"
              >
                <ellipse cx="260" cy="130" rx="240" ry="90" stroke="white" strokeWidth="1" />
                <ellipse cx="260" cy="130" rx="240" ry="90" stroke="white" strokeWidth="1" transform="rotate(20 260 130)" />
                <ellipse cx="260" cy="130" rx="240" ry="90" stroke="white" strokeWidth="1" transform="rotate(-20 260 130)" />
              </svg>

              <div className="relative max-w-3xl">
                <div className="flex items-center gap-2 mb-6 text-[12px] tracking-[0.18em] uppercase text-white/50">
                  <span className="w-6 h-px bg-white/40"></span>
                  <InfinityMark className="text-white/60" size={14} />
                  <span>{t.ctaEyebrow}</span>
                </div>
                <h2 className="font-serif text-[44px] md:text-[68px] leading-[1.0] tracking-[-0.02em] mb-8 text-pretty">
                  {t.ctaTitle[0]}<span className="text-white/50">{t.ctaTitle[1]}</span>{t.ctaTitle[2]}<span className="text-white/50">{t.ctaTitle[3]}</span>{t.ctaTitle[4]}
                </h2>
                <div className="flex flex-wrap items-center gap-4">
                  <a href="https://calendly.com/ceo-neooagency/30min" target="_blank" rel="noopener noreferrer" className="group inline-flex items-center gap-3 h-12 pl-6 pr-2 rounded-full bg-white text-[#0A0A0A] text-[15px] font-medium hover:bg-[#F4F4EF] transition-colors">
                    {t.ctaPrimary}
                    <span className="inline-flex items-center justify-center w-9 h-9 rounded-full bg-[#0A0A0A] text-white transition-transform group-hover:translate-x-0.5">
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                        <path d="M2 10L10 2M10 2H4M10 2V8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    </span>
                  </a>
                  <a href="https://calendly.com/ceo-neooagency/30min" target="_blank" rel="noopener noreferrer" className="text-[14px] text-white/60 hover:text-white transition-colors underline-offset-4 hover:underline">
                    {t.ctaSecondary}
                  </a>
                </div>
              </div>
            </div>
          </div>

        </div>

        {openStudy && <StudyDetailModal study={openStudy} onClose={() => setOpenStudy(null)} />}
      </section>
    </LangCtx.Provider>
  );
}

window.NEOOCaseStudiesSection = NEOOCaseStudiesSection;
window.CaseStudiesSection = NEOOCaseStudiesSection;
