/* eslint-disable react/prop-types */
/**
 * Hero · Sección 1 del Home · refinado gehlpeople-grade.
 *  - Entry animation al cargar: título y descripción fade+up escalonados
 *  - Pause auto-play al hover del carrusel
 *  - Ken Burns sutil en cada slide
 *  - data-cursor="next" en barras de progreso (cursor muestra "→")
 *  - Scroll hint en la base
 */

const { useState: uS_He, useEffect: uE_He, useRef: uR_He } = React;

const HERO_SLIDES = [
  {
    img: 'assets/images/prosperia-hero-slide-01-san-pedro-vida-calle.jpg',
    tone: 'people',
    label: 'CALLE VIVA · PERSONAS PRIMER PLANO · 16:9',
    title: 'CREAMOS LO EXTRAORDINARIO',
    desc: 'Originamos negocios inmobiliarios desde la demanda real \u2014 la que vive en las personas, no en los inventarios. Esa es la diferencia entre perseguir mercado y\u00A0crearlo.',
    cta: { label: 'Habla con Prosperia', href: '#contacto' },
    eyebrow: 'ORIGINACIÓN INMOBILIARIA · 18 AÑOS',
  },
  {
    img: 'assets/images/prosperia-hero-slide-02-cdmx-reforma.jpg',
    tone: 'aerial',
    label: 'CIUDAD DE MÉXICO · REFORMA + CHAPULTEPEC + BELLAS ARTES · 16:9',
    title: 'CREEMOS EN EL POTENCIAL DE LAS CIUDADES',
    desc: 'Las ciudades que construimos nos construyen de vuelta. Cuando se diseñan desde la vida de quien las habita \u2014no desde el inventario\u2014, los proyectos rentan más y las ciudades se viven\u00A0mejor.',
    cta: { label: 'Habla con Prosperia', href: '#contacto' },
    eyebrow: '57 CIUDADES · 3 REGIONES',
  },
  {
    img: 'assets/images/prosperia-hero-slide-03-distrito-residencial-vida.jpg',
    tone: 'urban',
    label: 'DISTRITO EMBLEMÁTICO · TEC/ARBOLEDA/LYRA · 16:9',
    title: 'DE MAGMA TOWERS A LYRA. 40+ DISTRITOS, 18 AÑOS.',
    titleLines: ['DE MAGMA TOWERS A LYRA.', '40+ DISTRITOS,', '18 AÑOS.'],
    desc: 'Co-creamos distritos urbanos completos \u2014 educación, vivienda asequible, polos tecnológicos, manufactura, arte \u2014 junto a gobiernos, asociaciones y desarrolladores valientes que se atrevieron a apostar fuera del\u00A0paradigma.',
    cta: { label: 'Ver portafolio', href: '/distritos/Distritos.html' },
    eyebrow: '+40 DISTRITOS · +1,900 PROYECTOS',
  },
];

const HERO_AUTOPLAY_MS = 6000;

function Hero() {
  const [index, setIndex]   = uS_He(0);
  const [progress, setProg] = uS_He(0);
  const [paused, setPaused] = uS_He(false);
  const [loaded, setLoaded] = uS_He(false);

  uE_He(() => {
    const t = setTimeout(() => setLoaded(true), 60);
    return () => clearTimeout(t);
  }, []);

  uE_He(() => {
    if (paused) return;
    setProg(0);
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / HERO_AUTOPLAY_MS);
      setProg(p);
      if (p < 1) raf = requestAnimationFrame(tick);
      else setIndex((i) => (i + 1) % HERO_SLIDES.length);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [index, paused]);

  const current = HERO_SLIDES[index];

  return (
    <section
      id="top"
      data-screen-label="01 Hero"
      style={heroStyles.section}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {HERO_SLIDES.map((s, i) => (
        <div
          key={i}
          aria-hidden={i !== index}
          style={{
            ...heroStyles.slideLayer,
            opacity: i === index ? 1 : 0,
            transition: 'opacity 1000ms cubic-bezier(0.16, 1, 0.3, 1)',
          }}
        >
          <div style={{
            ...heroStyles.kenBurnsLayer,
            animationPlayState: paused ? 'paused' : 'running',
          }}>
            <window.ImagePlaceholder
              src={s.img}
              alt={s.label}
              label={s.label}
              tone={s.tone}
              ratio="auto"
              style={{ width: '100%', height: '100%', aspectRatio: 'auto' }}
              overlay
              overlayOpacity={0.45}
            />
          </div>
        </div>
      ))}

      {/* Gradient inferior para legibilidad de progress + texto */}
      <div style={heroStyles.bottomGradient} aria-hidden="true" />

      <div style={heroStyles.contentWrap}>
        <div style={heroStyles.content}>
          <div style={{
            ...heroStyles.eyebrowRow,
            opacity: loaded ? 1 : 0,
            transform: loaded ? 'translateY(0)' : 'translateY(8px)',
            transition: 'opacity 700ms ease 200ms, transform 700ms cubic-bezier(0.16,1,0.3,1) 200ms',
          }}>
            <span style={heroStyles.eyebrowDot} aria-hidden="true" />
            <span style={heroStyles.eyebrow}>{current.eyebrow}</span>
          </div>

          <h1 key={`t-${index}`} style={{
            ...heroStyles.title,
            opacity: loaded ? 1 : 0,
            transform: loaded ? 'translateY(0)' : 'translateY(16px)',
            transition: 'opacity 900ms ease 350ms, transform 900ms cubic-bezier(0.16,1,0.3,1) 350ms',
            animation: 'heroTitleSwap 900ms cubic-bezier(0.16,1,0.3,1)',
          }}>
            {current.titleLines
              ? current.titleLines.map((line, i) => (
                  <span key={i} style={{ display: 'block', whiteSpace: 'nowrap' }}>{line}</span>
                ))
              : current.title}
          </h1>
          <p key={`d-${index}`} style={{
            ...heroStyles.desc,
            opacity: loaded ? 1 : 0,
            transform: loaded ? 'translateY(0)' : 'translateY(12px)',
            transition: 'opacity 900ms ease 500ms, transform 900ms cubic-bezier(0.16,1,0.3,1) 500ms',
            animation: 'heroDescSwap 900ms cubic-bezier(0.16,1,0.3,1)',
          }}>
            {current.desc}
          </p>
          <div style={{
            opacity: loaded ? 1 : 0,
            transform: loaded ? 'translateY(0)' : 'translateY(12px)',
            transition: 'opacity 900ms ease 650ms, transform 900ms cubic-bezier(0.16,1,0.3,1) 650ms',
            marginTop: 36,
          }}>
            <a href={current.cta.href} className="btn btn-copper" data-cursor="link">
              {current.cta.label}
              <window.Icon name="arrow-right" size={16} stroke={1.8} />
            </a>
          </div>
        </div>
      </div>

      {/* Scroll hint */}
      <div style={heroStyles.scrollHint} aria-hidden="true">
        <span style={heroStyles.scrollLabel}>SCROLL</span>
        <span style={heroStyles.scrollLine}><span style={heroStyles.scrollLineFill} /></span>
      </div>

      {/* Progress bars + thumbnails */}
      <div style={heroStyles.progressWrap} role="tablist" aria-label="Slides del hero">
        {HERO_SLIDES.map((_, i) => (
          <button
            key={i}
            onClick={() => setIndex(i)}
            role="tab"
            aria-selected={i === index}
            aria-label={`Slide ${i + 1}`}
            data-cursor="link"
            style={heroStyles.progressTrack}
          >
            <span style={heroStyles.progressDigit}>0{i + 1}</span>
            <span style={heroStyles.progressLine}>
              <span style={{
                ...heroStyles.progressFill,
                width: i < index ? '100%' : i === index ? `${progress * 100}%` : '0%',
                transition: i === index ? 'none' : 'width 240ms cubic-bezier(0.16,1,0.3,1)',
              }} />
            </span>
          </button>
        ))}
      </div>
    </section>
  );
}

const heroStyles = {
  section: {
    position: 'relative',
    minHeight: 'max(90vh, 600px)',
    width: '100%',
    overflow: 'hidden',
    background: 'var(--color-navy-deep)',
  },
  slideLayer: { position: 'absolute', inset: 0 },
  kenBurnsLayer: {
    position: 'absolute', inset: 0,
    animation: 'heroKenBurns 18s cubic-bezier(0.16, 1, 0.3, 1) infinite alternate',
    willChange: 'transform',
  },
  bottomGradient: {
    position: 'absolute', left: 0, right: 0, bottom: 0,
    height: 240,
    background: 'linear-gradient(180deg, transparent 0%, rgba(15,27,35,0.85) 100%)',
    zIndex: 1,
    pointerEvents: 'none',
  },
  contentWrap: {
    position: 'relative', zIndex: 2,
    maxWidth: 1280, margin: '0 auto',
    padding: '0 var(--container-padding-mobile)',
    minHeight: 'max(90vh, 600px)',
    display: 'flex', alignItems: 'flex-end',
    paddingBottom: 'min(22vh, 200px)',
  },
  content: { maxWidth: 940 },
  eyebrowRow: {
    display: 'inline-flex', alignItems: 'center', gap: 14,
    marginBottom: 28,
    paddingInline: 18, paddingBlock: 10,
    background: 'rgba(15,27,35,0.55)',
    border: '1px solid rgba(255,255,255,0.22)',
    borderRadius: 999,
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
  },
  eyebrowDot: {
    width: 7, height: 7, borderRadius: 999,
    background: 'var(--color-copper-fallback)',
    boxShadow: '0 0 14px rgba(168,107,45,0.8)',
  },
  eyebrow: {
    fontWeight: 700,
    fontSize: 'clamp(13px, 1vw, 16px)',
    letterSpacing: '0.2em',
    color: '#fff',
    textTransform: 'uppercase',
  },
  title: {
    margin: 0,
    fontWeight: 800,
    letterSpacing: '0.02em',
    color: '#fff',
    fontSize: 'clamp(28px, 5.4vw, 60px)',
    lineHeight: 1.05,
    textWrap: 'balance',
    textShadow: '0 2px 28px rgba(0,0,0,0.18)',
    overflowWrap: 'break-word',
    hyphens: 'auto',
  },
  desc: {
    marginTop: 24, marginBottom: 0,
    color: 'rgba(255,255,255,0.94)',
    fontSize: 'clamp(16px, 1.4vw, 19px)',
    lineHeight: 1.6,
    maxWidth: 720,
    textWrap: 'pretty',
  },
  scrollHint: {
    position: 'absolute',
    right: 'var(--container-padding-mobile)',
    bottom: 32,
    display: 'none',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 12,
    zIndex: 3,
  },
  scrollLabel: {
    color: 'rgba(255,255,255,0.7)',
    fontSize: 10, fontWeight: 700, letterSpacing: '0.3em',
    writingMode: 'vertical-rl',
    transform: 'rotate(180deg)',
  },
  scrollLine: {
    width: 1, height: 56,
    background: 'rgba(255,255,255,0.18)',
    overflow: 'hidden',
    position: 'relative',
  },
  scrollLineFill: {
    position: 'absolute', left: 0, top: 0, right: 0,
    height: '50%',
    background: 'var(--color-copper-fallback)',
    animation: 'scrollDot 2s ease-in-out infinite',
  },
  progressWrap: {
    position: 'absolute', bottom: 32, left: 0, right: 0,
    zIndex: 3,
    display: 'flex', justifyContent: 'center', gap: 24,
    padding: '0 var(--container-padding-mobile)',
  },
  progressTrack: {
    display: 'flex', flexDirection: 'column', gap: 10,
    background: 'transparent', border: 0, padding: 0,
    minWidth: 90,
  },
  progressDigit: {
    fontSize: 11, fontWeight: 700, letterSpacing: '0.18em',
    color: 'rgba(255,255,255,0.72)',
    fontFamily: 'ui-monospace, Menlo, Consolas, monospace',
  },
  progressLine: {
    display: 'block',
    height: 2,
    background: 'rgba(255,255,255,0.22)',
    overflow: 'hidden',
  },
  progressFill: {
    display: 'block', height: '100%',
    backgroundImage: 'url("assets/textures/cobre-patinado.svg")',
    backgroundSize: '600px 100%',
  },
};

const heroMQ = document.createElement('style');
heroMQ.textContent = `
  @media (min-width: 1024px) {
    section[data-screen-label="01 Hero"] { min-height: 100vh !important; }
    section[data-screen-label="01 Hero"] > div[style*="zIndex: 2"] { min-height: 100vh !important; }
    section[data-screen-label="01 Hero"] > div[aria-hidden="true"]:not([style*="height: 240"]) { display: flex; }
    section[data-screen-label="01 Hero"] > div[aria-hidden="true"][style*="bottom: 32px"] { display: flex !important; }
  }
  @keyframes heroKenBurns {
    0%   { transform: scale(1.02) translate(0, 0); }
    100% { transform: scale(1.10) translate(-1.5%, -1%); }
  }
  @keyframes heroTitleSwap {
    0%   { opacity: 0.0; transform: translateY(14px); filter: blur(4px); }
    60%  { filter: blur(0); }
    100% { opacity: 1.0; transform: translateY(0);   filter: blur(0); }
  }
  @keyframes heroDescSwap {
    0%   { opacity: 0.0; transform: translateY(10px); }
    100% { opacity: 1.0; transform: translateY(0); }
  }
  @keyframes scrollDot {
    0%   { transform: translateY(-100%); }
    100% { transform: translateY(200%); }
  }
`;
document.head.appendChild(heroMQ);

window.Hero = Hero;
