/* global React */
const { useEffect, useRef, useState, useMemo } = React;

/* ============== Reveal-on-scroll hook ============== */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal, .word');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -5% 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ============== Type helpers ============== */
function SplitWords({ text, children, className = '', delayBase = 0 }) {
  let raw = text;
  if (raw == null) {
    const arr = React.Children.toArray(children);
    raw = arr.map((c) => typeof c === 'string' || typeof c === 'number' ? String(c) : '').join('');
  }
  const words = String(raw).split(' ').filter(Boolean);
  return (
    <span className={className}>
      {words.map((w, i) =>
      <span key={i} className="word" style={{ marginRight: '0.22em' }}>
          <span style={{ transitionDelay: `${delayBase + i * 50}ms` }}>{w}</span>
        </span>
      )}
    </span>);
}

/* ============== Nav ============== */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const f = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', f, { passive: true });
    f();
    return () => window.removeEventListener('scroll', f);
  }, []);
  return (
    <header className={`fixed top-0 inset-x-0 z-50 transition-all duration-500 ${scrolled ? 'py-3' : 'py-6'}`}>
      <div className={`mx-auto max-w-[1400px] px-4 lg:px-10 flex items-center justify-between transition-all duration-500 ${scrolled ? 'bg-white/80 backdrop-blur-md border border-ink/10 rounded-full py-2.5 px-4 lg:px-6 shadow-sm' : ''}`}>
        <a href="#top" className="flex items-center gap-2.5">
          <span className="w-6 h-6 rounded bg-ink text-white grid place-items-center font-display font-medium text-[14px] leading-none pb-px">b</span>
          <span className="font-display font-medium text-[18px] tracking-tight">Bataj Systems</span>
        </a>
        <nav className="hidden md:flex items-center gap-9 text-[14px] font-medium text-ink/70">
          <a className="hover:text-ink transition-colors" href="#manifest">Filosofía</a>
          <a className="hover:text-ink transition-colors" href="#products">Productos</a>
          <a className="hover:text-ink transition-colors" href="#process">Proceso</a>
          <a className="hover:text-ink transition-colors" href="#contact">Contacto</a>
        </nav>
        <a href="#contact" className="btn btn-dark text-[13px] py-2 px-4">
          Empezar proyecto
        </a>
      </div>
    </header>);
}

/* ============== Background Helpers ============== */
function MasterGrid() {
  return <div className="sys-grid fixed inset-0 z-[-1] opacity-60 pointer-events-none" />;
}

/* ============== Record Player (YouTube) ============== */
function RecordPlayer() {
  const [player, setPlayer] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [isReady, setIsReady] = useState(false);
  
  useEffect(() => {
    const initPlayer = () => {
      // Avoid initializing multiple times
      if (document.getElementById('yt-player-container').innerHTML !== '') return;
      
      const ytPlayer = new window.YT.Player('yt-player-container', {
        height: '0',
        width: '0',
        videoId: 'MYW0TgV67RE', // Work Music for Serious Grind _ Stay Aligned
        playerVars: {
          autoplay: 1,
          controls: 0,
          disablekb: 1,
          fs: 0,
          rel: 0,
          showinfo: 0,
          iv_load_policy: 3
        },
        events: {
          onReady: (event) => {
            setIsReady(true);
            setPlayer(event.target);
            event.target.playVideo();
          },
          onStateChange: (event) => {
            if (event.data === window.YT.PlayerState.PLAYING) {
              setIsPlaying(true);
            } else {
              setIsPlaying(false);
            }
          }
        }
      });
    };

    if (!window.YT) {
      const tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';
      const firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      window.onYouTubeIframeAPIReady = initPlayer;
    } else if (window.YT && window.YT.Player) {
      initPlayer();
    } else {
      const prev = window.onYouTubeIframeAPIReady;
      window.onYouTubeIframeAPIReady = () => {
        if (prev) prev();
        initPlayer();
      }
    }
  }, []);

  // Hack for strict browsers: Force play on any first interaction (scroll, click, etc)
  const hasAutoPlayed = useRef(false);
  useEffect(() => {
    if (!player || hasAutoPlayed.current) return;
    
    const forcePlay = () => {
      if (!hasAutoPlayed.current && player.getPlayerState && player.getPlayerState() !== window.YT.PlayerState.PLAYING) {
        player.playVideo();
        hasAutoPlayed.current = true;
      }
      window.removeEventListener('click', forcePlay);
      window.removeEventListener('scroll', forcePlay);
      window.removeEventListener('touchstart', forcePlay);
      window.removeEventListener('keydown', forcePlay);
    };

    window.addEventListener('click', forcePlay, { passive: true });
    window.addEventListener('scroll', forcePlay, { passive: true });
    window.addEventListener('touchstart', forcePlay, { passive: true });
    window.addEventListener('keydown', forcePlay, { passive: true });

    return () => {
      window.removeEventListener('click', forcePlay);
      window.removeEventListener('scroll', forcePlay);
      window.removeEventListener('touchstart', forcePlay);
      window.removeEventListener('keydown', forcePlay);
    };
  }, [player]);

  const togglePlay = () => {
    if (!player) return;
    if (isPlaying) {
      player.pauseVideo();
    } else {
      player.playVideo();
    }
  };

  const toggleMute = (e) => {
    e.stopPropagation();
    if (!player) return;
    if (isMuted) {
      player.unMute();
      setIsMuted(false);
    } else {
      player.mute();
      setIsMuted(true);
    }
  };

  const spinState = isPlaying ? 'running' : 'paused';
  
  return (
    <div 
      onClick={togglePlay}
      className={`w-[320px] h-[320px] rounded-3xl sm:rounded-[40px] flex flex-col items-center justify-center relative overflow-hidden transition-all duration-500 ${isReady ? 'cursor-pointer hover:shadow-[0_0_50px_-15px_rgba(255,255,255,0.1)]' : 'opacity-70 pointer-events-none'}`}
      style={{ 
        background: 'rgba(15, 15, 15, 0.4)', 
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        border: '1px solid rgba(255,255,255,0.08)',
        boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.02), 0 20px 40px -10px rgba(0,0,0,0.6)' 
      }}
    >
      <div id="yt-player-container" className="absolute opacity-0 pointer-events-none" />
      
      {/* Background grid / tech texture */}
      <div className="absolute inset-0 opacity-[0.04]" style={{ backgroundImage: 'radial-gradient(#fff 1px, transparent 1px)', backgroundSize: '16px 16px' }} />
      
      {/* Nodal Processor Visuals (Rotates slightly) */}
      <div 
        className="absolute inset-0 flex items-center justify-center pointer-events-none"
        style={{ 
          animation: 'spin 20s linear infinite',
          animationPlayState: spinState,
        }} 
      >
        {/* Outer Ring 1 */}
        <div className="absolute w-[260px] h-[260px] rounded-full border border-white/5" />
        {/* Outer Ring 2 (dashed) */}
        <div className="absolute w-[180px] h-[180px] rounded-full border border-white/10" style={{ borderStyle: 'dashed' }} />
        {/* Inner Ring */}
        <div className="absolute w-[110px] h-[110px] rounded-full border border-white/10" />
        
        {/* PCB Traces (SVG lines) */}
        <svg width="320" height="320" viewBox="0 0 320 320" className="absolute inset-0 opacity-40">
          {/* Central cross */}
          <line x1="160" y1="30" x2="160" y2="105" stroke="#fff" strokeWidth="1" />
          <line x1="160" y1="215" x2="160" y2="290" stroke="#fff" strokeWidth="1" />
          <line x1="30" y1="160" x2="105" y2="160" stroke="#fff" strokeWidth="1" />
          <line x1="215" y1="160" x2="290" y2="160" stroke="#fff" strokeWidth="1" />
          
          {/* Diagonal nodes */}
          <circle cx="80" cy="80" r="2.5" fill="#fff" />
          <path d="M80 80 L 120 120" stroke="#fff" strokeWidth="1" fill="none" />
          
          <circle cx="240" cy="80" r="2.5" fill="#fff" />
          <path d="M240 80 L 200 120" stroke="#fff" strokeWidth="1" fill="none" />
          
          <circle cx="80" cy="240" r="2.5" fill="#fff" />
          <path d="M80 240 L 120 200" stroke="#fff" strokeWidth="1" fill="none" />
          
          <circle cx="240" cy="240" r="2.5" fill="#fff" />
          <path d="M240 240 L 200 200" stroke="#fff" strokeWidth="1" fill="none" />
        </svg>

        {/* Orbiting Data Packet (Orb) on the dashed ring */}
        <div 
          className="absolute w-[180px] h-[180px] pointer-events-none"
          style={{ 
            animation: 'spin 1s linear infinite',
            animationPlayState: spinState,
          }}
        >
          <div className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[5px] h-[5px] bg-white rounded-full shadow-[0_0_12px_3px_rgba(255,255,255,0.9)]" />
        </div>
      </div>
      
      {/* Central Core (Static) */}
      <div 
        onClick={toggleMute}
        className="w-[70px] h-[70px] rounded-full flex flex-col items-center justify-center relative bg-black/40 backdrop-blur-xl border border-white/10 z-10 shadow-2xl hover:scale-105 transition-transform cursor-pointer"
        title="Toggle Mute"
      >
         {/* Red Dot (Nothing OS style) */}
         <div className={`w-3 h-3 rounded-full transition-all duration-300 shadow-[0_0_15px_rgba(229,57,53,0.5)] ${isPlaying ? 'bg-[#E53935] scale-100' : 'bg-white/20 scale-75'}`} />
         
         {/* Mute button icon overlaid if muted */}
         {isMuted && (
           <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white/90 font-mono text-[10px]">
             ✕
           </div>
         )}
      </div>
      
      {/* Floating Status Texts (Dot-Matrix) */}
      <div 
        className="absolute top-5 w-full flex justify-between px-6 font-mono text-[11px] uppercase tracking-wider z-10"
        style={{ fontFamily: "'VT323', 'Courier New', monospace" }}
      >
        <div className="text-white/40">SYS_CORE</div>
        <div className="text-white/40">v2.4</div>
      </div>
      
      <div 
        className="absolute bottom-6 flex flex-col items-center gap-1 z-10 leading-none"
        style={{ fontFamily: "'VT323', 'Courier New', monospace", fontSize: '14px', letterSpacing: '0.05em' }}
      >
        {isReady ? (
          isPlaying ? (
            <>
              <div className="text-[#E53935] drop-shadow-[0_0_6px_rgba(229,57,53,0.3)]">[BATAJ_CORE.STREAMING.AUDIO:ACTIVE]</div>
              <div className="text-white/50">// BPM_SYNC: 120</div>
            </>
          ) : (
            <>
              <div className="text-white/60">[BATAJ_CORE.STATUS:LOCKED]</div>
              <div className="text-white/40">// AUDIO:MUTED</div>
            </>
          )
        ) : (
          <div className="text-white/40">[INITIALIZING_CORE...]</div>
        )}
      </div>
    </div>
  );
}

/* ============== Hero ============== */
function Hero() {
  return (
    <section id="top" className="relative pt-40 pb-20 lg:pt-48 lg:pb-32 overflow-hidden noise">
      <MasterGrid />
      <div className="relative mx-auto max-w-[1400px] px-4 lg:px-10">
        
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-center">
          <div className="lg:col-span-8 flex flex-col items-start text-left">
            <div className="flex items-center gap-3 mb-8 reveal">
              <span className="chip"><span className="dot pulse" /> [SYS_STATUS: ONLINE]</span>
              <span className="hidden sm:inline-flex chip border-none bg-transparent">v2.0.0-rc</span>
            </div>

            <h1 className="font-display tracking-tight leading-[0.9] text-[64px] sm:text-[80px] md:text-[110px] lg:text-[130px] font-medium">
              <div className="block"><SplitWords text="Software" /></div>
              <div className="block text-inkMute font-normal">
                <SplitWords text="con identidad." delayBase={150} />
              </div>
            </h1>

            <div className="mt-12 flex flex-col sm:flex-row items-start sm:items-center gap-6 reveal reveal-2">
              <p className="text-[18px] leading-[1.5] text-ink/80 max-w-[42ch]">
                Diseñamos y construimos aplicaciones web a medida. Estética premium, stack moderno, código limpio. Listas para operar.
              </p>
            </div>

            <div className="mt-10 flex flex-wrap items-center gap-3 reveal reveal-3">
              <a href="#products" className="btn btn-dark">Ver productos</a>
              <a href="#contact" className="btn btn-ghost">Hablar con el equipo</a>
            </div>
          </div>

          <div className="flex lg:col-span-4 justify-center lg:justify-end reveal reveal-4 mt-8 lg:mt-0">
            <RecordPlayer />
          </div>
        </div>

      </div>
    </section>
  );
}

/* ============== Manifesto ============== */
function Manifesto() {
  const pillars = [
    { n: '01', t: 'Identidad', d: 'Tipografía, ritmo y tono diseñados desde cero.' },
    { n: '02', t: 'Sistema', d: 'Componentes escalables, sin deuda visual.' },
    { n: '03', t: 'Operativo', d: 'Entregamos software que ya factura.' },
    { n: '04', t: 'Stack', d: 'React, Node, Postgres. Sin vendor lock-in.' }
  ];

  return (
    <section id="manifest" className="relative py-20 lg:py-24">
      <div className="mx-auto max-w-[1400px] px-4 lg:px-10">
        <div className="neo-card neo-glow rounded-2xl p-8 lg:p-14 relative overflow-hidden">
          <div className="absolute top-4 right-4 font-mono text-[10px] text-inkMute">// MANIFESTO</div>
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
            <div className="lg:col-span-5">
              <p className="chip mb-6 reveal">/ 04 Principios</p>
              <h2 className="font-display tracking-tight leading-[1] text-[48px] lg:text-[72px] font-medium reveal">
                No vendemos<br /><span className="text-inkMute">tecnología.</span>
              </h2>
              <p className="mt-6 text-[16px] leading-[1.6] text-ink/80 max-w-[34ch] reveal reveal-2">
                Vendemos productos terminados. Con estética. Con identidad. Listos para entrar al mercado el lunes.
              </p>
            </div>

            <div className="lg:col-span-7">
              <ul className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                {pillars.map((p, i) => (
                  <li key={p.n} className="neo-card p-6 rounded-xl reveal" style={{ transitionDelay: `${100 + i * 50}ms` }}>
                    <div className="font-mono text-[12px] text-inkMute mb-4">{p.n}</div>
                    <h3 className="font-display text-[24px] font-medium tracking-tight mb-2">{p.t}</h3>
                    <p className="text-[14.5px] leading-[1.5] text-ink/75">{p.d}</p>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== Products header ============== */
function ProductsIntro() {
  return (
    <section id="products" className="relative pt-20 pb-12">
      <div className="mx-auto max-w-[1400px] px-4 lg:px-10">
        <div className="neo-card rounded-2xl p-8 lg:p-14 text-left flex flex-col lg:flex-row lg:items-end justify-between gap-8 neo-glow">
          <div>
            <p className="chip mb-4 reveal">/ PRODUCTOS</p>
            <h2 className="font-display tracking-tight leading-[1] text-[48px] lg:text-[80px] font-medium reveal">
              Cada producto<br /><span className="text-inkMute">un universo.</span>
            </h2>
          </div>
          <p className="max-w-[40ch] text-[16px] leading-[1.6] text-ink/75 reveal reveal-2 lg:pb-2">
            Desde una agenda profesional hasta un dashboard de inteligencia comercial. Mismo estudio. Cuatro lenguajes visuales.
          </p>
        </div>
      </div>
    </section>
  );
}

/* ============== Process ============== */
function Process() {
  const steps = [
    { n: '01', t: 'Brief', d: 'Entendemos el negocio. No el ticket.', tag: '1 sem' },
    { n: '02', t: 'Sistema', d: 'Identidad, tokens y voz. Antes de codear.', tag: '2-3 sem' },
    { n: '03', t: 'Build', d: 'Sprints quincenales, deploy continuo.', tag: '6-12 sem' },
    { n: '04', t: 'Launch', d: 'Entregamos operativo. Cobranza, métricas.', tag: 'Día 1' }
  ];

  return (
    <section id="process" className="relative py-20 lg:py-24">
      <div className="mx-auto max-w-[1400px] px-4 lg:px-10">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 lg:gap-10 mb-12">
          <div className="lg:col-span-6">
            <p className="chip mb-4 reveal">/ PROCESO</p>
            <h2 className="font-display tracking-tight leading-[1] text-[48px] lg:text-[80px] font-medium reveal">
              De cero a producto.<br /><span className="text-inkMute">En semanas.</span>
            </h2>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {steps.map((s, i) =>
            <div key={s.n} className="neo-card neo-glow p-8 rounded-2xl reveal" style={{ transitionDelay: `${i * 50}ms` }}>
              <div className="flex items-center justify-between mb-8">
                <span className="font-mono text-[12px] text-inkMute bg-ink/5 px-2 py-1 rounded">{s.n}</span>
                <span className="font-mono text-[11px] text-inkMute uppercase">{s.tag}</span>
              </div>
              <h3 className="font-display text-[32px] font-medium tracking-tight mb-3">{s.t}</h3>
              <p className="text-[14px] leading-[1.5] text-ink/75">{s.d}</p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ============== Stats strip ============== */
function Stats() {
  const stats = [
    { v: '4', l: 'PRODUCTOS EN PRODUCCIÓN' },
    { v: '100%', l: 'DISEÑO + DEV INTEGRADO' },
    { v: '<12w', l: 'TIEMPO AL PRIMER LAUNCH' },
    { v: '0', l: 'PLANTILLAS REUTILIZADAS' }
  ];

  return (
    <section className="relative py-20">
      <div className="mx-auto max-w-[1400px] px-4 lg:px-10">
        <div className="neo-card p-10 lg:p-14 rounded-2xl bg-ink text-white neo-glow overflow-hidden relative">
          <div className="absolute top-4 right-4 font-mono text-[10px] text-white/30">[ METRICS_DB ]</div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-10 lg:gap-4">
            {stats.map((s, i) =>
              <div key={i} className="reveal" style={{ transitionDelay: `${i * 50}ms` }}>
                <div className="font-mono text-[64px] lg:text-[96px] leading-[1] tracking-tighter text-white/90">
                  {s.v}
                </div>
                <div className="font-mono text-[11px] text-white/50 mt-3">{s.l}</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== CTA / Footer ============== */
function CTAFooter() {
  return (
    <section id="contact" className="relative pt-20 pb-12 overflow-hidden">
      <div className="relative mx-auto max-w-[1400px] px-4 lg:px-10">
        
        <div className="neo-card neo-glow p-8 lg:p-16 rounded-2xl text-left mb-16 relative overflow-hidden">
          <div className="absolute bottom-4 right-4 font-mono text-[10px] text-inkMute">SYS_HALT</div>
          <p className="chip mb-6 reveal">/ CONTACTO</p>
          <h2 className="font-display tracking-tight leading-[1] text-[56px] sm:text-[80px] lg:text-[110px] font-medium reveal">
            Hablemos<br /><span className="text-inkMute">de tu proyecto.</span>
          </h2>
          <div className="mt-8 flex flex-col sm:flex-row gap-4 reveal reveal-2">
            <a href="mailto:comercial@batajsystems.com" className="btn btn-dark">
              comercial@batajsystems.com
            </a>
            <a href="https://wa.me/5491157623850" target="_blank" rel="noopener noreferrer" className="btn btn-ghost">
              Escríbenos por WhatsApp
            </a>
          </div>
        </div>

        <footer className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6 text-[12px] text-inkMute font-mono">
          <div className="flex items-center gap-2">
            <span className="w-5 h-5 rounded bg-ink/10 text-ink grid place-items-center font-display text-[12px] leading-none pb-px">b</span>
            <span>Bataj Systems · LATAM</span>
          </div>
          <div className="flex gap-6">
            <a className="hover:text-ink transition-colors" href="#">Instagram</a>
            <a className="hover:text-ink transition-colors" href="#">LinkedIn</a>
            <a className="hover:text-ink transition-colors" href="#">GitHub</a>
          </div>
          <div>© 2024-26 · [SYS_OK]</div>
        </footer>
      </div>
    </section>
  );
}

/* Expose */
Object.assign(window, {
  useReveal, SplitWords, Nav, Hero, Manifesto, ProductsIntro, Process, Stats, CTAFooter, MasterGrid
});