
// ============================================================
// ESTUDIO RETÓRICA · Navegación, motion y chrome compartido
// ============================================================

const MotionBoot = () => {
  React.useEffect(() => {
    const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const revealNodes = Array.from(document.querySelectorAll('[data-reveal]'));
    const counterNodes = Array.from(document.querySelectorAll('[data-counter]'));

    revealNodes.forEach((node, index) => {
      node.style.setProperty('--reveal-delay', `${Math.min(index * 60, 360)}ms`);
    });

    let revealObserver;
    if (!reduceMotion && revealNodes.length) {
      revealObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('is-revealed');
            revealObserver.unobserve(entry.target);
          }
        });
      }, { threshold: 0.18, rootMargin: '0px 0px -8% 0px' });
      revealNodes.forEach((node) => revealObserver.observe(node));
    } else {
      revealNodes.forEach((node) => node.classList.add('is-revealed'));
    }

    let counterObserver;
    if (counterNodes.length) {
      const animateCounter = (node) => {
        if (node.dataset.counted === 'true') return;
        node.dataset.counted = 'true';
        const target = Number(node.dataset.counter || '0');
        const duration = reduceMotion ? 0 : 1200;
        const start = performance.now();
        const step = (time) => {
          const progress = duration === 0 ? 1 : Math.min((time - start) / duration, 1);
          const eased = 1 - Math.pow(1 - progress, 3);
          node.textContent = String(Math.round(target * eased));
          if (progress < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
      };

      counterObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            animateCounter(entry.target);
            counterObserver.unobserve(entry.target);
          }
        });
      }, { threshold: 0.35 });
      counterNodes.forEach((node) => counterObserver.observe(node));
    }

    return () => {
      if (revealObserver) revealObserver.disconnect();
      if (counterObserver) counterObserver.disconnect();
    };
  }, []);

  return null;
};

const ScrollProgress = () => {
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      const doc = document.documentElement;
      const max = doc.scrollHeight - window.innerHeight;
      const value = max > 0 ? (window.scrollY / max) * 100 : 0;
      setProgress(Math.min(100, Math.max(0, value)));
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <div className="hp-scroll-progress" aria-hidden="true">
      <span style={{ width: `${progress}%` }} />
    </div>
  );
};

const Preloader = () => {
  const [hidden, setHidden] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setHidden(true), 420);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className={`preloader ${hidden ? 'preloader--hidden' : ''}`} aria-hidden={hidden}>
      <div className="preloader__panel">
        <img src={getRetoricaAssetUrl('assets/retorica-logo.png')} alt="Retórica" className="preloader__logo" />
        <div className="preloader__line" />
      </div>
    </div>
  );
};

const StickyContactBar = () => (
  <div className="hp-floatbar" data-reveal>
    <a href="https://api.whatsapp.com/send/?app_absent=0&phone=34617492461&text=&type=phone_number" className="hp-floatbar__item hp-floatbar__item--primary">
      <Icon name="phone" size={16} />
      WhatsApp
    </a>
    <a href="/brief/" className="hp-floatbar__item hp-floatbar__item--ghost">
      <Icon name="download" size={16} />
      Brief
    </a>
  </div>
);

const Nav = ({ currentPage = 'home' }) => {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const links = [
    { k: 'home', label: 'Inicio', href: '/' },
    { k: 'services', label: 'Servicios +', href: '/servicios/' },
    { k: 'portfolio', label: 'Portafolio', href: '/portafolio/' },
    { k: 'studio', label: 'Estudio', href: '/estudio/' },
    { k: 'journal', label: 'Contacto', href: '/contacto/' },
  ];

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 14);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    const close = () => setOpen(false);
    window.addEventListener('resize', close);
    return () => window.removeEventListener('resize', close);
  }, []);

  return (
    <>
      <header className={`hp-nav ${scrolled ? 'is-scrolled' : ''}`}>
        <ScrollProgress />
        <div className="hp-nav__inner">
          <a href="/" className="hp-nav__brand" aria-label="Retórica">
            <RetoricaLogo size={240} />
          </a>
          <ul className="hp-nav__links">
            {links.map((l) => (
              <li key={l.k}><a href={l.href} className={currentPage === l.k ? 'is-active' : ''}>{l.label}</a></li>
            ))}
          </ul>
          <div className="hp-nav__cta">
            <a href={currentPage === 'home' ? '#contact' : '/contacto/#contact'} className="btn btn--primary btn--lg">
              Contáctanos <Icon name="phone" size={16} />
            </a>
          </div>
          <button className="hp-nav__burger" aria-label="Menú" onClick={() => setOpen(v => !v)}>
            <Icon name={open ? 'close' : 'menu'} size={20} />
          </button>
          {open && (
            <div className="hp-nav__mobile">
              {links.map((l) => (
                <a key={l.k} href={l.href} className={currentPage === l.k ? 'is-active' : ''}>{l.label}</a>
              ))}
              <a href="/brief/" className="btn btn--secondary btn--lg">Descargar brief</a>
              <a href={currentPage === 'home' ? '#contact' : '/contacto/#contact'} className="btn btn--primary btn--lg">Contáctanos</a>
            </div>
          )}
        </div>
      </header>
      <StickyContactBar />
    </>
  );
};

const Footer = () => (
  <footer className="hp-footer">
    <div className="hp-footer__inner">
      <div className="hp-footer__brand">
        <RetoricaLogo size={220} inverse />
        <p className="t-body" style={{ color: 'rgba(255,255,255,0.74)', marginTop: 22, maxWidth: 420 }}>
          Estudio Retórica integra identidad corporativa, diseño web, contenido, audiovisual, activaciones y posicionamiento dentro de una experiencia más clara y más orientada a conversación.
        </p>
        <div className="hp-footer__social">
          <a href="https://estudioretorica.com/">Sitio oficial</a>
          <a href="https://estudioretorica.com/portafolio/">Portafolio</a>
          <a href="https://estudioretorica.com/contacto/">Contacto</a>
          <a href="/brief/">Brief inicial</a>
        </div>
      </div>
      <div className="hp-footer__cols">
        <div>
          <div className="t-eyebrow" style={{ color: 'var(--brand-yellow)' }}>Mapa</div>
          <ul>
            <li><a href="/">Inicio</a></li>
            <li><a href="/servicios/">Servicios</a></li>
            <li><a href="/portafolio/">Portafolio</a></li>
            <li><a href="/estudio/">Estudio</a></li>
          </ul>
        </div>
        <div>
          <div className="t-eyebrow" style={{ color: 'var(--brand-yellow)' }}>Servicios</div>
          <ul>
            <li><a href="/servicios/">Identidad corporativa</a></li>
            <li><a href="/servicios/">Diseño web</a></li>
            <li><a href="/servicios/">Gestión de redes sociales</a></li>
            <li><a href="/servicios/">Posicionamiento web y marketing</a></li>
          </ul>
        </div>
        <div>
          <div className="t-eyebrow" style={{ color: 'var(--brand-yellow)' }}>Contacto</div>
          <ul>
            <li><a href="mailto:direccion@estudioretorica.com">direccion@estudioretorica.com</a></li>
            <li><a href="https://api.whatsapp.com/send/?app_absent=0&phone=34617492461&text=&type=phone_number">+34 617492461</a></li>
            <li><a href="/contacto/">Canales y briefing</a></li>
            <li><a href="/brief/">Descargar brief</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div className="hp-footer__bottom">
      <div className="t-caption" style={{ color: 'rgba(255,255,255,0.56)' }}>© 2026 Estudio Retórica · versión estática optimizada para presentación, confianza y contacto.</div>
      <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap' }}>
        <a href="/contacto/#contact" className="t-caption" style={{ color: 'rgba(255,255,255,0.8)' }}>Formulario de contacto</a>
        <a href="https://estudioretorica.com/portafolio/" className="t-caption" style={{ color: 'rgba(255,255,255,0.8)' }}>Portafolio oficial</a>
      </div>
    </div>
  </footer>
);

const PageHeader = ({ eyebrow, title, subtitle, bg = 'yellow', ctaLabel, ctaHref = '/contacto/#contact' }) => (
  <section className={`hp-page-header hp-page-header--${bg === 'black' ? 'black' : bg === 'white' ? 'white' : 'yellow'}`} style={{ background: bg === 'black' ? 'var(--brand-black)' : bg === 'white' ? 'var(--brand-white)' : 'var(--brand-yellow)' }}>
    <div className="hp-page-header__inner" data-reveal>
      <div className="t-eyebrow" style={{ color: bg === 'black' ? 'var(--brand-yellow)' : 'rgba(0,0,0,0.68)' }}>{eyebrow}</div>
      <h1 className="t-display-lg" style={{ marginTop: 20 }}>{title}</h1>
      {subtitle && <p className="t-body-lg" style={{ marginTop: 18, maxWidth: 760, color: bg === 'black' ? 'rgba(255,255,255,0.78)' : 'rgba(0,0,0,0.74)' }}>{subtitle}</p>}
      {ctaLabel && <a href={ctaHref} className={`btn btn--lg ${bg === 'black' ? 'btn--primary' : 'btn--secondary'}`} style={{ marginTop: 28 }}>{ctaLabel}</a>}
    </div>
  </section>
);

Object.assign(window, { Preloader, Nav, Footer, PageHeader, StickyContactBar, MotionBoot });
