// ScrollRevealSection — adaptación del ContainerScroll de Aceternity.
// Al hacer scroll, una "card" rota desde 20deg (perspectiva) hasta plana,
// se escala ligeramente y el título se desplaza hacia arriba.
// Sustituye framer-motion por un hook scroll-progress nativo.

function _useScrollProgress(ref) {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onScroll = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight;
      // progress: 0 cuando la sección entra por abajo, 1 cuando sale por arriba
      const total = r.height + vh;
      const passed = vh - r.top;
      const prog = Math.max(0, Math.min(1, passed / total));
      setP(prog);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [ref]);
  return p;
}

function _lerp(a, b, t) { return a + (b - a) * t; }

function ScrollRevealSection({ root }) {
  const containerRef = React.useRef(null);
  const progress = _useScrollProgress(containerRef);

  const [isMobile, setIsMobile] = React.useState(false);
  React.useEffect(() => {
    const check = () => setIsMobile(window.innerWidth <= 768);
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  const rotate = _lerp(20, 0, progress);
  const scale = isMobile
    ? _lerp(0.7, 0.9, progress)
    : _lerp(1.05, 1, progress);
  const translateY = _lerp(0, -100, progress);

  return (
    <section
      ref={containerRef}
      id="demo"
      style={{
        position: 'relative',
        background: '#0a0a0a',
        color: '#faf8f3',
        borderTop: '1px solid rgba(10,10,10,0.08)',
        minHeight: isMobile ? '60rem' : '80rem',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: isMobile ? '0.5rem' : '5rem',
        overflow: 'hidden',
      }}
    >
      {/* Subtle noise overlay to sit with the editorial tone */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse at 50% 40%, rgba(245,228,208,0.08), transparent 60%)',
      }} />

      <div style={{
        padding: isMobile ? '2.5rem 0' : '10rem 0',
        width: '100%',
        position: 'relative',
        perspective: '1000px',
      }}>
        {/* Header */}
        <div style={{
          maxWidth: 1040, margin: '0 auto',
          textAlign: 'center', padding: '0 24px',
          transform: `translate3d(0, ${translateY}px, 0)`,
          willChange: 'transform',
        }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
            letterSpacing: 1.5, textTransform: 'uppercase',
            opacity: 0.5, marginBottom: 18,
          }}>◇ En vivo</div>
          <h2 style={{
            fontSize: 'clamp(40px, 5.5vw, 84px)',
            letterSpacing: '-0.045em',
            lineHeight: 0.98, margin: '0 0 20px',
            fontWeight: 400,
          }}>
            Así se ve <em style={{ fontFamily: 'Instrument Serif, serif' }}>ODAS</em> por dentro
          </h2>
          <p style={{
            fontSize: 18, lineHeight: 1.55, color: 'rgba(250,248,243,0.7)',
            maxWidth: 620, margin: '0 auto', textWrap: 'pretty',
          }}>
            Una ventana real al dashboard operativo. Datos, trazabilidad y cumplimiento fiscal en un único panel.
          </p>
        </div>

        {/* Card */}
        <div style={{
          maxWidth: 1040,
          margin: '-48px auto 0',
          height: isMobile ? '30rem' : '40rem',
          width: '100%',
          border: '4px solid #6C6C6C',
          padding: isMobile ? '0.5rem' : '1.5rem',
          background: '#222222',
          borderRadius: 30,
          transform: `rotateX(${rotate}deg) scale(${scale})`,
          transformOrigin: 'center top',
          boxShadow: '0 0 #0000004d, 0 9px 20px #0000004a, 0 37px 37px #00000042, 0 84px 50px #00000026, 0 149px 60px #0000000a, 0 233px 65px #00000003',
          willChange: 'transform',
        }}>
          <div style={{
            height: '100%', width: '100%',
            overflow: 'hidden',
            borderRadius: 16,
            background: '#18181b',
            padding: isMobile ? 0 : 16,
          }}>
            <DashboardPreview />
          </div>
        </div>
      </div>
    </section>
  );
}

// Simple dashboard-style preview inside the card — placeholder shaped like
// a real ODAS panel: sidebar + KPIs + chart + table. Uses the brand palette.
function DashboardPreview() {
  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'grid',
      gridTemplateColumns: '220px 1fr',
      background: '#fffdf8',
      color: '#0a0a0a',
      borderRadius: 12,
      overflow: 'hidden',
      fontFamily: 'Inter, system-ui, sans-serif',
    }}>
      {/* Sidebar */}
      <aside style={{
        background: '#faf8f3', padding: 20,
        borderRight: '1px solid rgba(10,10,10,0.08)',
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        <div style={{
          fontFamily: 'Instrument Serif, serif',
          fontSize: 22, letterSpacing: '-0.02em', marginBottom: 20,
        }}>ODAS</div>
        {['Overview', 'Excedentes', 'Donaciones', 'Trazabilidad', 'Fiscal', 'Informes'].map((l, i) => (
          <div key={l} style={{
            padding: '8px 12px', borderRadius: 8,
            fontSize: 13,
            background: i === 0 ? '#0a0a0a' : 'transparent',
            color: i === 0 ? '#faf8f3' : '#333',
          }}>{l}</div>
        ))}
      </aside>

      {/* Main */}
      <main style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20, overflow: 'hidden' }}>
        {/* Top bar */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: 1.5, opacity: 0.5, textTransform: 'uppercase' }}>Dashboard</div>
            <div style={{ fontSize: 22, letterSpacing: '-0.02em', marginTop: 2 }}>Resumen operativo</div>
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>Hoy · 18 nov 2025</div>
        </div>

        {/* KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {[
            { k: 'Kg salvados', v: '1.248', d: '+12%' },
            { k: 'Donaciones', v: '37', d: '+4' },
            { k: 'CO₂ evitado', v: '3,1 t', d: '+8%' },
            { k: 'Deducción fiscal', v: '€2.940', d: '+€210' },
          ].map(m => (
            <div key={m.k} style={{
              padding: 14,
              border: '1px solid rgba(10,10,10,0.08)',
              borderRadius: 10, background: '#fff',
            }}>
              <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: 1.2, opacity: 0.55, textTransform: 'uppercase' }}>{m.k}</div>
              <div style={{ fontSize: 22, letterSpacing: '-0.02em', marginTop: 6 }}>{m.v}</div>
              <div style={{ fontSize: 11, color: '#1f6b47', marginTop: 4 }}>{m.d}</div>
            </div>
          ))}
        </div>

        {/* Chart + side */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 12, flex: 1, minHeight: 0 }}>
          <div style={{
            border: '1px solid rgba(10,10,10,0.08)', borderRadius: 10,
            padding: 16, background: '#fff',
            display: 'flex', flexDirection: 'column', gap: 12,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Excedente semanal</div>
              <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, opacity: 0.55 }}>kg / día</div>
            </div>
            <FakeChart />
          </div>
          <div style={{
            border: '1px solid rgba(10,10,10,0.08)', borderRadius: 10,
            padding: 16, background: '#fff',
            display: 'flex', flexDirection: 'column', gap: 10,
          }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Últimos traslados</div>
            {[
              ['Banco de Aliments', '42 kg', 'Firmado'],
              ['Càritas BCN', '18 kg', 'Firmado'],
              ['Fundació Gresol', '27 kg', 'En ruta'],
              ['Creu Roja Sants', '9 kg', 'Firmado'],
            ].map(([a, b, c]) => (
              <div key={a} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                fontSize: 12, padding: '6px 0',
                borderBottom: '1px solid rgba(10,10,10,0.05)',
              }}>
                <span>{a}</span>
                <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{b}</span>
                <span style={{
                  fontSize: 10, padding: '2px 8px', borderRadius: 4,
                  background: c === 'Firmado' ? '#e3f0e8' : '#fdf2d9',
                  color: c === 'Firmado' ? '#1f6b47' : '#8a6a1a',
                }}>{c}</span>
              </div>
            ))}
          </div>
        </div>
      </main>
    </div>
  );
}

function FakeChart() {
  // Inline SVG area chart — deterministic, brand-tinted.
  const points = [18, 22, 19, 28, 24, 32, 30, 38, 34, 42, 39, 46];
  const w = 100, h = 100;
  const max = 50;
  const step = w / (points.length - 1);
  const line = points.map((v, i) => `${i === 0 ? 'M' : 'L'} ${i * step} ${h - (v / max) * h}`).join(' ');
  const area = `${line} L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', flex: 1 }}>
      <defs>
        <linearGradient id="cs-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#3d5a82" stopOpacity="0.3" />
          <stop offset="100%" stopColor="#3d5a82" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#cs-grad)" />
      <path d={line} fill="none" stroke="#3d5a82" strokeWidth="0.8" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

Object.assign(window, { ScrollRevealSection });
