/* ─────────────────────────────────────────────────────────────
   CreacionesWeb · "Nuestras creaciones web"
   Carrusel horizontal con UNA principal destacada en primer plano,
   centrada y al máximo tamaño para apreciar la web. Cada video es un
   LOOP de highlights (las partes importantes de la web, recortadas y
   en ciclo). El chrome del navegador ya viene recortado en el video
   (16:9 limpio); arriba va una barra propia con el dominio.

   Videos: assets/showcase/<web>-loop.mp4 (+ -loop-poster.jpg)
   ───────────────────────────────────────────────────────────── */
const { useState, useRef, useEffect } = React;

const NG_CREACIONES = [
  {
    key: 'praxia', brand: 'Práxico', rubro: 'Psicomotricidad infantil · Montevideo',
    desc: 'Una web cálida y profesional que transmite su mirada, su formación y sus servicios, con contacto directo por WhatsApp.',
    domain: 'praxico.com.uy',
    video: 'assets/showcase/praxia-loop.mp4', poster: 'assets/showcase/praxia-loop-poster.jpg', logo: 'assets/showcase/logos/praxia.png',
  },
  {
    key: 'purewater', brand: 'PureWater UY', rubro: 'Purificadores de agua · Tienda online',
    desc: 'Una tienda con carrito y pago integrado por Mercado Pago, más un agente que asiste y vende mientras el cliente navega.',
    domain: 'purewateruy.com',
    video: 'assets/showcase/purewater-loop.mp4', poster: 'assets/showcase/purewater-loop-poster.jpg', logo: 'assets/showcase/logos/purewater.webp',
  },
  {
    key: 'donnabita', brand: 'Donna Bita', rubro: 'Lavandería · Montevideo',
    desc: 'Una web simple y clara: antes y después, promos y servicios siempre a la vista, con pedidos directos por WhatsApp.',
    domain: 'donnabita.com',
    video: 'assets/showcase/donnabita-loop.mp4', poster: 'assets/showcase/donnabita-loop-poster.jpg', logo: 'assets/showcase/logos/donnabita.png',
  },
  {
    key: 'psicovicky', brand: 'Victoria Villadeamigo', rubro: 'Psicología · Terapeuta sistémica · Montevideo',
    desc: 'Un espacio terapéutico con identidad propia: su enfoque, los beneficios y cómo son las sesiones, con agenda directa.',
    domain: 'psicovicky.com',
    video: 'assets/showcase/psicovicky-loop.mp4', poster: 'assets/showcase/psicovicky-loop-poster.jpg', logo: 'assets/showcase/logos/psicovicky.png',
  },
];

function CWBrowserBar({ domain }) {
  return (
    <div className="flex items-center gap-2 h-9 md:h-10 px-3.5 border-b border-line" style={{ background: '#0E1622' }}>
      <span className="size-2.5 rounded-full" style={{ background: '#FF5F57' }} aria-hidden="true" />
      <span className="size-2.5 rounded-full" style={{ background: '#FEBC2E' }} aria-hidden="true" />
      <span className="size-2.5 rounded-full" style={{ background: '#28C840' }} aria-hidden="true" />
      <div className="flex-1 ml-2 h-6 rounded-full flex items-center px-3 gap-1.5 font-mono text-[11px] md:text-[12px] text-ink/55 truncate"
        style={{ background: 'rgba(255,255,255,0.07)' }}>
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" aria-hidden="true" className="shrink-0 opacity-70">
          <rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" />
        </svg>
        {domain}
      </div>
    </div>
  );
}

function CreacionesWeb() {
  const Reveal = window.Reveal;
  const n = NG_CREACIONES.length;
  const [active, setActive] = useState(0);
  const [hover, setHover] = useState(false);
  const vrefs = useRef([]);
  const cur = NG_CREACIONES[active];

  /* Al cambiar de slide: reinicia y reproduce el activo desde el principio; pausa el resto. */
  useEffect(() => {
    vrefs.current.forEach((v, i) => {
      if (!v) return;
      if (i === active) {
        try { v.currentTime = 0; } catch (e) {}
        if (!hover) { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
      } else {
        v.pause();
      }
    });
  }, [active]);

  /* Hover pausa/reanuda el video activo (no salta al siguiente mientras lo mirás). */
  useEffect(() => {
    const v = vrefs.current[active];
    if (!v) return;
    if (hover) v.pause();
    else { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
  }, [hover, active]);

  const go = (d) => setActive((a) => (a + d + n) % n);

  return (
    <section id="creaciones" className="relative py-24 md:py-32 border-t border-line overflow-hidden">
      <div className="mx-auto max-w-[1280px] px-6 md:px-8">
        <Reveal>
          <div className="text-center mb-12 md:mb-14">
            <div className="kicker mb-4 inline-block">Trabajos entregados</div>
            <h2 className="display-lg text-[clamp(40px,5.4vw,82px)] max-w-[1000px] mx-auto mb-5">
              Nuestras <span className="italic text-cyan">creaciones</span> web.
            </h2>
            <p className="text-ink/80 text-[17px] md:text-[18px] max-w-[760px] mx-auto leading-[1.6]">
              Sitios reales que diseñamos y construimos. Esto es lo más lindo de cada uno, en ciclo.
            </p>
          </div>
        </Reveal>

        <Reveal delay={120}>
          {/* Escenario principal — grande, centrado y a ancho completo de la web */}
          <div className="relative mx-auto max-w-[1160px]"
            onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
            <div className="overflow-hidden rounded-2xl card-solid-2"
              style={{ boxShadow: '0 50px 120px -45px rgba(0,0,0,0.9), 0 0 0 1px rgba(51,194,234,0.2)' }}>
              <CWBrowserBar domain={cur.domain} />
              <div className="relative w-full bg-black" style={{ aspectRatio: '1280 / 588' }}>
                <div className="flex h-full" style={{ transform: `translateX(-${active * 100}%)`, transition: 'transform 650ms cubic-bezier(0.65,0,0.35,1)' }}>
                  {NG_CREACIONES.map((item, i) => (
                    <video key={item.key} ref={(el) => (vrefs.current[i] = el)} src={item.video} poster={item.poster}
                      muted playsInline preload="metadata"
                      onEnded={() => setActive((a) => (a + 1) % n)}
                      className="w-full h-full shrink-0" style={{ objectFit: 'cover' }} />
                  ))}
                </div>
              </div>
            </div>

            {/* flechas */}
            <button type="button" onClick={() => go(-1)} aria-label="Anterior"
              className="btn-cta absolute left-[-8px] md:left-[-22px] top-1/2 -translate-y-1/2 inline-flex items-center justify-center size-12 rounded-full"
              style={{ background: 'rgba(8,10,16,0.82)', border: '1px solid rgba(244,241,234,0.16)', color: '#F4F1EA' }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M15 18l-6-6 6-6" /></svg>
            </button>
            <button type="button" onClick={() => go(1)} aria-label="Siguiente"
              className="btn-cta absolute right-[-8px] md:right-[-22px] top-1/2 -translate-y-1/2 inline-flex items-center justify-center size-12 rounded-full"
              style={{ background: 'rgba(8,10,16,0.82)', border: '1px solid rgba(244,241,234,0.16)', color: '#F4F1EA' }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6" /></svg>
            </button>
          </div>
        </Reveal>

        {/* Info de la web activa (debajo, centrada) */}
        <div className="mx-auto max-w-[760px] text-center mt-7">
          <div className="flex items-center justify-center gap-3 flex-wrap">
            <h3 className="font-serif text-[30px] md:text-[36px] leading-tight text-ink/95">{cur.brand}</h3>
            <span className="inline-flex items-center gap-1.5 text-[10px] font-mono uppercase tracking-[0.18em] px-2.5 py-1 rounded-full"
              style={{ color: '#50D2A0', border: '1px solid rgba(80,210,160,0.4)', background: 'rgba(80,210,160,0.10)' }}>
              <span className="size-1.5 rounded-full" style={{ background: '#50D2A0' }} aria-hidden="true" />
              Entregado
            </span>
          </div>
          <div className="kicker mt-2">{cur.rubro}</div>
          <p className="text-[15px] md:text-[15.5px] text-ink/75 leading-[1.55] mt-3">{cur.desc}</p>
        </div>

        {/* Filmstrip */}
        <div className="flex flex-wrap gap-3 justify-center mt-7">
          {NG_CREACIONES.map((item, i) => {
            const on = i === active;
            return (
              <button key={item.key} type="button" onClick={() => setActive(i)}
                aria-label={`Ver ${item.brand}`} aria-current={on}
                className="group relative rounded-xl overflow-hidden transition-all duration-300"
                style={{
                  width: 132, border: on ? '2px solid rgba(51,194,234,0.9)' : '1px solid rgba(244,241,234,0.12)',
                  boxShadow: on ? '0 10px 30px -12px rgba(51,194,234,0.6)' : 'none', opacity: on ? 1 : 0.62,
                }}>
                <div className="relative w-full bg-black" style={{ aspectRatio: '1280 / 588' }}>
                  <img src={item.poster} alt="" className="absolute inset-0 w-full h-full" style={{ objectFit: 'cover' }} />
                  {/* badge con el logo de la web */}
                  <span className="absolute top-1.5 left-1.5 inline-flex items-center justify-center overflow-hidden"
                    style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(255,255,255,0.95)', boxShadow: '0 2px 6px rgba(0,0,0,0.4)' }}>
                    <img src={item.logo} alt={`Logo ${item.brand}`} className="w-full h-full" style={{ objectFit: 'contain', padding: 3 }} />
                  </span>
                </div>
                <div className="px-2 py-1.5 text-left flex items-center gap-1.5" style={{ background: 'rgba(8,10,16,0.92)' }}>
                  <img src={item.logo} alt="" className="shrink-0" style={{ width: 14, height: 14, objectFit: 'contain' }} />
                  <div className="text-[11px] font-medium text-ink/90 truncate">{item.brand}</div>
                </div>
              </button>
            );
          })}
        </div>

        <Reveal delay={120}>
          <div className="mt-10 text-center text-[15px]">
            <span className="text-mute">¿Querés la tuya? </span>
            <a href="#contacto" className="text-cyan underline-offset-4 hover:underline">Armamos tu web a medida →</a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

window.CreacionesWeb = CreacionesWeb;
