// ── Scramble Link ─────────────────────────────────────────────
const _PR_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*';

function ScrambleLink({ href, children }) {
  const text = typeof children === 'string' ? children : '';
  const [displayText, setDisplayText] = React.useState(text);
  const [isHovering, setIsHovering] = React.useState(false);
  const intervalRef = React.useRef(null);
  const frameRef = React.useRef(0);

  const scramble = React.useCallback(() => {
    frameRef.current = 0;
    const duration = text.length * 3;
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      frameRef.current++;
      const progress = frameRef.current / duration;
      const revealedLength = Math.floor(progress * text.length);
      const newText = text.split('').map((char, i) => {
        if (char === ' ') return char;
        if (i < revealedLength) return text[i];
        return _PR_CHARS[Math.floor(Math.random() * _PR_CHARS.length)];
      }).join('');
      setDisplayText(newText);
      if (frameRef.current >= duration) {
        clearInterval(intervalRef.current);
        setDisplayText(text);
      }
    }, 30);
  }, [text]);

  React.useEffect(() => {
    return () => { if (intervalRef.current) clearInterval(intervalRef.current); };
  }, []);

  return (
    <a
      href={href}
      onMouseEnter={() => { setIsHovering(true); scramble(); }}
      onMouseLeave={() => setIsHovering(false)}
      style={{
        display: 'inline-block',
        fontFamily: 'Sora, sans-serif',
        fontWeight: 400,
        fontSize: '11px',
        letterSpacing: '0.15em',
        textTransform: 'uppercase',
        color: '#F2EFE8',
        textDecoration: 'none',
        border: `1px solid ${isHovering ? '#F2EFE8' : 'rgba(242,239,232,0.35)'}`,
        borderRadius: '999px',
        padding: '12px 32px',
        transition: 'border-color 0.2s',
        cursor: 'pointer',
      }}
    >
      {displayText}
    </a>
  );
}

// ── PORTAFOLIO RAIL ──────────────────────────────────────────
function PortafolioRail() {
  const [active, setActive] = React.useState(0);
  const dragStartX = React.useRef(null);

  const items = [
    {
      id: 0,
      title: 'CRM Operacional',
      description: 'Sistema de gestión de clientes y pipeline de ventas para empresa B2B con 200+ usuarios activos.',
      imageSrc: 'proyectos/crm.jpg',
      meta: 'Sistemas · 2024',
    },
    {
      id: 1,
      title: 'Automatización Logística',
      description: 'Flujos automáticos de seguimiento, notificación y coordinación para empresa de distribución regional.',
      imageSrc: 'proyectos/logistica.jpg',
      meta: 'Automatización · 2024',
    },
    {
      id: 2,
      title: 'Ecosistema E-commerce',
      description: 'Arquitectura completa: ERP, tienda, inventario y BI conectados en una sola operación.',
      imageSrc: 'proyectos/ecommerce.jpg',
      meta: 'Arquitectura · 2023',
    },
    {
      id: 3,
      title: 'Dashboard Ejecutivo',
      description: 'Centro de visibilidad operacional en tiempo real para directivos de empresa de servicios.',
      imageSrc: 'proyectos/dashboard.jpg',
      meta: 'Inteligencia · 2023',
    },
    {
      id: 4,
      title: 'Plataforma SaaS',
      description: 'Diseño y construcción de producto digital para startup de gestión de recursos humanos.',
      imageSrc: 'proyectos/saas.jpg',
      meta: 'Producto · 2023',
    },
  ];

  const count = items.length;

  function wrapIdx(v) {
    return ((v % count) + count) % count;
  }

  // Nearest offset with wrap-around (for smooth direction)
  function nearestOffset(rawOffset) {
    let o = rawOffset % count;
    if (o > count / 2) o -= count;
    if (o < -count / 2) o += count;
    return o;
  }

  const activeIndex = wrapIdx(active);
  const activeItem = items[activeIndex];

  const handlePrev = React.useCallback(() => setActive(p => p - 1), []);
  const handleNext = React.useCallback(() => setActive(p => p + 1), []);


  // Keyboard
  const onKeyDown = (e) => {
    if (e.key === 'ArrowLeft') handlePrev();
    if (e.key === 'ArrowRight') handleNext();
  };

  // Drag
  const onMouseDown = (e) => { dragStartX.current = e.clientX; };
  const onPointerUp = (e) => {
    if (dragStartX.current === null) return;
    const diff = dragStartX.current - e.clientX;
    if (Math.abs(diff) > 60) diff > 0 ? handleNext() : handlePrev();
    dragStartX.current = null;
  };

  // Card gradient placeholders (shown while images load / if missing)
  const gradients = [
    'linear-gradient(135deg, #1a1510 0%, #2c2318 50%, #1a1510 100%)',
    'linear-gradient(135deg, #0f1520 0%, #1a2535 50%, #0f1520 100%)',
    'linear-gradient(135deg, #151510 0%, #252518 50%, #151510 100%)',
    'linear-gradient(135deg, #150f10 0%, #251520 50%, #150f10 100%)',
    'linear-gradient(135deg, #101515 0%, #182525 50%, #101515 100%)',
  ];

  return (
    <section
      id="portafolio"
      tabIndex={0}
      onKeyDown={onKeyDown}
      style={{
        position: 'relative',
        width: '100%',
        overflow: 'hidden',
        background: 'transparent',
        outline: 'none',
        userSelect: 'none',
        borderTop: '1px solid var(--sand-border)',
        paddingTop: '80px',
        paddingBottom: '80px',
      }}
    >
      {/* Section label */}
      <div style={{ textAlign: 'center', marginBottom: '64px' }}>
        <p style={{ fontSize: '10px', letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--mist)', marginBottom: '12px' }}>

        </p>
        <h2 style={{ fontFamily: 'Sora, sans-serif', fontWeight: 400, fontSize: 'clamp(24px, 3vw, 42px)', color: '#F2EFE8', letterSpacing: '-0.02em', margin: 0 }}>
          Trabajo reciente
        </h2>
      </div>

      {/* Card rail */}
      <div
        style={{
          position: 'relative',
          zIndex: 10,
          margin: '0 auto',
          height: '380px',
          width: '100%',
          maxWidth: '1200px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          perspective: '1200px',
          cursor: 'grab',
        }}
        onMouseDown={onMouseDown}
        onMouseUp={onPointerUp}
        onMouseLeave={onPointerUp}
      >
        {items.map((item, i) => {
          const rawOffset = i - activeIndex;
          const offset = nearestOffset(rawOffset);
          const visible = Math.abs(offset) <= 2;

          const dist = Math.abs(offset);
          const xOffset = offset * 290;
          const zOffset = -dist * 150;
          const scale = offset === 0 ? 1 : 0.82;
          const rotateY = offset * -16;
          const opacity = offset === 0 ? 1 : Math.max(0.08, 1 - dist * 0.45);
          const blurVal = offset === 0 ? 0 : dist * 5;
          const brightness = offset === 0 ? 1 : 0.45;

          return (
            <div
              key={item.id}
              onClick={() => { if (offset !== 0) setActive(p => p + offset); }}
              style={{
                position: 'absolute',
                width: '240px',
                height: '320px',
                borderRadius: '14px',
                overflow: 'hidden',
                border: offset === 0 ? '1px solid rgba(200,184,149,0.28)' : '1px solid rgba(200,184,149,0.1)',
                background: gradients[item.id % gradients.length],
                boxShadow: offset === 0
                  ? '0 24px 64px rgba(0,0,0,0.6), 0 0 0 1px rgba(200,184,149,0.1)'
                  : '0 8px 24px rgba(0,0,0,0.3)',
                transform: `translateX(${xOffset}px) translateZ(${zOffset}px) scale(${scale}) rotateY(${rotateY}deg)`,
                transformStyle: 'preserve-3d',
                opacity: visible ? opacity : 0,
                filter: `blur(${blurVal}px) brightness(${brightness})`,
                transition: 'transform 0.55s cubic-bezier(0.25, 0.46, 0.45, 0.94), opacity 0.55s ease, filter 0.55s ease, border-color 0.4s ease, box-shadow 0.4s ease',
                zIndex: offset === 0 ? 20 : 10 - dist,
                cursor: offset === 0 ? 'default' : 'pointer',
                pointerEvents: visible ? 'auto' : 'none',
                flexShrink: 0,
              }}
            >
              <img
                src={item.imageSrc}
                alt={item.title}
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', pointerEvents: 'none' }}
                onError={e => { e.target.style.display = 'none'; }}
              />
              {/* Top gloss */}
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(255,255,255,0.07) 0%, transparent 35%)', borderRadius: '14px', pointerEvents: 'none' }} />
              {/* Bottom vignette on center card */}
              {offset === 0 && (
                <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(11,13,15,0.5) 0%, transparent 50%)', borderRadius: '14px', pointerEvents: 'none' }} />
              )}
            </div>
          );
        })}
      </div>

      {/* Info + Controls */}
      <div
        style={{
          position: 'relative',
          zIndex: 10,
          margin: '48px auto 0',
          display: 'flex',
          width: '100%',
          maxWidth: '900px',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: '24px',
          padding: '0 32px',
          flexWrap: 'wrap',
        }}
      >
        {/* Meta + Title + Desc */}
        <div style={{ flex: 1, minWidth: '200px' }}>
          {activeItem.meta && (
            <p style={{ fontSize: '10px', fontWeight: 500, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--sand)', marginBottom: '10px', transition: 'opacity 0.3s ease' }}>
              {activeItem.meta}
            </p>
          )}
          <h3 style={{ fontFamily: 'Sora, sans-serif', fontWeight: 400, fontSize: 'clamp(20px, 2.2vw, 30px)', color: '#F2EFE8', letterSpacing: '-0.02em', margin: '0 0 10px', lineHeight: 1.15, transition: 'opacity 0.3s ease' }}>
            {activeItem.title}
          </h3>
          {activeItem.description && (
            <p style={{ fontSize: '14px', color: 'var(--stone)', maxWidth: '400px', lineHeight: 1.7, margin: 0, transition: 'opacity 0.3s ease' }}>
              {activeItem.description}
            </p>
          )}
        </div>

        {/* Nav controls */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexShrink: 0 }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '4px',
            borderRadius: '999px',
            background: 'rgba(17,16,26,0.85)',
            padding: '4px',
            border: '1px solid rgba(200,184,149,0.14)',
            backdropFilter: 'blur(12px)',
          }}>
            <NavBtn onClick={handlePrev}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="15 18 9 12 15 6" />
              </svg>
            </NavBtn>
            <span style={{ minWidth: '38px', textAlign: 'center', fontSize: '11px', fontFamily: 'monospace', color: 'var(--stone)' }}>
              {String(activeIndex + 1).padStart(2, '0')} / {String(count).padStart(2, '0')}
            </span>
            <NavBtn onClick={handleNext}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="9 18 15 12 9 6" />
              </svg>
            </NavBtn>
          </div>
        </div>
      </div>

      {/* Dot indicators */}
      <div style={{ position: 'relative', zIndex: 10, display: 'flex', justifyContent: 'center', gap: '6px', marginTop: '32px' }}>
        {items.map((item, i) => (
          <button
            key={item.id}
            onClick={() => setActive(i)}
            style={{
              width: i === activeIndex ? '20px' : '6px',
              height: '6px',
              borderRadius: '3px',
              background: i === activeIndex ? 'var(--sand)' : 'rgba(200,184,149,0.25)',
              border: 'none',
              padding: 0,
              cursor: 'pointer',
              transition: 'width 0.3s ease, background 0.3s ease',
            }}
          />
        ))}
      </div>

      {/* Ver portafolio completo */}
      <div style={{ position: 'relative', zIndex: 10, display: 'flex', justifyContent: 'center', marginTop: '48px' }}>
        <ScrambleLink href="proyectos.html">Ver portafolio completo</ScrambleLink>
      </div>
    </section>
  );
}

// Small button helper
function NavBtn({ onClick, children }) {
  const [hovered, setHovered] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        borderRadius: '50%',
        padding: '9px',
        background: hovered ? 'rgba(255,255,255,0.09)' : 'transparent',
        border: 'none',
        color: hovered ? '#F2EFE8' : 'var(--stone)',
        cursor: 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        transition: 'color 0.2s, background 0.2s',
      }}
    >
      {children}
    </button>
  );
}
