const PRODUCTS = [
  {
    code: 'P-01',
    name: 'Papel Bond',
    tag: 'Escritura · Impresión',
    desc: 'Papel de escritura e impresión de uso general, ideal para documentos, formularios, cuadernos y material editorial. Excelente blancura y versatilidad.',
    tint: '#F8F8F4', dark: false,
  },
  {
    code: 'P-02',
    name: 'Papel Esmaltado',
    tag: 'Impresión premium',
    desc: 'Papel con recubrimiento que ofrece un acabado liso y brillante, perfecto para impresiones de alta calidad como catálogos, revistas y material publicitario.',
    tint: '#FFFFFF', dark: false,
  },
  {
    code: 'P-03',
    name: 'Cartulina Reverso Blanco',
    sub: 'C1S',
    tag: 'Empaque premium',
    desc: 'Cartulina con una cara esmaltada y reverso blanco, utilizada en empaques premium, cajas plegadizas y material POP donde la presentación es clave.',
    tint: '#FAFAF6', dark: false,
  },
  {
    code: 'P-04',
    name: 'Cartulina Reverso Café',
    sub: 'C1S',
    tag: 'Empaque resistente',
    desc: 'Cartulina con una cara esmaltada y reverso kraft, orientada a empaques y cajas donde se busca resistencia con buena presentación exterior.',
    tint: '#A77548', dark: true,
  },
  {
    code: 'P-05',
    name: 'Kraft Liner',
    tag: 'Corrugado · Bolsas',
    desc: 'Papel kraft de alta resistencia utilizado en la fabricación de bolsas, sacos y como cara externa en cartón corrugado. Aporta rigidez y protección.',
    tint: '#C39563', dark: false,
  },
  {
    code: 'P-06',
    name: 'Test Liner',
    tag: 'Reciclado · Económico',
    desc: 'Papel reciclado usado en la fabricación de bolsas y como cara en cartón corrugado, ofreciendo una alternativa económica al kraft liner con buen desempeño mecánico.',
    tint: '#B89570', dark: false,
  },
  {
    code: 'P-07',
    name: 'Kraft Semiextensible',
    tag: 'Sacos industriales',
    desc: 'Papel kraft con propiedades de elongación, diseñado para la fabricación de sacos multicapa destinados a productos industriales como cemento, cal y químicos.',
    tint: '#B6884E', dark: false,
  },
  {
    code: 'P-08',
    name: 'Papel MG',
    sub: 'Machine Glazed',
    tag: 'Envoltura · Laminación',
    desc: 'Papel con una cara satinada por cilindro, usado en envoltura, laminación y empaque flexible. Buena barrera y acabado uniforme.',
    tint: '#EFEAE0', dark: false,
  },
  {
    code: 'P-09',
    name: 'Papel Antigraso',
    tag: 'Empaque de alimentos',
    desc: 'Papel tratado para resistir la penetración de grasas y aceites, ideal para empaques de alimentos como panaderías, comidas rápidas y snacks.',
    tint: '#F4E5A8', dark: false,
  },
];

function Portafolio({ onCotizar }) {
  const trackRef = React.useRef(null);
  const [canLeft, setCanLeft] = React.useState(false);
  const [canRight, setCanRight] = React.useState(true);

  const updateArrows = React.useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    setCanLeft(el.scrollLeft > 8);
    setCanRight(el.scrollLeft < el.scrollWidth - el.clientWidth - 8);
  }, []);

  React.useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    updateArrows();
    el.addEventListener('scroll', updateArrows, { passive: true });
    window.addEventListener('resize', updateArrows);
    return () => {
      el.removeEventListener('scroll', updateArrows);
      window.removeEventListener('resize', updateArrows);
    };
  }, [updateArrows]);

  const scrollBy = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * 320, behavior: 'smooth' });
  };

  return (
    <section id="portafolio" data-screen-label="Portafolio" style={{
      padding: '120px 0 100px',
      background: 'var(--navy)',
      color: 'white',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Subtle bg glow */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 30% 40%, rgba(6,182,212,0.10) 0%, transparent 50%), radial-gradient(ellipse at 80% 70%, rgba(16,185,129,0.08) 0%, transparent 50%)',
        pointerEvents: 'none',
      }} />

      <div className="container" style={{ position: 'relative', zIndex: 2 }}>

        {/* Heading */}
        <div style={{ textAlign: 'center', marginBottom: 56 }}>
          <div style={{
            fontSize: 12, fontWeight: 700, letterSpacing: '0.22em',
            textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)', marginBottom: 16,
          }}>02 — Portafolio</div>
          <h2 className="section-title" style={{
            fontSize: 'clamp(36px, 5vw, 64px)',
            color: 'white',
            marginBottom: 16,
          }}>Nuestro portafolio</h2>
          <p style={{
            fontSize: 17,
            color: 'rgba(255,255,255,0.78)',
            maxWidth: 640,
            margin: '0 auto',
            lineHeight: 1.55,
          }}>
            Soluciones integrales en papel y materias primas para cada necesidad de tu operación.
          </p>
        </div>

        {/* Carousel */}
        <div style={{ position: 'relative' }}>

          {/* Arrows */}
          <button onClick={() => scrollBy(-1)} aria-label="Anterior" style={{
            position: 'absolute',
            left: -8, top: '50%', transform: 'translateY(-50%)',
            zIndex: 5,
            width: 48, height: 48,
            borderRadius: '50%',
            background: 'rgba(255,255,255,0.08)',
            border: '1px solid rgba(255,255,255,0.18)',
            backdropFilter: 'blur(8px)',
            color: 'white',
            display: 'grid', placeItems: 'center',
            transition: 'all .2s',
            opacity: canLeft ? 1 : 0,
            pointerEvents: canLeft ? 'auto' : 'none',
          }}
          onMouseOver={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
          onMouseOut={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
          </button>

          <button onClick={() => scrollBy(1)} aria-label="Siguiente" style={{
            position: 'absolute',
            right: -8, top: '50%', transform: 'translateY(-50%)',
            zIndex: 5,
            width: 48, height: 48,
            borderRadius: '50%',
            background: 'rgba(255,255,255,0.08)',
            border: '1px solid rgba(255,255,255,0.18)',
            backdropFilter: 'blur(8px)',
            color: 'white',
            display: 'grid', placeItems: 'center',
            transition: 'all .2s',
            opacity: canRight ? 1 : 0,
            pointerEvents: canRight ? 'auto' : 'none',
          }}
          onMouseOver={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
          onMouseOut={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
          </button>

          {/* Track */}
          <div ref={trackRef} className="carousel-track" style={{
            display: 'flex',
            gap: 20,
            overflowX: 'auto',
            scrollSnapType: 'x mandatory',
            paddingBottom: 16,
            paddingLeft: 4, paddingRight: 4,
          }}>
            {PRODUCTS.map((p) => (
              <ProductCard key={p.code} product={p} onCotizar={() => window.openWhatsApp(p.name)} />
            ))}
          </div>
        </div>

      </div>
    </section>
  );
}

function ProductCard({ product, onCotizar }) {
  const [hover, setHover] = React.useState(false);
  const p = product;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        flexShrink: 0,
        width: 280,
        scrollSnapAlign: 'start',
        background: 'linear-gradient(180deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0.03) 100%)',
        border: '1px solid rgba(255,255,255,0.10)',
        borderRadius: 16,
        padding: 24,
        display: 'flex',
        flexDirection: 'column',
        minHeight: 420,
        transition: 'all .35s cubic-bezier(.2,.7,.2,1)',
        transform: hover ? 'translateY(-6px)' : 'translateY(0)',
        boxShadow: hover ? '0 20px 50px rgba(0,0,0,0.40), 0 0 0 1px rgba(6,182,212,0.30)' : '0 4px 12px rgba(0,0,0,0.20)',
      }}
    >
      {/* Code + Tag row */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 12,
      }}>
        <div style={{
          fontSize: 10,
          fontWeight: 700,
          letterSpacing: '0.14em',
          color: 'rgba(255,255,255,0.45)',
        }}>{p.code}</div>

        {p.tag && (
          <div style={{
            fontSize: 9,
            fontWeight: 600,
            letterSpacing: '0.10em',
            textTransform: 'uppercase',
            color: 'var(--green-2)',
            padding: '3px 8px',
            border: '1px solid rgba(52,211,153,0.35)',
            borderRadius: 999,
            background: 'rgba(16,185,129,0.08)',
          }}>{p.tag}</div>
        )}
      </div>

      {/* Product visual */}
      <div style={{
        height: 160,
        marginBottom: 20,
        display: 'grid',
        placeItems: 'center',
      }}>
        <PaperRoll tint={p.tint} dark={p.dark} hover={hover} />
      </div>

      {/* Name */}
      <div style={{
        fontSize: 17,
        fontWeight: 800,
        textTransform: 'uppercase',
        color: 'white',
        marginBottom: p.sub ? 4 : 12,
        letterSpacing: '0.02em',
        lineHeight: 1.2,
      }}>
        {p.name}
      </div>
      {p.sub && (
        <div style={{
          fontSize: 11,
          fontWeight: 500,
          letterSpacing: '0.10em',
          color: 'var(--teal)',
          textTransform: 'uppercase',
          marginBottom: 12,
        }}>{p.sub}</div>
      )}

      {/* Desc */}
      <p style={{
        fontSize: 13,
        lineHeight: 1.55,
        color: 'rgba(255,255,255,0.72)',
        marginBottom: 24,
        flexGrow: 1,
      }}>
        {p.desc}
      </p>

      {/* CTA */}
      <button
        onClick={onCotizar}
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          fontSize: 12,
          fontWeight: 700,
          letterSpacing: '0.14em',
          textTransform: 'uppercase',
          color: hover ? 'var(--green-2)' : 'white',
          transition: 'color .2s',
          padding: '8px 0',
          borderTop: '1px solid rgba(255,255,255,0.10)',
          paddingTop: 16,
          width: '100%',
          justifyContent: 'space-between',
        }}
      >
        Cotizar
        <span style={{
          transition: 'transform .3s cubic-bezier(.2,.7,.2,1)',
          transform: hover ? 'translateX(4px)' : 'translateX(0)',
        }}>→</span>
      </button>
    </div>
  );
}

function PaperRoll({ tint, dark, hover }) {
  // CSS-rendered paper roll with cylinder lighting
  return (
    <div style={{
      position: 'relative',
      width: 140, height: 140,
      transition: 'transform .4s cubic-bezier(.2,.7,.2,1)',
      transform: hover ? 'rotate(-4deg) scale(1.05)' : 'rotate(-2deg) scale(1)',
    }}>
      {/* Drop shadow */}
      <div style={{
        position: 'absolute',
        bottom: -16, left: '10%', right: '10%',
        height: 18, borderRadius: '50%',
        background: 'rgba(0,0,0,0.40)',
        filter: 'blur(12px)',
      }} />

      {/* Roll body (circle) */}
      <div style={{
        position: 'absolute', inset: 0,
        borderRadius: '50%',
        background: `radial-gradient(circle at 30% 25%, ${dark ? lighten(tint, 0.25) : '#FFFFFF'} 0%, ${tint} 35%, ${dark ? darken(tint, 0.4) : darken(tint, 0.18)} 75%, ${darken(tint, 0.5)} 100%)`,
        boxShadow: `inset -16px -10px 30px rgba(0,0,0,0.25), inset 8px 6px 20px rgba(255,255,255,0.15), 0 8px 24px rgba(0,0,0,0.30)`,
      }} />

      {/* Layered rings to suggest paper layers */}
      <div style={{
        position: 'absolute', inset: '12%',
        borderRadius: '50%',
        background: `repeating-radial-gradient(circle, transparent 0, transparent 3px, ${dark ? 'rgba(0,0,0,0.10)' : 'rgba(0,0,0,0.06)'} 3px, ${dark ? 'rgba(0,0,0,0.10)' : 'rgba(0,0,0,0.06)'} 4px)`,
        opacity: 0.5,
      }} />

      {/* Inner core */}
      <div style={{
        position: 'absolute',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: '26%', height: '26%',
        borderRadius: '50%',
        background: 'radial-gradient(circle, #1A2456 0%, #0A1228 80%)',
        boxShadow: 'inset 0 3px 8px rgba(0,0,0,0.6)',
      }} />

      {/* Highlight */}
      <div style={{
        position: 'absolute',
        top: '8%', left: '20%',
        width: '30%', height: '20%',
        borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,255,255,0.4) 0%, transparent 70%)',
        filter: 'blur(4px)',
      }} />
    </div>
  );
}

// Color helpers — operate on hex strings
function hexToRgb(h) {
  h = h.replace('#', '');
  if (h.length === 3) h = h.split('').map(c => c + c).join('');
  return [parseInt(h.substr(0,2),16), parseInt(h.substr(2,2),16), parseInt(h.substr(4,2),16)];
}
function rgbToHex(r,g,b) {
  return '#' + [r,g,b].map(v => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2,'0')).join('');
}
function darken(hex, amt) {
  const [r,g,b] = hexToRgb(hex);
  return rgbToHex(r*(1-amt), g*(1-amt), b*(1-amt));
}
function lighten(hex, amt) {
  const [r,g,b] = hexToRgb(hex);
  return rgbToHex(r+(255-r)*amt, g+(255-g)*amt, b+(255-b)*amt);
}

window.Portafolio = Portafolio;
