// Shared chrome: Nav, Footer, helpers used across all pages.
// Bilingual: detects language from URL path (/en/* → en, otherwise → es).

const { useEffect, useRef, useState } = React;

/* ----------------- i18n helpers ----------------- */
function detectLang() {
  return typeof window !== 'undefined' && window.location.pathname.startsWith('/en/')
    ? 'en'
    : 'es';
}

// Mirror of lib/i18n.js#toggleHref (kept in sync; ~5 lines).
function toggleHref(targetLang, currentPath) {
  const baseLessPath = currentPath.replace(/^\/en(\/|$)/, '/');
  if (targetLang === 'es') return baseLessPath;
  return baseLessPath === '/' ? '/en/' : '/en' + baseLessPath;
}

const STRINGS = {
  es: {
    nav: { home: 'Inicio', pricing: 'Precios', about: 'Quiénes somos', benchmark: 'Diagnóstico', contact: 'Contacto' },
    cta: 'Solicita una demo',
    home: '/',
    about: '/about',
    benchmark: '/benchmark',
    contact: '/contact',
    privacy: '/privacy',
    security: '/security',
    terms: '/terms',
    footer: {
      tagline: <>Tu aliado para el <em>comercio</em> agéntico.</>,
      empresa: 'Empresa',
      whoWeAre: 'Quiénes somos',
      contact: 'Contacto',
      legal: 'Legal',
      privacy: 'Política de privacidad',
      security: 'Seguridad',
      terms: 'Términos del servicio',
      copyright: '© 2026 LISTO LABS LTD',
      location: 'LONDRES · BARCELONA',
    },
    finalCta: {
      eyebrow: 'Contacto',
      title: <>¿Listo para estar dentro de la <em className="hl">IA</em>?</>,
      lead: 'Habla con nuestro equipo. Te enseñamos cómo estás hoy y qué necesitas para empezar a distribuirte en estos canales.',
      cta: 'Solicita una demo',
    },
    midCtaDefault: <>Mira cómo se ve esto en tu hotel. <a href="/contact" style={{ color: 'var(--blue-deep)', textDecoration: 'none', borderBottom: '2px solid var(--blue-deep)' }}>Hablemos.</a></>,
  },
  en: {
    nav: { home: 'Home', pricing: 'Pricing', about: 'About', benchmark: 'Benchmark', contact: 'Contact' },
    cta: 'Request a demo',
    home: '/en/',
    about: '/en/about',
    benchmark: '/en/benchmark',
    contact: '/en/contact',
    privacy: '/en/privacy',
    security: '/en/security',
    terms: '/en/terms',
    footer: {
      tagline: <>Your <em>agentic</em> commerce partner.</>,
      empresa: 'Company',
      whoWeAre: 'About',
      contact: 'Contact',
      legal: 'Legal',
      privacy: 'Privacy policy',
      security: 'Security',
      terms: 'Terms of service',
      copyright: '© 2026 LISTO LABS LTD',
      location: 'LONDON · BARCELONA',
    },
    finalCta: {
      eyebrow: 'Contact',
      title: <>Ready to compete inside <em className="hl">AI</em>?</>,
      lead: "Talk to our team. We'll show you where you stand today and what it takes to start distributing through these channels.",
      cta: 'Request a demo',
    },
    midCtaDefault: <>See what this looks like for your hotel. <a href="/en/contact" style={{ color: 'var(--blue-deep)', textDecoration: 'none', borderBottom: '2px solid var(--blue-deep)' }}>Let's talk.</a></>,
  },
};

window.detectLang = detectLang;
window.STRINGS = STRINGS;

/* ----------------- Nav ----------------- */
function Nav({ active }) {
  const lang = detectLang();
  const t = STRINGS[lang];
  const [menuOpen, setMenuOpen] = useState(false);
  const links = [
    { id: 'home', label: t.nav.home, href: t.home },
    // Pricing hidden for this version — re-enable by uncommenting
    // { id: 'pricing', label: t.nav.pricing, href: active === 'home' ? '#pricing' : t.home + '#pricing' },
    { id: 'about', label: t.nav.about, href: t.about },
    { id: 'benchmark', label: t.nav.benchmark, href: t.benchmark },
    { id: 'contact', label: t.nav.contact, href: t.contact },
  ];
  const currentPath = typeof window !== 'undefined' ? window.location.pathname : '/';
  // ?setlang persists the manual choice as a cookie (server-side), so it always
  // overrides Accept-Language auto-routing on future visits.
  const esHref = toggleHref('es', currentPath) + '?setlang=es';
  const enHref = toggleHref('en', currentPath) + '?setlang=en';

  // Lock body scroll while the mobile menu is open.
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <nav className={'nav' + (menuOpen ? ' nav-open' : '')}>
      <div className="nav-inner">
        <a href={t.home} className="nav-brand" aria-label="Listo">
          <img className="nav-brand-mark" src="/assets/listo-mark.png" alt="" aria-hidden="true" />
          <span className="nav-brand-word">Listo</span>
        </a>
        <button
          type="button"
          className="nav-toggle"
          aria-label={menuOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={menuOpen}
          aria-controls="nav-menu"
          onClick={() => setMenuOpen((v) => !v)}
        >
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            {menuOpen ? (
              <path d="M6 6l12 12M18 6L6 18" />
            ) : (
              <path d="M3 6h18M3 12h18M3 18h18" />
            )}
          </svg>
        </button>
        <div className="nav-links" id="nav-menu">
          {links.map((l) => (
            <a
              key={l.id}
              href={l.href}
              onClick={closeMenu}
              className={'nav-link' + (active === l.id ? ' active' : '')}
            >
              {l.label}
            </a>
          ))}
          <span className="nav-lang nav-link-keep" aria-label="Language">
            <a href={esHref} className={'nav-lang-opt' + (lang === 'es' ? ' active' : '')}>ES</a>
            <span className="nav-lang-sep" aria-hidden="true">|</span>
            <a href={enHref} className={'nav-lang-opt' + (lang === 'en' ? ' active' : '')}>EN</a>
          </span>
          <a href={t.contact} className="nav-cta nav-link-keep" onClick={closeMenu}>
            {t.cta} <span aria-hidden="true" style={{ marginLeft: 2 }}>→</span>
          </a>
        </div>
      </div>
    </nav>
  );
}

/* ----------------- Footer ----------------- */
function Footer() {
  const lang = detectLang();
  const t = STRINGS[lang];
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-brand">
          <div className="footer-brand-lockup">
            <img className="footer-brand-mark" src="/assets/listo-mark.png" alt="" aria-hidden="true" />
            <span className="footer-brand-word">Listo</span>
          </div>
          <p>{t.footer.tagline}</p>
        </div>
        <div className="footer-col">
          <h4>{t.footer.empresa}</h4>
          <a href={t.about}>{t.footer.whoWeAre}</a>
          <a href={t.benchmark}>{t.nav.benchmark}</a>
          {/* Pricing hidden for this version — re-enable by uncommenting */}
          {/* <a href={t.home + '#pricing'}>{t.nav.pricing}</a> */}
          <a href={t.contact}>{t.footer.contact}</a>
          <a href="https://www.linkedin.com/company/listoai/" target="_blank" rel="noreferrer">LinkedIn</a>
        </div>
        <div className="footer-col">
          <h4>{t.footer.legal}</h4>
          <a href={t.privacy}>{t.footer.privacy}</a>
          <a href={t.security}>{t.footer.security}</a>
          <a href={t.terms}>{t.footer.terms}</a>
        </div>
      </div>
      <div className="footer-bottom">
        <span>{t.footer.copyright}</span>
        <span>{t.footer.location}</span>
      </div>
    </footer>
  );
}

/* ----------------- Reveal on scroll ----------------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    if (!('IntersectionObserver' in window)) {
      els.forEach((e) => e.classList.add('in'));
      return;
    }
    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 -40px 0px' }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ----------------- Scroll to #hash after async render -----------------
   Cross-page anchor links (e.g. "index.html#pricing" from another page) land
   before React has rendered the target section, so the native jump finds
   nothing. Poll briefly after mount, then scroll to it. */
function useHashScroll() {
  useEffect(() => {
    const id = decodeURIComponent((window.location.hash || '').slice(1));
    if (!id) return;
    let tries = 0;
    const tryScroll = () => {
      const el = document.getElementById(id);
      if (el) {
        el.scrollIntoView({ behavior: 'instant', block: 'start' });
      } else if (tries++ < 40) {
        setTimeout(tryScroll, 50);
      }
    };
    requestAnimationFrame(() => setTimeout(tryScroll, 0));
  }, []);
}

/* ----------------- Final CTA block ----------------- */
function FinalCTA() {
  const lang = detectLang();
  const t = STRINGS[lang].finalCta;
  return (
    <section className="final-cta" id="cta">
      <img
        src="/assets/listo-mark.png"
        alt=""
        className="swoosh"
        style={{
          right: -240,
          bottom: -260,
          width: 900,
          opacity: 0.18,
          transform: 'rotate(-12deg)',
        }}
      />
      <div className="container" style={{ position: 'relative', textAlign: 'center' }}>
        <div className="reveal">
          <h2 className="display" style={{ fontSize: 'clamp(48px, 6vw, 96px)', margin: '0 auto', maxWidth: 900 }}>
            {t.title}
          </h2>
          <p className="lead" style={{ marginTop: 28, maxWidth: 560, marginInline: 'auto' }}>
            {t.lead}
          </p>
          <div style={{ marginTop: 44, display: 'flex', justifyContent: 'center' }}>
            <a href={STRINGS[lang].contact} className="btn btn-primary">
              {t.cta} <span aria-hidden="true">→</span>
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ----------------- Mid-page CTA ----------------- */
function MidCTA({ text }) {
  const lang = detectLang();
  return (
    <section className="cta-banner reveal">
      <div className="container">
        <p className="h2" style={{ fontSize: 'clamp(28px, 3vw, 44px)', margin: 0 }}>
          {text || STRINGS[lang].midCtaDefault}
        </p>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Footer, FinalCTA, MidCTA, useReveal, useHashScroll, toggleHref });
