/* AORYN — main app components */

const { useState, useEffect, useRef, useMemo } = React;

// ============================================================================
// HOOKS
// ============================================================================
function useScrollProgress() {
  const [p, setP] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const scrolled = h.scrollTop;
      const max = h.scrollHeight - h.clientHeight;
      setP(max > 0 ? scrolled / max : 0);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return p;
}

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

// Magnetic effect (subtle pull toward cursor)
function useMagnetic(ref, strength = 0.25) {
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const rect = el.getBoundingClientRect();
      const x = e.clientX - (rect.left + rect.width / 2);
      const y = e.clientY - (rect.top + rect.height / 2);
      el.style.transform = `translate(${x * strength}px, ${y * strength}px)`;
    };
    const onLeave = () => { el.style.transform = ''; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, [ref, strength]);
}

// ============================================================================
// CURSOR
// ============================================================================
function CursorDot() {
  const ref = useRef(null);
  useEffect(() => {
    let raf;
    let tx = 0, ty = 0, x = 0, y = 0;
    const onMove = (e) => { tx = e.clientX; ty = e.clientY; ref.current?.classList.add('visible'); };
    const onOut = () => ref.current?.classList.remove('visible');
    const tick = () => {
      x += (tx - x) * 0.22;
      y += (ty - y) * 0.22;
      if (ref.current) ref.current.style.transform = `translate(${x}px, ${y}px)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    window.addEventListener('mousemove', onMove);
    document.addEventListener('mouseleave', onOut);
    const onOver = (e) => {
      const t = e.target;
      if (t.closest('a, button, input, textarea, .work-card, .service-card, .tool-chip, [data-cursor="hover"]')) {
        ref.current?.classList.add('hover');
      } else {
        ref.current?.classList.remove('hover');
      }
    };
    document.addEventListener('mouseover', onOver);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseleave', onOut);
      document.removeEventListener('mouseover', onOver);
    };
  }, []);
  return (
    <div ref={ref} className="cursor-dot">
      <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path d="M3 2 L3 19 L8 14.5 L11.2 21.5 L13.8 20.3 L10.6 13.3 L17 13.3 Z"
              fill="currentColor" stroke="currentColor" strokeWidth="0.6" strokeLinejoin="round" />
      </svg>
    </div>
  );
}

// ============================================================================
// SCROLL PROGRESS BAR
// ============================================================================
function ScrollProgress() {
  const p = useScrollProgress();
  return <div className="scroll-progress" style={{ transform: `scaleX(${p})` }} />;
}

// ============================================================================
// NAVBAR
// ============================================================================
function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [hasSession, setHasSession] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    try { setHasSession(!!localStorage.getItem('aoryn_user')); } catch (e) {}
  }, []);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const goTo = (id) => {
    setMenuOpen(false);
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);
  };
  return (
    <>
    <nav className={`navbar ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-brand">
        <span className="mark"></span>
        <span>AORYN</span>
        {hasSession && <span className="session-badge" title="Sesión activa"><span className="sb-dot"></span>Sesión activa</span>}
      </div>
      
      <div className="nav-links">
        <button onClick={() => goTo('services')}>Servicios</button>
        <button onClick={() => goTo('works')}>Trabajos</button>
        <button onClick={() => goTo('philosophy')}>Filosofía</button>
        <button onClick={() => goTo('calculator')}>Presupuesto</button>
      </div>
      <a href="portal/PortalCliente.html" className={`nav-cta nav-cta-desktop ${hasSession ? 'has-session' : ''}`}>
        {hasSession ? 'Volver al portal' : 'Área cliente'}
      </a>
      <button className={`nav-burger ${menuOpen ? 'open' : ''}`} onClick={() => setMenuOpen(!menuOpen)} aria-label="Menú">
        <span></span><span></span><span></span>
      </button>
    </nav>
    {menuOpen && (
      <div className="mobile-menu" onClick={() => setMenuOpen(false)}>
        <div className="mobile-menu-inner" onClick={(e) => e.stopPropagation()}>
          <button onClick={() => goTo('services')}>Servicios</button>
          <button onClick={() => goTo('works')}>Trabajos</button>
          <button onClick={() => goTo('philosophy')}>Filosofía</button>
          <button onClick={() => goTo('calculator')}>Presupuesto</button>
          <a href="portal/PortalCliente.html" className="mobile-cta">{hasSession ? 'Volver al portal' : 'Área cliente'}</a>
        </div>
      </div>
    )}
    </>
  );
}

// ============================================================================
// HERO
// ============================================================================
function Hero() {
  const wrapRef = useRef(null);
  const [rotation, setRotation] = useState(0);
  const ctaRef = useRef(null);
  useMagnetic(ctaRef, 0.18);

  useEffect(() => {
    let auto = 0;
    let manual = null;
    const tick = () => {
      auto = (auto + 0.2) % 360;
      const target = manual !== null ? manual : auto;
      setRotation(target);
      raf = requestAnimationFrame(tick);
    };
    let raf = requestAnimationFrame(tick);
    const handleMove = (e) => {
      const el = wrapRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;
      const dx = e.clientX - cx;
      const dy = e.clientY - cy;
      const angle = (Math.atan2(dy, dx) * 180 / Math.PI + 360) % 360;
      manual = angle;
    };
    window.addEventListener('mousemove', handleMove);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', handleMove);
    };
  }, []);

  // parallax on hero content
  const heroRef = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      if (!heroRef.current) return;
      const y = window.scrollY;
      heroRef.current.style.setProperty('--y', `${y * 0.4}px`);
      heroRef.current.style.setProperty('--op', `${Math.max(0, 1 - y / 600)}`);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <section className="hero" id="hero">
      <div className="hero-mesh">
        <div className="mesh-blob b1" />
        <div className="mesh-blob b2" />
        <div className="mesh-blob b3" />
      </div>
      <div className="hero-grid-overlay" />
      <div className="hero-vignette" />

      <div
        ref={heroRef}
        className="hero-content"
        style={{
          transform: 'translateY(calc(var(--y, 0px) * -1))',
          opacity: 'var(--op, 1)'
        }}
      >
        <div className="hero-eyebrow reveal in">
          <span className="pulse"></span>
          <span>Studio · Disponible 2026</span>
        </div>

        <div ref={wrapRef} className="hero-symbol-wrap reveal in" style={{ '--reveal-delay': '100ms' }}>
          <div className="hero-symbol-glow" style={{ '--rotation': `${rotation}deg` }} />
          <div className="hero-symbol-ring" style={{ '--rotation': `${rotation}deg` }} />
          <div className="hero-symbol-img" />
        </div>

        <div className="hero-headline-sm reveal" style={{ '--reveal-delay': '250ms' }}>
          Studio
        </div>

        <div className="hero-wordmark reveal" style={{ '--reveal-delay': '300ms' }}>
          {'AORYN'.split('').map((c, i) => (
            <span key={i} className="char">{c}</span>
          ))}
        </div>

        <h1 className="hero-headline reveal" style={{ '--reveal-delay': '450ms' }}>
          Marcas que <span className="accent text-gradient-shift">respiran</span>
          <br />y conectan.
        </h1>

        <p className="hero-sub reveal" style={{ '--reveal-delay': '600ms' }}>
          Estrategia, diseño y experiencias digitales para negocios reales que quieren
          comunicar con claridad — sin promesas mágicas, con proceso.
        </p>

        <div className="hero-actions reveal" style={{ '--reveal-delay': '750ms' }}>
          <a ref={ctaRef} href="#contact" className="btn-primary" onClick={(e) => { e.preventDefault(); document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' }); }}>
            Iniciar conversación
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </a>
          <a href="#works" className="btn-secondary" onClick={(e) => { e.preventDefault(); document.getElementById('works')?.scrollIntoView({ behavior: 'smooth' }); }}>
            Ver trabajos
          </a>
        </div>
      </div>

      <div className="scroll-cue">
        <span>scroll</span>
        <span className="line"></span>
      </div>
    </section>
  );
}

// ============================================================================
// MARQUEE (between hero and services)
// ============================================================================
function Marquee() {
  const items = ['Estrategia', 'Diseño', 'Audiovisual', 'Web', 'Automatización', 'IA aplicada'];
  const all = [...items, ...items, ...items];
  return (
    <div className="marquee-section">
      <div className="marquee-track">
        {all.map((t, i) => (
          <div key={i} className={`item ${i % 2 === 1 ? 'outline' : ''}`}>
            {t}
            <span className="dot"></span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Make available to other scripts
Object.assign(window, { CursorDot, ScrollProgress, Navbar, Hero, Marquee, useReveal, useMagnetic });
