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

function LangToggle() {
  const { lang, setLang } = window.useLang();
  const options = [
    { code: 'ar', label: 'AR' },
    { code: 'en', label: 'EN' },
  ];
  return (
    <div
      role="group"
      aria-label="Language selector"
      style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}
    >
      {options.map((opt, i) => (
        <React.Fragment key={opt.code}>
          <button
            type="button"
            onClick={() => setLang(opt.code)}
            aria-label={`Switch language to ${opt.label}`}
            aria-pressed={lang === opt.code}
            style={{
              fontFamily: 'var(--font-display)',
              fontSize: 11,
              fontWeight: lang === opt.code ? 600 : 400,
              letterSpacing: '0.12em',
              textTransform: 'uppercase',
              color: lang === opt.code ? '#0047ff' : 'var(--text-dim)',
              background: 'transparent',
              border: 'none',
              padding: 0,
              cursor: 'pointer',
              transition: 'color 150ms',
            }}
            onMouseEnter={(e) => { if (lang !== opt.code) e.currentTarget.style.color = 'var(--text-secondary)'; }}
            onMouseLeave={(e) => { if (lang !== opt.code) e.currentTarget.style.color = 'var(--text-dim)'; }}
          >
            {opt.label}
          </button>
          {i < options.length - 1 && (
            <span aria-hidden="true" style={{ color: 'var(--border-strong)', userSelect: 'none', fontSize: 11 }}>·</span>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

function NavBar() {
  const [scrolled,  setScrolled]  = useState(false);
  const [menuOpen,  setMenuOpen]  = useState(false);
  const [hideNav,   setHideNav]   = useState(false);
  const lastScrollY = useRef(0);

  /* Scroll: frosted glass + hide-on-scroll-down */
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 20);
      if (!menuOpen) {
        const delta = y - lastScrollY.current;
        if (Math.abs(delta) > 6) {
          setHideNav(delta > 0 && y > 120);
        }
      }
      lastScrollY.current = y;
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [menuOpen]);

  /* Body scroll lock when menu open */
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  /* Escape key closes menu */
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const { theme } = window.useTheme();
  const ThemeToggle = window.ThemeToggle;
  const t = window.useCopy();
  const links = [
    { label: t.nav.cases,    href: '#sila-case' },
    { label: t.nav.services, href: '#tier-1'    },
    { label: t.nav.doctrine, href: '#doctrine'  },
    { label: t.nav.contact,  href: '#final-cta' },
  ];

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

  const bgSolid   = theme === 'light' ? 'rgba(255,255,255,0.97)' : 'rgba(9,9,11,0.97)';
  const bgScrolled = theme === 'light' ? 'rgba(255,255,255,0.90)' : 'rgba(9,9,11,0.88)';

  const WA = ({ size = 15 }) => (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" style={{ flex:'none' }}>
      <path d="M17.5 14.4c-.3-.1-1.7-.9-2-1-.3-.1-.5-.1-.7.1-.2.3-.8 1-1 1.2-.2.2-.4.2-.7.1-.3-.1-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6l.5-.5c.2-.2.2-.3.3-.5 0-.2 0-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.4 0 1.4 1 2.8 1.2 3 .1.2 2 3 4.7 4.2 1.7.7 2.3.8 3.1.7.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.3.2-1.4-.1-.1-.3-.2-.5-.2zM12 2C6.5 2 2 6.5 2 12c0 1.9.5 3.7 1.5 5.3L2 22l4.8-1.5c1.5.8 3.3 1.3 5.2 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
    </svg>
  );

  return (
    <>
      {/* ── Header bar ── */}
      <header
        className={`navbar${hideNav && !menuOpen ? ' navbar--hidden' : ''}`}
        style={{
          position: 'sticky', top: 0, zIndex: 1000,
          height: scrolled ? 64 : 80,
          background: menuOpen ? bgSolid : scrolled ? bgScrolled : 'transparent',
          backdropFilter:       scrolled || menuOpen ? 'blur(12px)' : 'none',
          WebkitBackdropFilter: scrolled || menuOpen ? 'blur(12px)' : 'none',
          borderBottom: scrolled ? '1px solid var(--border-subtle)' : '1px solid transparent',
          transition: 'height 300ms var(--ease-out), background 300ms var(--ease-out), border-color 300ms var(--ease-out)',
        }}
      >
        <div
          className="nav-inner"
          style={{
            maxWidth: 1280, height: '100%', margin: '0 auto', padding: '0 40px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 32,
          }}
        >
          {/* Logo */}
          <a href="#hero" onClick={closeMenu} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none', flexShrink: 0 }}>
            <svg viewBox="0 0 96 96" width={24} height={24} style={{ flex:'none' }}>
              <path d="M68 18 L32 48 L68 78 L60 78 L24 48 L60 18 Z" style={{ fill: 'var(--text-primary)' }}/>
            </svg>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17, color: 'var(--text-primary)', letterSpacing: '-0.01em' }}>
              BoldBrandz
            </span>
          </a>

          {/* Desktop center nav */}
          <nav className="nav-links" style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
            {links.map(l => (
              <a key={l.href} href={l.href} style={{
                fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500,
                color: 'var(--text-secondary)', textDecoration: 'none', transition: 'color 180ms',
              }}
                onMouseEnter={(e) => e.currentTarget.style.color = '#0047ff'}
                onMouseLeave={(e)  => e.currentTarget.style.color = 'var(--text-secondary)'}
              >{l.label}</a>
            ))}
          </nav>

          {/* Right cluster */}
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 16, flexShrink: 0 }}>

            {/* Desktop-only controls */}
            <div className="nav-desktop-controls" style={{ display: 'inline-flex', alignItems: 'center', gap: 16 }}>
              <LangToggle />
              <ThemeToggle />
              <a
                href="https://wa.me/972534200984?text=Hi%20BoldBrandz%2C%20I%27d%20like%20to%20book%20a%20strategy%20call"
                target="_blank" rel="noopener noreferrer"
                data-gtm-event="Lead_WhatsApp_NavBarCTA"
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  padding: '10px 18px', fontSize: 13, fontWeight: 600,
                  fontFamily: 'var(--font-display)',
                  background: '#0047ff', color: '#fff',
                  borderRadius: 9, textDecoration: 'none',
                  boxShadow: '0 0 18px var(--accent-primary-glow)',
                  transition: 'background 180ms, box-shadow 180ms',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.background = '#0035cc'; e.currentTarget.style.boxShadow = '0 0 28px rgba(0,71,255,0.55)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = '#0047ff'; e.currentTarget.style.boxShadow = '0 0 18px var(--accent-primary-glow)'; }}
              >
                <WA size={14}/> {t.nav.cta}
              </a>
            </div>

            {/* Hamburger — shown on mobile via CSS */}
            <button
              className="nav-hamburger"
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label={menuOpen ? 'Close menu' : 'Open menu'}
              aria-expanded={menuOpen}
              style={{
                display: 'none',            /* CSS shows it on mobile */
                alignItems: 'center', justifyContent: 'center',
                width: 44, height: 44,
                background: 'transparent', border: 'none', cursor: 'pointer',
                padding: 0, color: 'var(--text-primary)', flexShrink: 0,
              }}
            >
              {menuOpen
                ? <svg viewBox="0 0 24 24" width={22} height={22} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
                : <svg viewBox="0 0 24 24" width={22} height={22} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M3 12h18M3 6h18M3 18h18"/></svg>
              }
            </button>
          </div>
        </div>
      </header>

      {/* ── Mobile fullscreen overlay ── */}
      {menuOpen && (
        <div
          className="nav-overlay"
          style={{
            position: 'fixed', top: 60, left: 0, right: 0, bottom: 0,
            zIndex: 999,
            background: bgSolid,
            backdropFilter: 'blur(16px)',
            WebkitBackdropFilter: 'blur(16px)',
            display: 'flex', flexDirection: 'column',
            padding: '32px 24px 48px',
            overflowY: 'auto',
          }}
        >
          {/* Nav links */}
          <nav style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
            {links.map((l, i) => (
              <a key={l.href} href={l.href} onClick={closeMenu}
                style={{
                  fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 600,
                  color: 'var(--text-primary)', textDecoration: 'none',
                  letterSpacing: '-0.025em', lineHeight: 1,
                  padding: '18px 0',
                  borderBottom: '1px solid var(--border-subtle)',
                  transition: 'color 160ms',
                  opacity: 0,
                  animation: `beat-in 280ms var(--ease-out) ${i * 50}ms forwards`,
                }}
                onMouseEnter={(e) => e.currentTarget.style.color = '#0047ff'}
                onMouseLeave={(e) => e.currentTarget.style.color = 'var(--text-primary)'}
              >{l.label}</a>
            ))}
          </nav>

          {/* Bottom controls */}
          <div style={{ marginTop: 36, display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
              <LangToggle />
              <ThemeToggle />
            </div>
            <a
              href="https://wa.me/972534200984?text=Hi%20BoldBrandz%2C%20I%27d%20like%20to%20book%20a%20strategy%20call"
              target="_blank" rel="noopener noreferrer"
              data-gtm-event="Lead_WhatsApp_NavBarCTA_Mobile"
              onClick={closeMenu}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
                padding: '18px 0', fontSize: 17, fontWeight: 600,
                fontFamily: 'var(--font-display)',
                background: '#0047ff', color: '#fff',
                borderRadius: 12, textDecoration: 'none',
                boxShadow: '0 0 28px rgba(0,71,255,0.4)',
              }}
            >
              <WA size={18}/> {t.nav.cta}
            </a>
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { NavBar, LangToggle });
