/* Hero slider — full-bleed promotional banners with image slots */

const HeroSlider = ({ onNavigate }) => {
  const slides = [
  {
    id: 'banner-black',
    src: 'uploads/PORTADA PÁGINA PRUEBA 3-0a58125f.jpg',
    srcMobile: 'uploads/PORTADA PÁGINA PRUEBA 3 MOBILE-9729cb3d.jpg',
    alt: 'Equipos de Limpieza Profesional e Industrial',
    route: '/tienda'
  },
  {
    id: 'banner-red',
    src: 'uploads/PORTADA PÁGINA PRUEBA 1-13027773.jpg',
    srcMobile: 'uploads/PORTADA PÁGINA PRUEBA 1 MOBILE.jpg',
    alt: 'Hasta 12 cuotas sin interés en toda la web',
    route: '/tienda'
  }];


  const [idx, setIdx] = React.useState(0);
  const total = slides.length;

  // Track mobile viewport so we can swap to portrait-format art when applicable
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' && window.matchMedia('(max-width: 768px)').matches
  );
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 768px)');
    const handler = (e) => setIsMobile(e.matches);
    mq.addEventListener ? mq.addEventListener('change', handler) : mq.addListener(handler);
    return () => {
      mq.removeEventListener ? mq.removeEventListener('change', handler) : mq.removeListener(handler);
    };
  }, []);

  // Edit mode for VER+ pills: Alt+E to toggle, drag to position, click "Copiar" to log coords.
  const initialCtas = React.useMemo(() => {
    const out = {};
    slides.forEach((s) => (s.hotspots || []).forEach((h) => { out[h.label] = h.cta || { top: '50%', left: '50%' }; }));
    return out;
  }, []);
  const [ctaPositions, setCtaPositions] = React.useState(initialCtas);
  const [editMode, setEditMode] = React.useState(false);
  const [drag, setDrag] = React.useState(null); // { label, hotspotRect }

  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.altKey || e.metaKey) && (e.key === 'e' || e.key === 'E')) {
        e.preventDefault(); setEditMode((m) => !m);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  React.useEffect(() => {
    if (!drag) return;
    const onMove = (e) => {
      const r = drag.hotspotRect;
      const x = ((e.clientX - r.left) / r.width) * 100;
      const y = ((e.clientY - r.top) / r.height) * 100;
      setCtaPositions((p) => ({ ...p, [drag.label]: { top: `${Math.max(0, Math.min(100, y)).toFixed(1)}%`, left: `${Math.max(0, Math.min(100, x)).toFixed(1)}%` } }));
    };
    const onUp = () => setDrag(null);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
  }, [drag]);

  const copyCoords = async () => {
    const text = JSON.stringify(ctaPositions, null, 2);
    try { await navigator.clipboard.writeText(text); alert('Coordenadas copiadas al portapapeles. Pegámelas en el chat.'); }
    catch { console.log('CTA coords:', text); alert('Copiá del log de consola: ' + text); }
  };

  const go = (i) => setIdx((i % total + total) % total);
  const next = () => go(idx + 1);
  const prev = () => go(idx - 1);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowLeft') prev();
      if (e.key === 'ArrowRight') next();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [idx]);

  return (
    <section
      className="hero-section"
      style={{ background: '#0A1A2F', position: 'relative', overflow: 'hidden', width: '100%' }}>
      
      {/* Slides stack — aspect-locked to banner art (desktop 1920×757 / mobile 1080×1652).
          On mobile the hero is also height-capped so the top announce strip + header +
          bottom marquee bar all fit on screen alongside the banner. image-slot's cover
          fit absorbs the slight crop. */}
      <div
        onTouchStart={(e) => {
          const t = e.changedTouches[0];
          window.__heroSwipe = { x: t.clientX, y: t.clientY, t: Date.now() };
        }}
        onTouchEnd={(e) => {
          const s = window.__heroSwipe;
          if (!s) return;
          const t = e.changedTouches[0];
          const dx = t.clientX - s.x;
          const dy = t.clientY - s.y;
          const dt = Date.now() - s.t;
          window.__heroSwipe = null;
          // Horizontal intent + fast enough flick or large enough drag
          if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy) * 1.4 && dt < 800) {
            if (dx < 0) next(); else prev();
          }
        }}
        style={{
        position: 'relative', width: '100%',
        aspectRatio: isMobile ? '1080 / 1652' : '1920 / 757',
        maxHeight: isMobile ? 'calc(100dvh - 170px)' : 'none',
        touchAction: 'pan-y'
      }}>
        {slides.map((s, i) => {
          const active = i === idx;
          const hasHotspots = Array.isArray(s.hotspots) && s.hotspots.length > 0;
          const slideSrc = (isMobile && s.srcMobile) ? s.srcMobile : s.src;
          return (
            <div
              key={s.id}
              aria-hidden={!active}
              style={{
                position: 'absolute', inset: 0,
                opacity: active ? 1 : 0,
                pointerEvents: active ? 'auto' : 'none',
                transition: 'opacity .6s ease'
              }}>
              {/* Whole-banner link (only when no hotspots) */}
              {!hasHotspots &&
              <a
                href="#"
                onClick={(e) => {e.preventDefault();onNavigate(s.route);}}
                tabIndex={active ? 0 : -1}
                style={{ position: 'absolute', inset: 0, display: 'block', cursor: 'pointer', zIndex: 1 }}
                aria-label={s.alt} />

              }

              <image-slot
                key={slideSrc}
                id={`hero-${s.id}${isMobile && s.srcMobile ? '-m' : ''}`}
                src={slideSrc}
                fit="cover"
                shape="rect"
                placeholder="Arrastrá una imagen de banner"
                style={{
                  position: 'absolute',
                  inset: 0,
                  width: '100%',
                  height: '100%'
                }}>
              </image-slot>

              {/* Caption overlay (top of the banner) */}
              {s.caption &&
              <div
                style={{
                  position: 'absolute',
                  top: '6%', left: '4%', right: '4%',
                  zIndex: 3,
                  pointerEvents: 'none',
                  color: '#fff',
                  fontFamily: '"Syne", var(--font-sans)',
                  fontWeight: 800,
                  fontSize: 'clamp(22px, 2.6vw, 50px)',
                  lineHeight: 1.05,
                  letterSpacing: '-0.01em',
                  textShadow: '0 2px 12px rgba(0,0,0,0.45)'
                }}>
                  {s.caption}
                </div>
              }

              {/* Ribbon category labels (over the red strips) */}
              {Array.isArray(s.ribbonLabels) && s.ribbonLabels.map((rl) =>
              <div
                key={rl.text}
                style={{
                  position: 'absolute',
                  left: rl.cx, top: rl.cy,
                  transform: `translate(-50%, -50%) rotate(${rl.rotate || '0deg'})`,
                  zIndex: 4,
                  pointerEvents: 'none',
                  color: '#fff',
                  fontFamily: '"Syne", var(--font-sans)',
                  fontWeight: 800,
                  fontSize: 'clamp(11px, 1.35vw, 24px)',
                  letterSpacing: '0.02em',
                  textTransform: 'uppercase',
                  whiteSpace: 'nowrap'
                }}>
                  {rl.text}
                </div>
              )}

              {/* Per-category hotspots */}
              {hasHotspots && s.hotspots.map((h, hi) =>
              <a
                key={h.label}
                href="#"
                onClick={(e) => { e.preventDefault(); if (!editMode) onNavigate(h.route); }}
                tabIndex={active ? 0 : -1}
                aria-label={`Ir a ${h.label}`}
                title={h.label}
                style={{
                  position: 'absolute',
                  left: h.left, top: h.top, width: h.width, height: h.height,
                  cursor: editMode ? 'default' : 'pointer',
                  zIndex: 2,
                  background: editMode ? 'rgba(255,255,255,0.04)' : 'transparent',
                  outline: editMode ? '1px dashed rgba(255,255,255,0.3)' : 'none',
                  overflow: 'visible',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', margin: "0px"
                }}>
                
                  {h.img &&
                <div
                  className="hero-wiggle-pos"
                  style={{
                    position: 'relative',
                    width: `${(h.imgScale || 0.6) * 100}%`,
                    height: '77%',
                    pointerEvents: 'none',
                    animationDelay: `${hi * 0.15}s`
                  }}>
                  
                      <img
                    src={h.img}
                    alt=""
                    loading="lazy"
                    className="hero-wiggle-rot"
                    style={{
                      display: 'block',
                      width: '100%', height: '100%',
                      objectFit: 'contain', objectPosition: 'center center',
                      animationDelay: `${hi * 0.18}s`
                    }} />
                  
                    </div>
                }
                </a>
              )}
            </div>);

        })}

        {/* Arrows — on mobile they're rendered as plain white icons (no
            circular background or shadow); on desktop keep the white pill. */}
        <button
          onClick={prev}
          aria-label="Anterior"
          style={{
            position: 'absolute', left: isMobile ? 8 : 'clamp(12px, 2vw, 28px)', top: '50%', transform: 'translateY(-50%)',
            width: 48, height: 48, borderRadius: '50%',
            background: isMobile ? 'transparent' : 'rgba(255,255,255,0.92)',
            color: isMobile ? '#fff' : 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: isMobile ? 'none' : '0 4px 14px rgba(0,0,0,0.25)',
            filter: isMobile ? 'drop-shadow(0 1px 3px rgba(0,0,0,0.45))' : 'none',
            zIndex: 5,
            border: 'none'
          }}>
          
                    <span style={{ display: 'inline-flex', transform: 'rotate(180deg)' }}>
            <Icon name="arrowRight" size={isMobile ? 26 : 18} strokeWidth={isMobile ? 2.4 : 1.8}/>
          </span>
        </button>
        <button
          onClick={next}
          aria-label="Siguiente"
          style={{
            position: 'absolute', right: isMobile ? 8 : 'clamp(12px, 2vw, 28px)', top: '50%', transform: 'translateY(-50%)',
            width: 48, height: 48, borderRadius: '50%',
            background: isMobile ? 'transparent' : 'rgba(255,255,255,0.92)',
            color: isMobile ? '#fff' : 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: isMobile ? 'none' : '0 4px 14px rgba(0,0,0,0.25)',
            filter: isMobile ? 'drop-shadow(0 1px 3px rgba(0,0,0,0.45))' : 'none',
            zIndex: 5,
            border: 'none'
          }}>
          
          <Icon name="arrowRight" size={isMobile ? 26 : 18} strokeWidth={isMobile ? 2.4 : 1.8}/>
        </button>

        {/* Dots */}
        <div style={{
          position: 'absolute', bottom: 'clamp(12px, 2.5vh, 24px)', left: '50%', transform: 'translateX(-50%)',
          display: 'flex', gap: 8, zIndex: 5
        }}>
          {slides.map((_, i) =>
          <button
            key={i}
            onClick={() => go(i)}
            aria-label={`Ir al slide ${i + 1}`}
            style={{
              width: i === idx ? 28 : 8, height: 4, borderRadius: 2,
              background: i === idx ? '#fff' : 'rgba(255,255,255,0.55)',
              transition: 'width .3s ease, background .3s ease',
              border: 'none',
              cursor: 'pointer',
              padding: 0
            }} />

          )}
        </div>
      </div>

      {/* Edit-mode floating panel (Alt+E to toggle) */}
      {editMode && (
        <div style={{
          position: 'absolute', top: 12, right: 12, zIndex: 50,
          background: 'rgba(0,0,0,0.85)', color: '#fff',
          padding: '10px 14px', borderRadius: 8,
          fontSize: 12, fontFamily: 'system-ui, sans-serif',
          display: 'flex', flexDirection: 'column', gap: 8,
          boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
        }}>
          <div style={{ fontWeight: 700, letterSpacing: '0.04em' }}>MODO EDIT VER+</div>
          <div style={{ opacity: 0.75, fontSize: 11 }}>Arrastrá cada botón a su posición.<br/>Alt+E para salir.</div>
          <div style={{ fontFamily: 'monospace', fontSize: 10, background: 'rgba(255,255,255,0.08)', padding: 6, borderRadius: 4, maxWidth: 280, overflowX: 'auto' }}>
            {Object.entries(ctaPositions).map(([k, v]) => (
              <div key={k}>{k}: {JSON.stringify(v)}</div>
            ))}
          </div>
          <button onClick={copyCoords} style={{
            background: '#a00e0c', color: '#fff', border: 'none',
            padding: '8px 14px', borderRadius: 6, fontSize: 12, fontWeight: 700, cursor: 'pointer',
          }}>📋 Copiar coordenadas</button>
        </div>
      )}
    </section>);

};

Object.assign(window, { HeroSlider });