/* home.jsx — Cinematic dark home with fullscreen hero slider */

function HomePage({ onNavigate }) {
  const { t } = useLang();
  const { PORTFOLIO, SERVICES, PROCESS } = window.JMC_DATA;
  const featured = PORTFOLIO.filter(p => p.featured);

  return (
    <div className="dc-page-enter" data-screen-label="Home">
      <HomeHero onNavigate={onNavigate} />

      {/* MARQUEE band — running tech stack */}
      <DcMarquee items={t.home.marquee} />

      {/* CAPABILITIES preview */}
      <section className="dc-section" style={{ background: 'var(--canvas)' }}>
        <div className="dc-container">
          <DcReveal>
            <DcSectionHeader
              eyebrow={t.home.capabilities.eyebrow}
              title={t.home.capabilities.title}
              rightSlot={<DcTextLink onClick={() => onNavigate('services')}>{t.home.capabilities.seeAll}</DcTextLink>}
            />
          </DcReveal>
          <div className="dc-grid-3">
            {SERVICES.slice(0, 3).map((s, i) => (
              <DcReveal key={s.id} delay={i * 100}>
                <HomeCapabilityCard service={s} onNavigate={onNavigate} />
              </DcReveal>
            ))}
          </div>
        </div>
      </section>

      {/* SPEC ROW */}
      <DcSpecRow specs={t.home.stats} />

      {/* FEATURED case — QTS */}
      <FeaturedCase onNavigate={onNavigate} />

      {/* SHOWCASE GALLERY — big image grid */}
      <ShowcaseGallery onNavigate={onNavigate} />

      {/* DIGITAL TWIN — interactive feature */}
      <DigitalTwinSection onNavigate={onNavigate} />

      {/* PROCESS strip */}
      <HomeProcessStrip onNavigate={onNavigate} />

      {/* CTA with image bg */}
      <DcCTABand
        eyebrow={t.home.cta.eyebrow}
        title={t.home.cta.title}
        body={t.home.cta.body}
        primaryLabel={t.home.cta.primary}
        secondaryLabel={t.home.cta.secondary}
        onPrimary={() => onNavigate('contact')}
        onSecondary={() => onNavigate('portfolio')}
        image="assets/portfolio/bess-01.png"
      />
    </div>
  );
}

/* ─────────────────────── HERO with slider ───────────────────── */

function HomeHero({ onNavigate }) {
  const { t, lang } = useLang();

  // Each media item carries its own bilingual copy so images & copy never desync.
  const slideMedia = [
    { type: 'video', src: 'assets/portfolio/hero-anim.mp4',
      en: { eyebrow: 'Reel · UE5 cinematic build', title: ['Cinematic Infrastructure', 'Visualization'], accent: 'Visualization', sub: 'Hero films, real-time walkthroughs and AI-augmented concept work for data centers, energy storage, and renewable operators.', caption: 'QTS · Cinematic After Reel · UE5' },
      es: { eyebrow: 'Reel · Unreal Engine 5', title: ['Visualización Cinemática', 'de Infraestructura Crítica'], accent: 'Visualización Cinemática', sub: 'Films, recorridos en tiempo real y trabajo conceptual con IA para data centers, almacenamiento de energía y renovables.', caption: 'QTS · After Reel Cinematográfico · UE5' } },
    { type: 'image', src: 'assets/portfolio/oilgas-3d.png',
      en: { eyebrow: 'Oil & gas infrastructure', title: ['Oil & gas 3D visuals', 'that close deals'], accent: 'that close deals', sub: 'Process plants, administrative buildings and transmission corridors visualized specifically to make the financing case impossible to ignore.', caption: 'Pampa Energía · Process Plant · Sunset Hero' },
      es: { eyebrow: 'Infraestructura oil & gas', title: ['Imágenes 3D de oil & gas', 'que cierran negocios'], accent: 'que cierran negocios', sub: 'Plantas de proceso, edificios administrativos y corredores de transmisión — renderizados en golden hour para volver irresistible el caso de financiamiento.', caption: 'Pampa Energía · Planta de Proceso · Hero Atardecer' } },
    { type: 'video', src: 'assets/portfolio/hero-kling2.mp4',
      en: { eyebrow: 'Real-time camera', title: ['Camera moves', 'through finished sites'], accent: 'through finished sites', sub: 'A slow dolly across the campus — modeled to surveyed coordinates, lit to real spec, rendered live in Unreal Engine 5.', caption: 'Studio reel · Real-time camera · UE5' },
      es: { eyebrow: 'Cámara en tiempo real', title: ['La cámara recorre', 'sitios terminados'], accent: 'sitios terminados', sub: 'Un travelling lento por el campus — modelado sobre coordenadas reales, iluminado al proyecto, renderizado en vivo en Unreal Engine 5.', caption: 'Reel del estudio · Cámara en tiempo real · UE5' } },
    { type: 'image', src: 'assets/portfolio/qts-interior-red.png',
      en: { eyebrow: 'Inside the hall', title: ['Server halls,', 'rendered like film sets'], accent: 'rendered like film sets', sub: 'Branded data halls in cinematic light — the red glow, the endless aisle, the lit signage. The cathedrals of the compute era.', caption: 'QTS · Data Hall Interior · UE5' },
      es: { eyebrow: 'Dentro del hall', title: ['Salas de servidores,', 'iluminadas como sets de cine'], accent: 'iluminadas como sets de cine', sub: 'Data halls de marca con luz cinematográfica — el glow rojo, el pasillo infinito, la señalética iluminada. Las catedrales de la era del cómputo.', caption: 'QTS · Interior de Data Hall · UE5' } },
    { type: 'video', src: 'assets/portfolio/aerial-flythrough.mp4',
      en: { eyebrow: 'Aerial cinematography', title: ['Hyperscale campuses,', 'seen from above'], accent: 'seen from above', sub: 'A real-time aerial fly-through across a modern hyperscale campus — estuary, substation and the full site, all in one continuous shot.', caption: 'Hyperscale Campus · Aerial Fly-Through · UE5' },
      es: { eyebrow: 'Cinematografía aérea', title: ['Campus hyperscale,', 'vistos desde arriba'], accent: 'vistos desde arriba', sub: 'Un fly-through aéreo en tiempo real sobre un campus hyperscale moderno — estuario, subestación y el sitio completo, todo en una toma continua.', caption: 'Campus Hyperscale · Fly-Through Aéreo · UE5' } },
    { type: 'image', src: 'assets/portfolio/datahall-modern.png',
      en: { eyebrow: 'Architectural scale', title: ['Modern data halls,', '12.5 acres each'], accent: '12.5 acres each', sub: 'Glass-and-steel facades, raised plant decks, kilometre-long aisles — each hall a 12.5-acre building, rendered to convey the sheer scale on the ground.', caption: 'Modern Data Hall · Exterior · UE5 Path Traced' },
      es: { eyebrow: 'Escala arquitectónica', title: ['Data halls modernos,', '12,5 acres cada uno'], accent: '12,5 acres cada uno', sub: 'Fachadas de vidrio y acero, decks de plantas elevadas, pasillos de un kilómetro — cada hall un edificio de 12,5 acres, renderizado para transmitir la escala real en el terreno.', caption: 'Data Hall Moderno · Exterior · UE5 Path Traced' } },
    { type: 'image', src: 'assets/portfolio/datacenter-river.jpg',
      en: { eyebrow: 'Site in context', title: ['Campuses set', 'into their landscape'], accent: 'into their landscape', sub: 'A riverside data center campus at dawn — surrounding industry, transmission, water and green buffer. The full context in a single frame.', caption: 'Data Center Campus · Riverside · Aerial' },
      es: { eyebrow: 'El sitio en contexto', title: ['Campus integrados', 'a su paisaje'], accent: 'a su paisaje', sub: 'Un campus de data center sobre el río al amanecer — industria, transmisión, agua y buffer verde. Todo el contexto en una sola imagen.', caption: 'Data Center Campus · Sobre el Río · Aérea' } },
    { type: 'image', src: 'assets/portfolio/datacore-interior.jfif',
      en: { eyebrow: 'Architectural cinematography', title: ['Interiors that', 'sell the experience'], accent: 'sell the experience', sub: 'A technician walks the cold aisle as the sun sets behind the cooling towers — film-grade lighting, real materials, real scale.', caption: 'DataCore · Cold Aisle · UE5 Path Traced' },
      es: { eyebrow: 'Cinematografía arquitectónica', title: ['Interiores que', 'venden la experiencia'], accent: 'venden la experiencia', sub: 'Un técnico recorre el cold aisle mientras el sol cae tras las torres de enfriamiento — luz de cine, materiales reales, escala real.', caption: 'DataCore · Cold Aisle · UE5' } },
    { type: 'image', src: 'assets/portfolio/btc-datacenter.jpg',
      en: { eyebrow: 'Crypto & HPC', title: ['Compute campuses,', 'at neon dusk'], accent: 'at neon dusk', sub: 'BTC and HPC facilities lit with the brand\'s own signature addressable data halls, river frontage, the works.', caption: 'BTC Data Center · Dusk · Brand Lighting' },
      es: { eyebrow: 'Crypto & HPC', title: ['Campus de cómputo,', 'al atardecer neón'], accent: 'al atardecer neón', sub: 'Instalaciones BTC y HPC iluminadas con la firma de la marca — data halls direccionables, frente al río, todo.', caption: 'BTC Data Center · Atardecer · Luz de Marca' } },
    { type: 'image', src: 'assets/portfolio/datacenter-iso-02.png',
      en: { eyebrow: 'Clean isometric', title: ['3D models', 'that read at a glance'], accent: 'that read at a glance', sub: 'Isometric studies for board packs, permits and operations — the buildings, the halls, the connectivity bridges, all legible in one frame.', caption: 'Data Center Campus · Isometric · UE5' },
      es: { eyebrow: 'Isométrico claro', title: ['Modelos 3D', 'que se leen de un vistazo'], accent: 'que se leen de un vistazo', sub: 'Vistas isométricas para directorios, permisos y operaciones — los edificios, los halls, los puentes de conexión, todo legible en una imagen.', caption: 'Data Center Campus · Isométrico · UE5' } },
    { type: 'image', src: 'assets/portfolio/bess-investor-overlay.png',
      en: { eyebrow: 'Investor-ready', title: ['3D energy visuals', 'that win investors'], accent: 'that win investors', sub: 'Project-finance-grade visualization — a single hero frame, layered with typography, that anchors the entire pitch.', caption: 'BESS · Investor Hero · 16K' },
      es: { eyebrow: 'Listo para inversores', title: ['Imágenes 3D de energía', 'que convencen inversores'], accent: 'que convencen inversores', sub: 'Visualización a la altura de una ronda de inversión — una sola imagen, con tipografía, que sostiene toda la presentación.', caption: 'BESS · Hero de Inversión · 16K' } },
    { type: 'image', src: 'assets/portfolio/bess-overcast.png',
      en: { eyebrow: 'Aerial cinematography', title: ['Storm light,', 'permitted spec'], accent: 'permitted spec', sub: 'Wet pavement, overcast skies, transmission corridors on the horizon — every detail modeled to the operator\'s permit drawings.', caption: 'BESS · Aerial · Overcast Light' },
      es: { eyebrow: 'Cinematografía aérea', title: ['Luz de tormenta,', 'spec de permiso'], accent: 'spec de permiso', sub: 'Pavimento húmedo, cielo cubierto, corredores de transmisión en el horizonte — cada detalle modelado según los planos de permiso del operador.', caption: 'BESS · Aérea · Luz Cubierta' } },
    { type: 'image', src: 'assets/portfolio/bess-plan-render-bw.png',
      en: { eyebrow: 'Plan → reality', title: ['Complex layouts,', 'translated to cinema'], accent: 'translated to cinema', sub: 'We start where your architect leaves off. Technical plans become cinematic images — the same project, two languages.', caption: 'BESS · Plan & Render · Side-by-Side' },
      es: { eyebrow: 'Del plano a la imagen', title: ['Layouts complejos,', 'traducidos a cine'], accent: 'traducidos a cine', sub: 'Empezamos donde termina tu arquitecto. Planos técnicos se vuelven imágenes cinematográficas — el mismo proyecto, dos lenguajes.', caption: 'BESS · Plano y Render · Lado a Lado' } },
    { type: 'image', src: 'assets/portfolio/bess-iso-white.png',
      en: { eyebrow: 'Clarity', title: ['The substation,', 'the yard, one frame'], accent: 'the yard, one frame', sub: 'A clean isometric of the full BESS facility — substation, battery yard, admin building, all callable for board packs and permits.', caption: 'BESS · Iso Reference · White Background' },
      es: { eyebrow: 'Claridad', title: ['La subestación,', 'el yard, una imagen'], accent: 'el yard, una imagen', sub: 'Un isométrico limpio de toda la instalación BESS — subestación, yard de baterías, edificio administrativo, todo accesible para directorios y permisos.', caption: 'BESS · Iso de Referencia · Fondo Blanco' } },
    { type: 'image', src: 'assets/portfolio/infarm-testfit.png',
      en: { eyebrow: 'Test-fit & feasibility', title: ['BIM models,', 'turned into stories'], accent: 'turned into stories', sub: 'Test-fits, MEP schedules and density studies — we translate the technical case into a single annotated image stakeholders actually read.', caption: 'Infarm · Vertical Farming Hub · Test-Fit' },
      es: { eyebrow: 'Test-fit y factibilidad', title: ['Modelos BIM,', 'convertidos en relatos'], accent: 'convertidos en relatos', sub: 'Test-fits, planillas MEP y estudios de densidad — traducimos el caso técnico en una sola imagen anotada que los stakeholders sí leen.', caption: 'Infarm · Hub de Agricultura Vertical · Test-Fit' } },
    { type: 'image', src: 'assets/portfolio/uae-storage-hub.png',
      en: { eyebrow: 'Case studies', title: ['Logistics, energy,', 'and atmosphere'], accent: 'and atmosphere', sub: 'A UAE storage hub — solar array integration, weathered industrial materials, harsh desert light. A 1:1 preview of the future facility.', caption: 'UAE Storage Logistics Hub · 2025' },
      es: { eyebrow: 'Casos', title: ['Logística, energía', 'y atmósfera'], accent: 'y atmósfera', sub: 'Un hub de almacenamiento en EAU — integración solar, materiales industriales curtidos, luz dura del desierto. Una vista previa 1:1 de la futura instalación.', caption: 'Hub Logístico de Almacenamiento · EAU · 2025' } },
    { type: 'image', src: 'assets/portfolio/bess-solar-canopy.png',
      en: { eyebrow: 'Solar canopy', title: ['Energy infrastructure,', 'in detail'], accent: 'in detail', sub: 'Modular solar canopies over battery containers — modeled with the same discipline as a feature film set.', caption: 'BESS + Solar Canopy · Aerial Study' },
      es: { eyebrow: 'Canopy solar', title: ['Infraestructura energética,', 'en detalle'], accent: 'en detalle', sub: 'Canopies solares modulares sobre contenedores de baterías — modeladas con la misma disciplina que un set de cine.', caption: 'BESS + Canopy Solar · Estudio Aéreo' } },
    { type: 'image', src: 'assets/portfolio/bess-plan-to-real.png',
      en: { eyebrow: 'From the drawing', title: ['The plan and the render,', 'side by side'], accent: 'side by side', sub: 'A board pairing the Level 01 plan with the final aisle render — translating construction documents into something any board can approve.', caption: 'BESS · Plan → Render · Board Pairing' },
      es: { eyebrow: 'Desde el plano', title: ['El plano y el render,', 'lado a lado'], accent: 'lado a lado', sub: 'Un pareado del plano Nivel 01 con el render final del aisle — traduce documentos de obra en algo que cualquier directorio puede aprobar.', caption: 'BESS · Plano → Render · Pareado' } },
    { type: 'image', src: 'assets/portfolio/level-01-plan.png',
      en: { eyebrow: 'From the documents', title: ['We work from', 'your actual drawings'], accent: 'your actual drawings', sub: 'Level plans at 1:400, generator yards, fuel tanks, cooling plants — modeled to your real spec, not stock geometry.', caption: 'Level 01 Plan · Scale 1:400 · Source Document' },
      es: { eyebrow: 'Desde tus documentos', title: ['Trabajamos sobre', 'tus planos reales'], accent: 'tus planos reales', sub: 'Plantas a escala, salas técnicas, generadores, sistemas de refrigeración — modelados según tu proyecto real, no geometría genérica.', caption: 'Planta Nivel 01 · Escala 1:400 · Documento Fuente' } },
    { type: 'image', src: 'assets/portfolio/datacenter-iso-red.png',
      en: { eyebrow: 'Isometric clarity', title: ['3D models', 'that read at a glance'], accent: 'that read at a glance', sub: 'Isometric studies for board packs, public hearings and briefings — the building, the equipment, the circulation, legible in one frame.', caption: 'Data Center · Isometric View · UE5' },
      es: { eyebrow: 'Claridad isométrica', title: ['Modelos 3D', 'que se leen de un vistazo'], accent: 'que se leen de un vistazo', sub: 'Vistas isométricas para directorios, audiencias públicas y presentaciones — el edificio, los equipos, la circulación, legible en una imagen.', caption: 'Data Center · Vista Isométrica · UE5' } },
    { type: 'image', src: 'assets/portfolio/pampa-3d.png',
      en: { eyebrow: 'Industrial scale', title: ['Process plants,', 'energy, data centers'], accent: 'energy', sub: 'From process plants to GW-scale storage — the most consequential buildings of the moment, modeled with the same precision.', caption: 'Pampa Energía · Process Plant · Isometric' },
      es: { eyebrow: 'Escala industrial', title: ['Plantas industriales,', 'energía, data centers'], accent: 'energía', sub: 'De plantas de proceso a almacenamiento GW-scale — las obras más relevantes del momento, modeladas con la misma precisión.', caption: 'Pampa Energía · Planta de Proceso · Isométrico' } },
    { type: 'video', src: 'assets/portfolio/hero-kling.mp4',
      en: { eyebrow: 'Real-time camera', title: ['Cinematic moves.', 'Engineered detail.'], accent: 'Engineered detail', sub: 'A camera dolly through a finished site — modeled to surveyed coordinates, lit to real spec, rendered in Unreal Engine 5.', caption: 'Studio reel · Real-time camera · UE5' },
      es: { eyebrow: 'Cámara en tiempo real', title: ['Movimientos de cine.', 'Precisión técnica.'], accent: 'Precisión técnica', sub: 'Un recorrido de cámara por un sitio terminado — modelado sobre coordenadas reales, iluminado al proyecto, renderizado en Unreal Engine 5.', caption: 'Reel del estudio · Cámara en tiempo real · UE5' } },
    { type: 'image', src: 'assets/portfolio/bess-03.png',
      en: { eyebrow: 'Energy', title: ['Images that tell', 'the project\'s story'], accent: 'the project\'s story', sub: 'From the master plan to the final image — cinematic visualization for storage, solar and substations, delivered at 8K.', caption: 'Meridian BESS · Sunset · UE5' },
      es: { eyebrow: 'Energía', title: ['Imágenes que cuentan', 'la historia del proyecto'], accent: 'la historia del proyecto', sub: 'Del plan maestro a la imagen final — visualización cinemática para almacenamiento, solar y subestaciones, entregada en 8K.', caption: 'Meridian BESS · Atardecer · UE5' } },
    { type: 'image', src: 'assets/portfolio/jmc-night.png',
      en: { eyebrow: 'Brand image', title: ['The frame', 'that closes the deal'], accent: 'that closes the deal', sub: 'A single 16K hero still — the image that anchors the deck, the website, the lobby print, the board pack.', caption: 'JMC Realities · Night Facade · Brand Hero' },
      es: { eyebrow: 'Imagen de marca', title: ['La imagen', 'que cierra el trato'], accent: 'que cierra el trato', sub: 'Un único still hero en 16K — la imagen que ancla la presentación, la web, el print de lobby, el board pack.', caption: 'JMC Realities · Fachada Nocturna · Imagen de Marca' } },
    { type: 'image', src: 'assets/portfolio/qts-mountains.png',
      en: { eyebrow: 'Site in context', title: ['Designed to operate.', 'Rendered to convince.'], accent: 'Rendered to convince', sub: 'From exterior approach to interior detail — modeled to surveyed coordinates, lit to your real spec, delivered at 16K.', caption: 'QTS · Mountain Site · UE5' },
      es: { eyebrow: 'El sitio en contexto', title: ['Pensado para operar.', 'Renderizado para convencer.'], accent: 'Renderizado para convencer', sub: 'De la aproximación exterior al detalle interior — modelado sobre coordenadas reales, iluminado al proyecto, entregado en 16K.', caption: 'QTS · Sitio en Montaña · UE5' } },
    { type: 'image', src: 'assets/portfolio/pampa-aerial.png',
      en: { eyebrow: 'AI-augmented pipeline', title: ['Concepts in hours.', 'Flawless final images.'], accent: 'Flawless final images', sub: 'Our own AI models speed up the concept stage — every final image goes through the full render in Unreal Engine 5.', caption: 'Pampa Energía · Aerial · Final Image' },
      es: { eyebrow: 'Flujo aumentado con IA', title: ['Conceptos en horas.', 'Imágenes finales impecables.'], accent: 'Imágenes finales impecables', sub: 'Nuestros modelos de IA propios aceleran la etapa conceptual — cada imagen final pasa por el render completo en Unreal Engine 5.', caption: 'Pampa Energía · Vista Aérea · Imagen Final' } },
  ];

  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const timerRef = React.useRef(null);

  const count = slideMedia.length;

  // auto-advance — videos get more time
  React.useEffect(() => {
    if (paused) return;
    const duration = slideMedia[idx]?.type === 'video' ? 9000 : 6000;
    timerRef.current = setTimeout(() => {
      setIdx(i => (i + 1) % count);
    }, duration);
    return () => clearTimeout(timerRef.current);
  }, [idx, paused, count]);

  const goto = (i) => {
    clearTimeout(timerRef.current);
    setIdx(((i % count) + count) % count);
  };

  const slide = (slideMedia[idx] || slideMedia[0])[lang];

  // Render the title with the accent word highlighted
  const renderTitle = (titleLines, accentWord) => {
    return titleLines.map((line, i) => {
      if (line.includes(accentWord)) {
        const parts = line.split(accentWord);
        return (
          <span key={i} style={{ display: 'block' }}>
            {parts[0]}
            <em>{accentWord}</em>
            {parts[1]}
          </span>
        );
      }
      return <span key={i} style={{ display: 'block' }}>{line}</span>;
    });
  };

  return (
    <section className="dc-hero"
             onMouseEnter={() => setPaused(true)}
             onMouseLeave={() => setPaused(false)}>
      <div className="dc-hero-slides">
        {slideMedia.map((rawMedia, i) => {
          // Standalone builds can't bundle the large videos — fall back to a still.
          const fb = window.__videoFallback;
          const media = (fb && rawMedia?.type === 'video')
            ? { type: 'image', src: fb[rawMedia.src] || rawMedia.src }
            : rawMedia;
          return (
            <div key={i} className={'dc-hero-slide' + (i === idx ? ' active' : '')}>
              {media?.type === 'video' ? (
                <video className="dc-hero-video"
                       autoPlay muted loop playsInline
                       src={window.RES(media.src)}
                       key={i + '-' + idx} />
              ) : (
                <div className="dc-hero-image"
                     style={{ backgroundImage: `url("${window.RES(media?.src)}")` }}
                     key={i + '-' + idx} />
              )}
              <div className="dc-hero-overlay" />
            </div>
          );
        })}
      </div>

      <button className="dc-hero-arrow left" onClick={() => goto(idx - 1)} aria-label="Previous">
        <DcIcon name="chevronLeft" size={22} />
      </button>
      <button className="dc-hero-arrow right" onClick={() => goto(idx + 1)} aria-label="Next">
        <DcIcon name="chevronRight" size={22} />
      </button>

      <div className="dc-hero-content dc-container">
        <div key={idx} className="dc-hero-inner" style={{ animation: 'dcPageEnter 600ms var(--ease-standard) both' }}>
          <div className="dc-hero-headblock">
            <h1 className="dc-hero-title">
              {renderTitle(slide.title, slide.accent)}
            </h1>
          </div>
          <div className="dc-hero-footblock">
            <p className="dc-hero-sub">{slide.sub}</p>
            <div className="dc-hero-ctas">
              <button className="dc-hero-cta" onClick={() => onNavigate('contact')}>
                {t.hero.ctaSingle}
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="dc-hero-meta">
        <div className="dc-hero-caption">{slide.caption}</div>
        <div className="dc-hero-pager">
          {slideMedia.map((_, i) => (
            <button key={i}
                    className={'dc-hero-dot' + (i === idx ? ' active' : '')}
                    onClick={() => goto(i)} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────── Capability card ───────────────────── */

function HomeCapabilityCard({ service, onNavigate }) {
  const { lang } = useLang();
  return (
    <div className="dc-card" style={{ minHeight: 480 }}
         onClick={() => onNavigate('services')}>
      <DcPhoto src={service.image} aspectRatio="4/3"
               tag={service.eyebrow[lang]} />
      <div className="dc-card-body" style={{ padding: 28, gap: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--accent)' }}>
          <DcIcon name={service.icon} size={20} />
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase' }}>
            {service.eyebrow[lang]}
          </span>
        </div>
        <h4 style={{ fontSize: 24, fontWeight: 700, lineHeight: 1.2, margin: 0 }}>{service.title[lang]}</h4>
        <p style={{ fontSize: 14, fontWeight: 300, lineHeight: 1.6, color: 'var(--body)', margin: 0 }}>
          {service.body[lang]}
        </p>
        <div style={{ marginTop: 'auto', paddingTop: 16 }}>
          <DcTextLink>{lang === 'es' ? 'Conocer más' : 'Learn more'}</DcTextLink>
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────── Featured case ───────────────────── */

function FeaturedCase({ onNavigate }) {
  const { t, lang } = useLang();
  return (
    <section className="dc-section" style={{ background: 'var(--surface-soft)' }}>
      <div className="dc-container">
        <DcReveal>
          <DcSectionHeader
            eyebrow={t.home.featured.eyebrow}
            title={t.home.featured.title}
            rightSlot={<DcTextLink onClick={() => onNavigate('portfolio')}>{lang === 'es' ? 'Todos los proyectos' : 'All projects'}</DcTextLink>}
          />
        </DcReveal>
        <div className="dc-grid-2">
          <DcReveal>
            <DcPhoto
              src="assets/portfolio/bess-03.png"
              caption="Meridian BESS · Sunset · UE5 Path Traced"
              tag="Featured"
              tagAccent
              aspectRatio="4/3"
            />
          </DcReveal>
          <DcReveal delay={120}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
              <div className="dc-eyebrow muted">{t.home.featured.meta}</div>
              <h3 style={{ fontSize: 'clamp(28px, 3.5vw, 42px)', fontWeight: 700,
                            lineHeight: 1.1, margin: 0, letterSpacing: '-0.5px' }}>
                {t.home.featured.title}
              </h3>
              <p style={{ fontSize: 17, fontWeight: 300, lineHeight: 1.65,
                          color: 'var(--body)', margin: 0 }}>
                {t.home.featured.body}
              </p>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28,
                            padding: '28px 0', borderTop: '1px solid var(--hairline)',
                            borderBottom: '1px solid var(--hairline)' }}>
                {t.home.featured.specs.map(([k, v]) => (
                  <div key={k}>
                    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                                  textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>{k}</div>
                    <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--ink)',
                                  letterSpacing: '-0.3px' }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 12 }}>
                <DcBtn onClick={() => onNavigate('portfolio', { project: 'meridian-bess' })}>{t.home.featured.primary}</DcBtn>
                <DcBtn variant="secondary" onClick={() => onNavigate('contact')}>{t.home.featured.secondary}</DcBtn>
              </div>
            </div>
          </DcReveal>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────── Showcase grid (mosaic) ───────────────────── */

function ShowcaseGallery({ onNavigate }) {
  const { t, lang } = useLang();
  const { PORTFOLIO } = window.JMC_DATA;
  const items = [
    PORTFOLIO.find(p => p.id === 'meridian-bess'),
    PORTFOLIO.find(p => p.id === 'helios-solar'),
    PORTFOLIO.find(p => p.id === 'pampa-vacamuerta'),
    PORTFOLIO.find(p => p.id === 'qts-campus'),
    PORTFOLIO.find(p => p.id === 'riverside-campus'),
  ].filter(Boolean);

  return (
    <section className="dc-section" style={{ background: 'var(--canvas)' }}>
      <div className="dc-container">
        <DcReveal>
          <DcSectionHeader
            eyebrow={t.home.grid.eyebrow}
            title={t.home.grid.title}
            rightSlot={<DcTextLink onClick={() => onNavigate('portfolio')}>{t.home.grid.seeAll}</DcTextLink>}
          />
        </DcReveal>

        <div className="dc-grid-3">
          {items.slice(0, 3).map((p, i) => (
            <DcReveal key={p.id} delay={i * 80}>
              <ProjectThumb project={p} onNavigate={onNavigate} />
            </DcReveal>
          ))}
        </div>

        <div style={{ marginTop: 24 }} className="dc-grid-2">
          {items.slice(3, 5).map((p, i) => (
            <DcReveal key={p.id} delay={i * 80}>
              <ProjectThumb project={p} onNavigate={onNavigate} aspect="16/9" />
            </DcReveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProjectThumb({ project, onNavigate, aspect = '4/3' }) {
  const { lang } = useLang();
  return (
    <div className="dc-card" onClick={() => onNavigate('portfolio', { project: project.id })}>
      <DcPhoto src={project.image} aspectRatio={aspect}
               tag={project.tag} tagAccent={!!project.tag && project.tag !== ''} />
      <div className="dc-card-body">
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                      textTransform: 'uppercase', color: 'var(--accent)' }}>
          {[project.typeLabel[lang], project.year].filter(Boolean).join(' · ')}
        </div>
        <h4 style={{ fontSize: 22, fontWeight: 700, lineHeight: 1.2, margin: '4px 0 0' }}>
          {project.name}
        </h4>
        <div style={{ fontSize: 13, fontWeight: 300, color: 'var(--muted)', marginTop: 4 }}>
          {[project.locationLabel[lang], project.capacity].filter(Boolean).join(' · ')}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────── Process strip ───────────────────── */

function HomeProcessStrip({ onNavigate }) {
  const { t, lang } = useLang();
  const { PROCESS } = window.JMC_DATA;
  return (
    <section className="dc-section" style={{
      background: 'var(--surface-dark)',
      borderTop: '1px solid var(--hairline)',
      borderBottom: '1px solid var(--hairline)',
    }}>
      <div className="dc-container">
        <DcReveal>
          <div style={{ display: 'flex', justifyContent: 'space-between',
                        alignItems: 'flex-end', marginBottom: 56, gap: 32, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 640 }}>
              <div className="dc-eyebrow">{t.home.process.eyebrow}</div>
              <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 52px)', fontWeight: 700,
                           lineHeight: 1.05, margin: 0, letterSpacing: '-0.5px' }}>
                {t.home.process.title}
              </h2>
            </div>
            <DcTextLink onClick={() => onNavigate('about')}>{t.home.process.more}</DcTextLink>
          </div>
        </DcReveal>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
                       borderTop: '1px solid var(--hairline)',
                       borderLeft: '1px solid var(--hairline)' }}>
          {PROCESS.map(p => (
            <DcReveal key={p.n}>
              <div style={{
                padding: 36,
                borderRight: '1px solid var(--hairline)',
                borderBottom: '1px solid var(--hairline)',
                display: 'flex', flexDirection: 'column', gap: 14,
                minHeight: 220,
              }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--accent)',
                              letterSpacing: '2px' }}>{p.n}</div>
                <h5 style={{ fontSize: 20, fontWeight: 700, color: 'var(--ink)', margin: 0 }}>
                  {p[lang].label}
                </h5>
                <p style={{ fontSize: 14, fontWeight: 300, lineHeight: 1.65,
                            color: 'var(--body)', margin: 0 }}>
                  {p[lang].body}
                </p>
              </div>
            </DcReveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────── Digital Twin section ───────────────────── */

function DigitalTwinSection({ onNavigate }) {
  const { lang } = useLang();

  const copy = {
    en: {
      eyebrow: 'Digital Twin',
      title: 'A live, annotated, callable model of your campus.',
      body: 'Beyond a hero film — we deliver a navigable digital twin: data halls, cooling towers, power plant, control center, security perimeter, and connectivity bridges, all addressable individually. Use it in stakeholder pitches, planning hearings, and operations briefings.',
      bullets: [
        ['layers', 'Annotated components', 'Every IT module, transformer, and bridge — labeled and callable.'],
        ['cpu', 'Live spec swap', 'Cooling type, capacity, topology — change the model in real time.'],
        ['eye', 'Walk-and-talk', 'Camera flies, narration optional, runs on a laptop or LED wall.'],
        ['box', 'Hand-off ready', 'Packaged UE5 build delivered to your storage with a demo script.'],
      ],
      cta: 'Discuss your project',
      caption: 'Digital Twin · Axonometric Reference · UE5',
    },
    es: {
      eyebrow: 'Digital Twin',
      title: 'Un modelo vivo, anotado y navegable de tu campus.',
      body: 'Más allá del hero film — entregamos un digital twin navegable: data halls, torres de enfriamiento, planta eléctrica, centro de control, perímetro de seguridad y bridges de conectividad, cada uno direccionable. Usalo en pitches, audiencias y briefings de operaciones.',
      bullets: [
        ['layers', 'Componentes anotados', 'Cada módulo IT, transformador y bridge — etiquetado y direccionable.'],
        ['cpu', 'Swap de spec en vivo', 'Tipo de cooling, capacidad, topología — cambiá el modelo en tiempo real.'],
        ['eye', 'Walk-and-talk', 'Cámara vuela, narración opcional, corre en laptop o LED wall.'],
        ['box', 'Listo para entrega', 'Build UE5 packaged en tu storage, con guion de demo.'],
      ],
      cta: 'Conversemos tu proyecto',
      caption: 'Digital Twin · Referencia Axonométrica · UE5',
    },
  }[lang];

  return (
    <section className="dc-section" style={{
      background: 'var(--surface-dark)',
      borderTop: '1px solid var(--hairline)',
      borderBottom: '1px solid var(--hairline)',
    }}>
      <div className="dc-container">
        <DcReveal>
          <DcSectionHeader
            eyebrow={copy.eyebrow}
            title={copy.title}
            rightSlot={<DcTextLink onClick={() => onNavigate('contact')}>{copy.cta}</DcTextLink>}
          />
        </DcReveal>
        <div className="dc-grid-2">
          <DcReveal>
            <DcPhoto
              src="assets/portfolio/digital-twin.png"
              caption={copy.caption}
              tag="Interactive"
              tagAccent
              aspectRatio="4/3"
            />
          </DcReveal>
          <DcReveal delay={120}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
              <p style={{ fontSize: 17, fontWeight: 300, lineHeight: 1.65,
                          color: 'var(--body)', margin: 0 }}>
                {copy.body}
              </p>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20,
                            paddingTop: 20, borderTop: '1px solid var(--hairline)' }}>
                {copy.bullets.map(([icon, label, body]) => (
                  <div key={label} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--accent)' }}>
                      <DcIcon name={icon} size={18} />
                      <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px',
                                      textTransform: 'uppercase', color: 'var(--ink)' }}>{label}</span>
                    </div>
                    <p style={{ fontSize: 13, fontWeight: 300, lineHeight: 1.55,
                                 color: 'var(--body)', margin: 0 }}>{body}</p>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 8 }}>
                <DcBtn onClick={() => onNavigate('contact')}>{copy.cta}</DcBtn>
              </div>
            </div>
          </DcReveal>
        </div>
      </div>
    </section>
  );
}

window.HomePage = HomePage;