// Hero · Extracción de datos — pure React + CSS animations.
// Keyframes are defined in Hero Extract.html <style>.
// ~10s loop, editorial aesthetic matching the reference video.
//
// Layout: 1120×440 stage, scaled to fit viewport
//   LEFT   — 3 document mockups in a row, content evolves (form → filled → table)
//   DIVIDER — thin violet vertical bar
//   CENTER — small "engine" pixel-mark
//   RIGHT  — 5 form-field cards with colored tag headers

const LOOP = 10; // seconds

// ═════════ tokens ═════════
const C = {
  bg:        '#FAFAFA',
  gridLine:  '#EEEFF2',
  primary:   '#1F2937',
  primaryBar:'#1F2937',
  ink:       '#1F2937',
  ink2:      '#4B5563',
  ink3:      '#9CA3AF',
  paperLine: '#E5E7EB',
  paperFaint:'#F3F4F6',
  paper:     '#FFFFFF',
  olive:     '#B5B27A',  oliveInk:  '#4D4B2A',
  mauve:     '#8FB890',  mauveInk:  '#24452A',
  teal:      '#7FAFB5',  tealInk:   '#22484C',
  orange:    '#D99760',  orangeInk: '#5C3316',
  fuchsia:   '#4F9C63',  fuchsiaInk:'#0E3A1C',
};

// ═════════ grid background ═════════
function GridBG() {
  return (
    <div aria-hidden style={{
      position:'absolute', inset:0,
      backgroundImage:
        `linear-gradient(to right, ${C.gridLine} 1px, transparent 1px),` +
        `linear-gradient(to bottom, ${C.gridLine} 1px, transparent 1px)`,
      backgroundSize: '16px 16px',
      opacity: 0.8,
      pointerEvents:'none',
    }}/>
  );
}

// ═════════ document mockup ═════════
// Content morphs between variants over the loop via CSS opacity.
// We use useEffect + setState to drive the phase.
function DocMock({ x, y, rotate, z, delay, phase }) {
  const W = 168, H = 220;
  const showForm   = phase < 0.35;
  const showFilled = phase >= 0.3 && phase < 0.75;
  const showTable  = phase >= 0.7;

  return (
    <div
      className="doc-enter"
      style={{
        position:'absolute',
        left: x, top: y,
        width: W, height: H,
        background: C.paper,
        border: `1px solid ${C.paperLine}`,
        '--doc-rotate': `${rotate}deg`,
        animationDelay: `${delay}s`,
        boxShadow: `0 1px 0 rgba(15,23,42,0.02), 0 20px 48px -30px rgba(15,23,42,0.18)`,
        padding: '14px 14px 12px',
        zIndex: z,
        overflow: 'hidden',
      }}
    >
      {/* page hairline header */}
      <div style={{display:'flex',gap:4,marginBottom:10,alignItems:'center'}}>
        <div style={{width:14,height:6,background:C.ink,opacity:0.85}}/>
        <div style={{height:4,background:C.paperLine,flex:1}}/>
        <div style={{width:20,height:4,background:C.paperLine}}/>
      </div>

      {/* Content area — opacity-crossfaded variants */}
      <div style={{position:'relative', height: H - 52}}>
        {/* VARIANT 0: empty form fields */}
        <div className="variant" style={{opacity: showForm ? 1 : 0, display:'flex', flexDirection:'column', gap:8}}>
          {[0,1,2,3].map(i => (
            <div key={i}>
              <div style={{width: [46,60,40,52][i], height:3, background:C.paperLine, marginBottom:4}}/>
              <div style={{height: i===3 ? 36 : 14, border:`1px solid ${C.paperLine}`, background: C.paper}}/>
            </div>
          ))}
        </div>

        {/* VARIANT 1: filled with faux-text */}
        <div className="variant" style={{opacity: showFilled ? 1 : 0, display:'flex', flexDirection:'column', gap:3.5}}>
          {Array.from({length:14}).map((_,i)=>(
            <div key={i} style={{
              height:3, background:C.ink3, opacity:0.55,
              width: `${40 + ((i*37)%55)}%`,
            }}/>
          ))}
        </div>

        {/* VARIANT 2: dense table */}
        <div className="variant" style={{opacity: showTable ? 1 : 0}}>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:4, marginBottom:5}}>
            {[0,1,2].map(i=>(
              <div key={i} style={{height:3, background:C.paperLine}}/>
            ))}
          </div>
          {Array.from({length:10}).map((_,r)=>(
            <div key={r} style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:4, marginBottom:4}}>
              {[0,1,2].map(c=>(
                <div key={c} style={{
                  height:3, background: C.ink3, opacity: 0.5,
                  width: `${55 + ((r*31+c*17)%35)}%`,
                }}/>
              ))}
            </div>
          ))}
        </div>
      </div>

      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:6}}>
        <div style={{width:20, height:3, background:C.paperLine}}/>
        <div style={{width:28, height:8, background: showTable ? C.ink : C.paperFaint, border: showTable ? 'none' : `1px solid ${C.paperLine}`}}/>
      </div>
    </div>
  );
}

// ═════════ engine pixel-mark ═════════
function EngineMark() {
  return (
    <div style={{
      position:'relative',
      width: 64, height: 64,
      background: C.paper,
      border: `1px solid ${C.paperLine}`,
      display:'flex', alignItems:'center', justifyContent:'center',
      boxShadow: `0 1px 0 rgba(15,23,42,0.02), 0 16px 40px -20px rgba(15,23,42,0.28)`,
      zIndex: 6,
    }}>
      <div className="engine-pulse" style={{
        display:'flex', alignItems:'center', justifyContent:'center',
        fontFamily:'ui-sans-serif,system-ui,"Segoe UI",Roboto,sans-serif',
        fontSize: 28,
        fontWeight: 700,
        letterSpacing:'-0.03em',
        color: C.ink,
        lineHeight: 1,
      }}>
        in
      </div>

      <div aria-hidden className="ring-pulse" style={{
        position:'absolute', inset:-4,
        border:`1px solid ${C.primary}`,
        pointerEvents:'none',
      }}/>
    </div>
  );
}

// ═════════ pill card ═════════
function PillCard({ label, tagBg, tagInk, x, y, delay, activeAt }) {
  // Value line fills via CSS animation keyed on activeAt.
  // We offset the animation-delay so it fires at activeAt*LOOP seconds into loop.
  const fillDelay = `${activeAt * LOOP - 0.1}s`;
  return (
    <div
      className="pill-enter"
      style={{
        position:'absolute',
        left: x, top: y,
        width: 178,
        animationDelay: `${delay}s`,
      }}
    >
      {/* Tag header */}
      <div style={{
        display:'inline-flex', alignItems:'center', gap:6,
        background: tagBg,
        color: tagInk,
        padding: '4px 8px 4px 5px',
        fontFamily:'ui-monospace,"SF Mono",Menlo,monospace',
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: '0.02em',
        position:'relative',
        zIndex: 2,
        marginBottom: -1,
      }}>
        <svg width="10" height="10" viewBox="0 0 10 10" shapeRendering="crispEdges">
          <rect x="0" y="0" width="3" height="3" fill={tagInk}/>
          <rect x="4" y="0" width="3" height="3" fill={tagInk} opacity="0.4"/>
          <rect x="0" y="4" width="3" height="3" fill={tagInk} opacity="0.6"/>
          <rect x="4" y="4" width="3" height="3" fill={tagInk}/>
          <rect x="4" y="8" width="3" height="2" fill={tagInk} opacity="0.4"/>
          <rect x="8" y="0" width="2" height="3" fill={tagInk} opacity="0.4"/>
        </svg>
        {label}
      </div>

      {/* Input field card */}
      <div style={{
        background: C.paper,
        border: `1px solid ${C.paperLine}`,
        padding: '11px 12px',
        display:'flex', alignItems:'center', gap:8,
        height: 36,
      }}>
        <div style={{
          height: 3,
          background: tagBg,
          flex: 1,
          transformOrigin: 'left center',
          opacity: 0.7,
          transform: 'scaleX(0)',
          animation: `valueFill ${LOOP}s linear infinite`,
          animationDelay: fillDelay,
        }}/>
        <div style={{
          height: 3,
          background: C.paperLine,
          width: 28,
          transformOrigin: 'left center',
          transform: 'scaleX(0)',
          animation: `valueFill ${LOOP}s linear infinite`,
          animationDelay: `calc(${fillDelay} + 0.08s)`,
        }}/>
      </div>
    </div>
  );
}

// ═════════ traveling pixel chip ═════════
function PixelChip({ fromX, fromY, toX, toY, midX, midY, size, color, delay, duration }) {
  return (
    <div style={{
      position: 'absolute',
      width: size, height: size,
      background: color,
      top: 0, left: 0,
      pointerEvents: 'none',
      zIndex: 5,
      '--from-x': `${fromX}px`,
      '--from-y': `${fromY}px`,
      '--mid-x': `${midX}px`,
      '--mid-y': `${midY}px`,
      '--to-x': `${toX}px`,
      '--to-y': `${toY}px`,
      animation: `pixelTravel ${duration}s ease-in-out infinite`,
      animationDelay: `${delay}s`,
      opacity: 0,
    }}/>
  );
}

// ═════════ main hero ═════════
function HeroExtract({ embed }) {
  const [phase, setPhase] = React.useState(0);
  const wrapRef = React.useRef(null);
  const [scale, setScale] = React.useState(1);

  // Drive doc-content morph
  React.useEffect(() => {
    let raf, start = performance.now();
    const tick = (now) => {
      const t = ((now - start) / 1000) % LOOP;
      setPhase(t / LOOP);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Responsive scale
  React.useEffect(() => {
    const STAGE_W = 1120;
    const calc = () => {
      const el = wrapRef.current;
      if (!el) return;
      const w = el.clientWidth;
      setScale(Math.min(1, w / STAGE_W));
    };
    calc();
    window.addEventListener('resize', calc);
    return () => window.removeEventListener('resize', calc);
  }, []);

  const STAGE_W = 1120;
  const STAGE_H = 440;

  const docs = [
    { variant: 0, x: 40,  y: 90,  rotate: -1.5, z: 3, delay: 0.05 },
    { variant: 1, x: 175, y: 70,  rotate: 0.8,  z: 2, delay: 0.18 },
    { variant: 2, x: 310, y: 95,  rotate: -0.6, z: 1, delay: 0.32 },
  ];

  const engineX = 530, engineY = 188;

  const pills = [
    { label:'email',     tagBg: C.olive,   tagInk: C.oliveInk,   x: 680,  y: 70,  at: 0.48 },
    { label:'total',     tagBg: C.fuchsia, tagInk: '#fff',       x: 900,  y: 80,  at: 0.56 },
    { label:'dirección', tagBg: C.teal,    tagInk: '#fff',       x: 790,  y: 180, at: 0.62 },
    { label:'pedido',    tagBg: C.orange,  tagInk: C.orangeInk,  x: 680,  y: 290, at: 0.68 },
    { label:'líneas',    tagBg: C.mauve,   tagInk: '#fff',       x: 900,  y: 300, at: 0.74 },
  ];

  // Pixel chips: doc → engine (orange scan)
  const scanPixels = Array.from({length: 10}).map((_, i) => {
    const d = docs[i % 3];
    const fromX = d.x + 30 + (i*13) % 100;
    const fromY = d.y + 40 + (i*23) % 140;
    const toX = engineX + 20;
    const toY = engineY + 20;
    return {
      id: `scan-${i}`,
      fromX, fromY, toX, toY,
      midX: (fromX + toX) / 2 + (i % 2 === 0 ? -20 : 20),
      midY: (fromY + toY) / 2 - 30,
      color: C.orange,
      size: 6 + (i % 3) * 2,
      delay: 0.9 + i * 0.18,
      duration: Math.max(0.1, LOOP - 0.9 - i * 0.18 - 0.1),
    };
  });

  // Pixel chips: engine → pills (colored output)
  const outPixels = pills.flatMap((p, pi) => (
    Array.from({length: 3}).map((_, i) => {
      const fromX = engineX + 22;
      const fromY = engineY + 20;
      const toX = p.x + 20 + i * 30;
      const toY = p.y + 4;
      const delay = Math.max(0, p.at * LOOP - 0.4 + i * 0.12);
      return {
        id: `out-${pi}-${i}`,
        fromX, fromY, toX, toY,
        midX: (fromX + toX) / 2 + (i % 2 === 0 ? 20 : -20),
        midY: (fromY + toY) / 2 - 20,
        color: p.tagBg,
        size: 6 + (i % 2) * 2,
        delay,
        duration: Math.max(0.5, LOOP - delay - 0.2),
      };
    })
  ));

  return (
    <section style={{
      width: '100%',
      background: embed ? 'transparent' : C.bg,
      position: 'relative',
      overflow: 'hidden',
      paddingTop: embed ? 8 : 24, paddingBottom: embed ? 8 : 24,
    }}>
      {!embed && <GridBG/>}

      {/* Responsive wrapper */}
      <div ref={wrapRef} style={{
        position:'relative',
        width:'100%',
        height: STAGE_H * scale + 24,
        margin:'0 auto',
      }}>
        <div style={{
          position:'absolute',
          left:'50%', top:0,
          width: STAGE_W,
          height: STAGE_H,
          transform: `translateX(-50%) scale(${scale})`,
          transformOrigin: 'top center',
        }}>
          {/* Divider */}
          <div
            className="divider-enter"
            aria-hidden
            style={{
              position: 'absolute',
              left: engineX + 22,
              top: 30, bottom: 30,
              width: 4,
              background: `linear-gradient(to bottom, transparent 0%, ${C.primaryBar} 8%, ${C.primaryBar} 92%, transparent 100%)`,
              transformOrigin: 'center',
              zIndex: 1,
            }}
          />

          {/* Documents */}
          {docs.map((d, i) => (
            <DocMock key={`doc-${i}`} {...d} phase={phase}/>
          ))}

          {/* Engine */}
          <div style={{ position:'absolute', left: engineX - 10, top: engineY - 12 }}>
            <EngineMark/>
          </div>

          {/* Pills */}
          {pills.map((p, i) => (
            <PillCard
              key={`pill-${i}`}
              {...p}
              activeAt={p.at}
              delay={0.55 + i * 0.08}
            />
          ))}

          {/* Pixel chips */}
          {scanPixels.map(p => <PixelChip key={p.id} {...p}/>)}
          {outPixels.map(p => <PixelChip key={p.id} {...p}/>)}
        </div>
      </div>
    </section>
  );
}

// ═════════ wrapper with heading ═════════
function App() {
  return (
    <div style={{minHeight:'100vh', paddingTop: 56, paddingBottom: 40, background: C.bg}}>
      <div style={{maxWidth: 1120, margin:'0 auto', padding:'0 40px 28px'}}>
        <div style={{
          fontFamily:'ui-monospace,monospace',
          fontSize:11, letterSpacing:'0.16em',
          color: C.ink3, fontWeight:600,
          textTransform:'uppercase', marginBottom: 18,
        }}>
          § Conciliación automática de facturas
        </div>
        <h1 style={{
          fontFamily:'ui-sans-serif,system-ui,sans-serif',
          fontSize: 52, fontWeight: 500,
          letterSpacing: '-0.025em', lineHeight: 1.05,
          margin: 0, maxWidth: 860, color: C.ink,
        }}>
          Factura, pedido y albarán <em style={{fontStyle:'italic', fontWeight:400}}>cuadrados solos</em>,<br/>
          línea por línea.
        </h1>
        <p style={{
          fontFamily:'ui-sans-serif,system-ui,sans-serif',
          fontSize: 17, color: C.ink2, maxWidth: 580,
          marginTop: 16, lineHeight: 1.55,
        }}>
          Conecta tu correo. Nosotros leemos cada documento, cruzamos los datos y te avisamos de cada descuadre antes de que lo pagues.
        </p>
      </div>
      <HeroExtract/>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  window.__HERO_EMBED ? <HeroExtract embed/> : <App/>
);
