/* eslint-disable react/prop-types */
/**
 * Portfolio · Sección 7 del Home · Carrusel de proyectos destacados.
 * Brief 1 §3.1 Sección 7. Refinamiento gehlpeople-grade:
 *  - Auto-pause on hover
 *  - Animated text swap entre slides (fade+up con stagger)
 *  - Strip de proyectos al pie con nombres (no solo barras anónimas)
 *  - Ken Burns sutil
 *  - data-cursor="view" sobre el card activo
 */

const { useState: uS_Pf, useEffect: uE_Pf } = React;

const PORTFOLIO = [
  { slug: 'magma-towers', name: 'MAGMA TOWERS', loc: 'VALLE ORIENTE, SPGG, NL',           year: '2008', tag: 'MIXTO · TORRES',
    img: 'assets/images-distritos/magma-towers.jpg', tone: 'urban' },
  { slug: 'distrito-tec',  name: 'DISTRITO TEC',  loc: 'MONTERREY, NL',                     year: '2014', tag: 'UNIVERSITARIO · RE-DENSIFICACIÓN',
    img: 'assets/images-distritos/distrito-tec.jpg', tone: 'residential' },
  { slug: 'lyra',          name: 'LYRA',          loc: 'CUMBRES ÉLITE, MONTERREY, NL',      year: '2021', tag: 'VIVIENDA · LEED + WELL',
    img: 'assets/images-distritos/lyra.jpg', tone: 'residential' },
  { slug: 'arboleda',      name: 'ARBOLEDA',      loc: 'SAN PEDRO GARZA GARCÍA, NL',        year: '2019', tag: 'MIXTO · NET-ZERO',
    img: 'assets/images-distritos/arboleda.jpg', tone: 'urban' },
  { slug: 'latiz',         name: 'LATÍZ',         loc: 'NAUCALPAN, EDOMEX',                 year: '2021', tag: 'POLO TECNOLÓGICO · LIVE+WORK+PLAY',
    img: 'assets/images-distritos/latiz.jpg', tone: 'industrial' },
  { slug: 'la-reserva',    name: 'LA RESERVA',    loc: 'NORPONIENTE DE MONTERREY, NL',      year: '2022', tag: 'ECO-URBANO · COMUNIDAD PLANEADA',
    img: 'assets/images-distritos/la-reserva.jpg', tone: 'aerial' },
];

const PF_AUTOPLAY = 6500;

function Portfolio() {
  const [index, setIndex] = uS_Pf(0);
  const [progress, setP]  = uS_Pf(0);
  const [paused, setPaused] = uS_Pf(false);

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

  const current = PORTFOLIO[index];

  return (
    <section
      id="portfolio"
      data-screen-label="07 Portfolio"
      style={pfStyles.section}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {PORTFOLIO.map((s, i) => (
        <div
          key={i}
          aria-hidden={i !== index}
          style={{
            ...pfStyles.slideLayer,
            opacity: i === index ? 1 : 0,
            transition: 'opacity 1000ms cubic-bezier(0.16, 1, 0.3, 1)',
          }}
        >
          <div style={{
            ...pfStyles.kenBurnsLayer,
            animationPlayState: (paused || i !== index) ? 'paused' : 'running',
          }}>
            <window.ImagePlaceholder
              src={s.img}
              alt={`${s.name} · ${s.loc}`}
              label={`${s.name} · ${s.loc} · ${s.year}`}
              tone={s.tone}
              ratio="auto"
              style={{ width: '100%', height: '100%', aspectRatio: 'auto' }}
              overlay
              overlayOpacity={0.55}
            />
          </div>
        </div>
      ))}

      <div style={pfStyles.bottomGradient} aria-hidden="true" />

      <div style={pfStyles.contentWrap}>
        <a
          href={`/distritos/Ficha.html?slug=${current.slug}`}
          style={pfStyles.cardLink}
          data-cursor="view"
          data-cursor-label="VER DISTRITO"
          aria-label={`Ver ficha completa de ${current.name}`}
        >
          <div style={pfStyles.content}>
            <div style={pfStyles.headerRow}>
              <span style={pfStyles.eyebrow}>PORTAFOLIO</span>
              <span style={pfStyles.counter}>
                <strong>{String(index + 1).padStart(2, '0')}</strong>
                <span style={pfStyles.counterDivider} />
                {String(PORTFOLIO.length).padStart(2, '0')}
              </span>
            </div>

            <h2 key={`pf-t-${index}`} style={pfStyles.title}>
              {current.name}
            </h2>
            <p key={`pf-meta-${index}`} style={pfStyles.meta}>
              <span>{current.loc}</span>
              <span style={pfStyles.metaDot} />
              <span>{current.year}</span>
              <span style={pfStyles.metaDot} />
              <span style={pfStyles.metaTag}>{current.tag}</span>
            </p>

            <span style={pfStyles.cta} className="btn btn-navy-outline">
              Conocer este distrito
              <window.Icon name="arrow-right" size={16} stroke={1.8} />
            </span>
          </div>
        </a>
      </div>

      {/* Strip de proyectos al pie. Click cambia el slide; si vuelves a hacer
          click en el slide activo, navega a la ficha. */}
      <div style={pfStyles.strip} role="tablist" aria-label="Distritos del portafolio">
        {PORTFOLIO.map((s, i) => {
          const active = i === index;
          const handleClick = () => {
            if (active) {
              window.location.href = `/distritos/Ficha.html?slug=${s.slug}`;
            } else {
              setIndex(i);
            }
          };
          return (
            <button
              key={i}
              role="tab"
              aria-selected={active}
              onClick={handleClick}
              data-cursor={active ? 'view' : 'link'}
              data-cursor-label={active ? 'VER FICHA' : null}
              title={active ? `Click para ver la ficha de ${s.name}` : `Ver ${s.name}`}
              style={{
                ...pfStyles.stripItem,
                color: active ? '#fff' : 'rgba(255,255,255,0.55)',
              }}
            >
              <span style={pfStyles.stripLine}>
                <span style={{
                  ...pfStyles.stripLineFill,
                  width: i < index ? '100%' : active ? `${progress * 100}%` : '0%',
                  transition: active ? 'none' : 'width 240ms cubic-bezier(0.16,1,0.3,1)',
                }} />
              </span>
              <span style={pfStyles.stripName}>
                {s.name}
                {active && (
                  <span style={pfStyles.stripArrow} aria-hidden="true">→</span>
                )}
              </span>
              <span style={pfStyles.stripYear}>{s.year}</span>
            </button>
          );
        })}
      </div>
    </section>
  );
}

const pfStyles = {
  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: 'pfKenBurns 18s cubic-bezier(0.16, 1, 0.3, 1) infinite alternate',
    willChange: 'transform',
  },
  bottomGradient: {
    position: 'absolute', left: 0, right: 0, bottom: 0,
    /* Gradient más alto y direccional desde la zona del texto.
       Oscurece solo el tercio inferior donde está el contenido,
       deja la parte superior de la imagen visible y respirable. */
    height: '70%',
    background: 'linear-gradient(180deg, transparent 0%, transparent 30%, rgba(15,27,35,0.55) 65%, rgba(15,27,35,0.92) 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(28vh, 240px)',
  },
  content: { maxWidth: 880 },
  headerRow: {
    display: 'inline-flex', alignItems: 'center', gap: 14,
    marginBottom: 18,
    /* Pill con backdrop-blur — sutil pero efectivo para etiquetas pequeñas */
    paddingInline: 14, paddingBlock: 7,
    background: 'rgba(15,27,35,0.40)',
    border: '1px solid rgba(255,255,255,0.14)',
    borderRadius: 999,
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
  },
  eyebrow: {
    color: 'var(--color-copper-fallback)',
    fontWeight: 700, fontSize: 12, letterSpacing: '0.22em',
    textTransform: 'uppercase',
    textShadow: '0 1px 2px rgba(0,0,0,0.4)',
  },
  counter: {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    fontSize: 12, color: 'rgba(255,255,255,0.78)',
    fontFamily: 'ui-monospace, Menlo, Consolas, monospace',
    letterSpacing: '0.12em',
  },
  counterDivider: {
    display: 'inline-block', width: 24, height: 1,
    background: 'rgba(255,255,255,0.4)',
  },
  title: {
    margin: '8px 0 0',
    fontWeight: 800,
    fontSize: 'clamp(28px, 7vw, 80px)',
    lineHeight: 1.0,
    color: '#fff',
    letterSpacing: '0.03em',
    animation: 'pfTextSwap 800ms cubic-bezier(0.16,1,0.3,1)',
    textWrap: 'balance',
    textShadow: '0 2px 24px rgba(0,0,0,0.45), 0 1px 4px rgba(0,0,0,0.3)',
  },
  meta: {
    margin: '24px 0 0',
    color: '#fff',
    fontSize: 13,
    letterSpacing: '0.14em',
    textTransform: 'uppercase',
    display: 'flex', alignItems: 'center', gap: 12,
    flexWrap: 'wrap',
    animation: 'pfTextSwap 800ms cubic-bezier(0.16,1,0.3,1) 80ms backwards',
    textShadow: '0 1px 8px rgba(0,0,0,0.6), 0 1px 2px rgba(0,0,0,0.4)',
    fontWeight: 700,
  },
  metaDot: {
    display: 'inline-block', width: 4, height: 4, borderRadius: 999,
    background: 'rgba(255,255,255,0.6)',
  },
  metaTag: {
    color: 'var(--color-copper-fallback)',
    fontWeight: 700,
    textShadow: '0 1px 4px rgba(0,0,0,0.5)',
  },
  cardLink: {
    display: 'block',
    color: 'inherit', textDecoration: 'none',
    /* área de click expandida a todo el rectángulo del texto */
  },
  cta: {
    marginTop: 36,
    borderColor: 'rgba(255,255,255,0.6)',
    color: '#fff',
    display: 'inline-flex', alignItems: 'center', gap: 12,
    pointerEvents: 'none', /* el click lo recibe el <a> padre */
  },
  strip: {
    position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 3,
    display: 'grid',
    gridTemplateColumns: `repeat(${PORTFOLIO.length}, 1fr)`,
    background: 'rgba(15,27,35,0.55)',
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
    borderTop: '1px solid rgba(255,255,255,0.10)',
  },
  stripItem: {
    background: 'transparent', border: 0,
    display: 'flex', flexDirection: 'column',
    gap: 8, padding: '16px 20px',
    textAlign: 'left',
    borderRight: '1px solid rgba(255,255,255,0.08)',
    transition: 'color 240ms ease',
  },
  stripLine: {
    display: 'block', width: '100%', height: 2,
    background: 'rgba(255,255,255,0.16)',
    overflow: 'hidden',
  },
  stripLineFill: {
    display: 'block', height: '100%',
    backgroundImage: 'url("assets/textures/cobre-patinado.svg")',
    backgroundSize: '600px 100%',
  },
  stripName: {
    fontSize: 13, fontWeight: 700, letterSpacing: '0.14em',
    textTransform: 'uppercase',
    display: 'inline-flex', alignItems: 'center', gap: 8,
  },
  stripArrow: {
    color: 'var(--color-copper-fallback)',
    fontWeight: 800,
    transform: 'translateY(-1px)',
  },
  stripYear: {
    fontSize: 11, color: 'rgba(255,255,255,0.45)',
    letterSpacing: '0.18em',
    fontFamily: 'ui-monospace, Menlo, Consolas, monospace',
  },
};

const pfMQ = document.createElement('style');
pfMQ.textContent = `
  /* Card grande clickeable — hover state */
  section[data-screen-label="07 Portfolio"] a[aria-label^="Ver ficha"] {
    cursor: pointer;
    transition: transform 360ms cubic-bezier(0.16,1,0.3,1);
  }
  section[data-screen-label="07 Portfolio"] a[aria-label^="Ver ficha"]:hover {
    transform: translateY(-2px);
  }
  section[data-screen-label="07 Portfolio"] a[aria-label^="Ver ficha"]:hover span.btn {
    background: rgba(255,255,255,0.1) !important;
    border-color: #fff !important;
  }

  @media (max-width: 767px) {
    section[data-screen-label="07 Portfolio"] > div[role="tablist"] {
      grid-template-columns: repeat(${PORTFOLIO.length}, minmax(140px, 1fr)) !important;
      overflow-x: auto;
      scrollbar-width: none;
    }
    section[data-screen-label="07 Portfolio"] > div[role="tablist"]::-webkit-scrollbar { display: none; }
  }
  @media (min-width: 1024px) {
    section[data-screen-label="07 Portfolio"] { min-height: 100vh; }
    section[data-screen-label="07 Portfolio"] > div[style*="zIndex: 2"] { min-height: 100vh !important; }
  }
  section[data-screen-label="07 Portfolio"] a.btn-navy-outline:hover {
    background: rgba(255,255,255,0.96);
    color: var(--color-navy-deep);
    border-color: rgba(255,255,255,0.96);
  }
  @keyframes pfKenBurns {
    0%   { transform: scale(1.02) translate(0, 0); }
    100% { transform: scale(1.10) translate(-1.5%, -1%); }
  }
  @keyframes pfTextSwap {
    0%   { opacity: 0.0; transform: translateY(12px); filter: blur(4px); }
    60%  { filter: blur(0); }
    100% { opacity: 1.0; transform: translateY(0);   filter: blur(0); }
  }
`;
document.head.appendChild(pfMQ);

window.Portfolio = Portfolio;
