/* global React, Compass, Arrow, GM_ROUTES */
const { useEffect: nUseEffect, useState: nUseState } = React;

const NAV_ROUTES = (window.GM_CONFIG && window.GM_CONFIG.routes) || GM_ROUTES || {
  home: '/', services: '/servicios/', cases: '/casos/',
  about: '/nosotros/', blog: '/blog-gm/', contact: '/contacto/',
};

function navHref(key) {
  return NAV_ROUTES[key] || '/';
}

function navClick(e, key, setRoute) {
  if (e.ctrlKey || e.metaKey || e.shiftKey) return; // permite abrir en nueva pestaña
  e.preventDefault();
  setRoute(key);
}

function Nav({ route, setRoute }) {
  const [scrolled, setScrolled] = nUseState(false);
  const [theme, setTheme] = nUseState(() => document.documentElement.getAttribute('data-theme') || 'light');

  nUseEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    const mo = new MutationObserver(() => {
      setTheme(document.documentElement.getAttribute('data-theme') || 'light');
    });
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => { window.removeEventListener('scroll', onScroll); mo.disconnect(); };
  }, []);

  const links = [
    ['home',     'Inicio'],
    ['services', 'Servicios'],
    ['cases',    'Casos'],
    ['about',    'Nosotros'],
    ['blog',     'Blog'],
  ];

  const logoSrc = (window.GM_CONFIG ? window.GM_CONFIG.assetsUrl + '/img/' : 'assets/')
    + (theme === 'dark' ? 'logo-blanco.png' : 'logo-color.png');

  return (
    <header className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a
          className="brand"
          href={navHref('home')}
          onClick={(e) => navClick(e, 'home', setRoute)}
          aria-label="Growth Masters"
        >
          <img src={logoSrc} alt="Growth Masters" style={{ height: 72, width: 'auto', display: 'block' }} />
        </a>
        <nav className="nav-links">
          {links.map(([k, label]) => (
            <a
              key={k}
              className={`nav-link ${route === k ? 'active' : ''}`}
              href={navHref(k)}
              onClick={(e) => navClick(e, k, setRoute)}
            >
              {label}
            </a>
          ))}
          <a
            className="btn btn-accent"
            href={navHref('contact')}
            onClick={(e) => navClick(e, 'contact', setRoute)}
            style={{ marginLeft: 8 }}
          >
            Hablemos <Arrow />
          </a>
        </nav>
      </div>
    </header>
  );
}

function Footer({ setRoute }) {
  const logoSrc = (window.GM_CONFIG ? window.GM_CONFIG.assetsUrl + '/img/' : 'assets/') + 'logo-blanco.png';

  const navLinks = [
    ['home',     'Inicio'],
    ['services', 'Servicios'],
    ['cases',    'Casos de éxito'],
    ['about',    'Nosotros'],
    ['blog',     'Blog'],
    ['contact',  'Contacto'],
  ];

  return (
    <footer className="footer">
      <div className="container">
        <div style={{ marginBottom: 48 }}>
          <img src={logoSrc} alt="Growth Masters" style={{ height: 80, width: 'auto', display: 'block' }} />
        </div>
        <div className="grid grid-4" style={{ gap: 40, alignItems: 'start' }}>
          <div style={{ gridColumn: 'span 2' }}>
            <div className="footer-cta-headline" style={{ fontSize: 'clamp(40px, 5vw, 72px)', fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 0.96 }}>
              ¿Listos para<br /><span className="serif" style={{ color: 'var(--accent)' }}>crecer</span> juntos?
            </div>
            <p style={{ marginTop: 24, maxWidth: '40ch', color: 'rgba(246,243,236,0.7)' }}>
              Agenda una consultoría gratuita de 30 minutos. Sin compromiso, con ideas accionables.
            </p>
            <a
              className="btn btn-accent"
              href={navHref('contact')}
              onClick={(e) => navClick(e, 'contact', setRoute)}
              style={{ marginTop: 32, display: 'inline-flex' }}
            >
              Agendar llamada <Arrow />
            </a>
          </div>
          <div className="footer-nav-col">
            <div className="ticker" style={{ color: 'rgba(246,243,236,0.5)', marginBottom: 16 }}>Navegación</div>
            <div className="stack-md" style={{ display: 'flex', flexDirection: 'column' }}>
              {navLinks.map(([k, l]) => (
                <a key={k} href={navHref(k)} onClick={(e) => navClick(e, k, setRoute)}>{l}</a>
              ))}
            </div>
          </div>
          <div className="footer-contact-col">
            <div className="ticker" style={{ color: 'rgba(246,243,236,0.5)', marginBottom: 16 }}>Contacto</div>
            <div className="stack-md" style={{ display: 'flex', flexDirection: 'column' }}>
              <a href="mailto:diego.bustos@d2consultoresdigitales.com">diego.bustos@<br />d2consultoresdigitales.com</a>
              <a href="tel:+573052604847">+57 305 260 4847</a>
              <a href="https://growthmasters.digital" target="_blank" rel="noopener">growthmasters.digital</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom" style={{ marginTop: 80, paddingTop: 32, borderTop: '1px solid rgba(246,243,236,0.1)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <div className="ticker" style={{ color: 'rgba(246,243,236,0.5)' }}>© 2026 Growth Masters · Una marca de D² Consultores Digitales</div>
          <div className="ticker" style={{ color: 'rgba(246,243,236,0.5)' }}>Bogotá · Colombia</div>
        </div>
      </div>
    </footer>
  );
}

const { useState: mnUseState, useEffect: mnUseEffect } = React;

function MobileNav({ route, setRoute }) {
  const [visible, setVisible] = mnUseState(window.innerWidth <= 880);

  mnUseEffect(() => {
    const mq = window.matchMedia('(max-width: 880px)');
    const handler = (e) => setVisible(e.matches);
    mq.addEventListener ? mq.addEventListener('change', handler) : mq.addListener(handler);
    setVisible(mq.matches);
    return () => mq.removeEventListener ? mq.removeEventListener('change', handler) : mq.removeListener(handler);
  }, []);

  if (!visible) return null;

  const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#EC4E3C';
  const surface = getComputedStyle(document.documentElement).getPropertyValue('--surface').trim() || '#FAFAF8';
  const inkLow = getComputedStyle(document.documentElement).getPropertyValue('--ink-low').trim() || '#9A9590';

  const navStyle = {
    position: 'fixed',
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 99999,
    display: 'grid',
    gridTemplateColumns: 'repeat(5, 1fr)',
    background: surface,
    borderTop: '1px solid rgba(0,0,0,0.1)',
    paddingTop: '6px',
    paddingBottom: 'calc(8px + env(safe-area-inset-bottom, 0px))',
    paddingLeft: '4px',
    paddingRight: '4px',
    gap: '2px',
    boxShadow: '0 -4px 24px rgba(0,0,0,0.08)',
  };

  const itemBase = {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '3px',
    padding: '8px 4px 6px',
    borderRadius: '12px',
    color: inkLow,
    fontFamily: 'var(--font-mono, monospace)',
    fontSize: '9px',
    letterSpacing: '0.06em',
    textTransform: 'uppercase',
    textDecoration: 'none',
    cursor: 'pointer',
    WebkitTapHighlightColor: 'transparent',
    transition: 'color .15s',
    border: 'none',
    background: 'none',
  };

  const items = [
    ['home', 'Inicio', (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
      </svg>
    )],
    ['services', 'Servicios', (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/>
      </svg>
    )],
    ['cases', 'Casos', (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/>
      </svg>
    )],
    ['about', 'Nosotros', (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
      </svg>
    )],
    ['contact', 'Contacto', (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/>
      </svg>
    )],
  ];

  return (
    <nav style={navStyle} aria-label="Navegación principal">
      {items.map(([key, label, icon]) => {
        const isActive = route === key;
        return (
          <a
            key={key}
            style={{ ...itemBase, color: isActive ? accent : inkLow }}
            href={navHref(key)}
            onClick={(e) => navClick(e, key, setRoute)}
            aria-label={label}
          >
            {icon}
            <span>{label}</span>
          </a>
        );
      })}
    </nav>
  );
}

Object.assign(window, { Nav, Footer, MobileNav });
