/* Nexpersona - Nav + Hero */

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

const THEME_KEY = 'nx_theme';
const LANG_KEY = 'nx_lang';

function useTheme() {
  const [theme, setThemeState] = useState(() => {
    if (typeof window === 'undefined') return 'light';
    return localStorage.getItem(THEME_KEY) || 'light';
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem(THEME_KEY, theme);
  }, [theme]);
  const toggle = () => setThemeState(t => (t === 'light' ? 'dark' : 'light'));
  return [theme, toggle];
}

function useLang() {
  const [lang, setLangState] = useState(() => localStorage.getItem(LANG_KEY) || 'EN');
  useEffect(() => {
    localStorage.setItem(LANG_KEY, lang);
    document.documentElement.lang = lang.toLowerCase();
    window.NXLang = lang;
    window.dispatchEvent(new Event('nxlangchange'));
  }, [lang]);
  return [lang, setLangState];
}

function useReveal() {
  useEffect(() => {
    if (typeof IntersectionObserver === 'undefined') return;
    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 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

function ThemeIcon({ theme }) {
  if (theme === 'dark') {
    return (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="4"/>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
      </svg>
    );
  }
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
    </svg>
  );
}

function Nav({ theme, onToggleTheme, lang, onLang, onCTA }) {
  const { t } = window.useT();
  const [scrolled, setScrolled] = useState(false);
  const [langOpen, setLangOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const popRef = useRef(null);

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

  useEffect(() => {
    const onDoc = (e) => {
      if (popRef.current && !popRef.current.contains(e.target)) setLangOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  // Imperatively unlock scroll the instant a link is tapped, so the
  // anchor jump that fires synchronously after the click isn't blocked
  // by a still-locked body.
  const closeMobile = () => {
    setMobileOpen(false);
    document.body.style.overflow = '';
  };

  return (
    <>
    <header className={`nav-wrap ${scrolled ? 'scrolled' : ''} ${mobileOpen ? 'mobile-open' : ''}`}>
      <div className="shell">
        <nav className="nav">
          <a className="brand" href="#top" aria-label="Nexpersona - home" onClick={closeMobile}>
            <span className="logomark" aria-hidden="true">
              <svg viewBox="0 0 32 32" width="28" height="28">
                <rect width="32" height="32" rx="8" fill="var(--accent-alt)"/>
                <path d="M8.6 24.5 L8.6 7.5 L23.4 24.5 L23.4 7.5"
                      stroke="#FAFAF7" strokeWidth="2.4"
                      strokeLinecap="square" strokeLinejoin="miter" fill="none"/>
                <circle cx="23.4" cy="7.5" r="2.3" fill="#E8E5D8"/>
              </svg>
            </span>
            <span className="wordmark">Nex<span className="mark">persona</span></span>
          </a>
          <div className="nav-links" role="navigation">
            <a href="#work">{t('nav.work')}</a>
            <a href="#services">{t('nav.services')}</a>
            <a href="#process">{t('nav.process')}</a>
            <a href="#about">{t('nav.about')}</a>
          </div>
          <div className="nav-actions">
            <div className="lang-pop" ref={popRef}>
              <button className="icon-btn" aria-label={t('nav.lang_aria')} onClick={() => setLangOpen(o => !o)}>
                <span style={{fontFamily:'Geist Mono, monospace', fontSize:11, letterSpacing:'0.08em'}}>{lang}</span>
              </button>
              <div className={`lang-menu ${langOpen ? 'open' : ''}`} role="menu">
                {window.NX_LANGS.map(l => (
                  <button
                    key={l.code}
                    className={lang === l.code ? 'active' : ''}
                    onClick={() => { onLang(l.code); setLangOpen(false); }}
                  >
                    <span>{l.name}</span>
                    <span className="code">{l.code}</span>
                  </button>
                ))}
              </div>
            </div>
            <button className="icon-btn" aria-label={t('nav.theme_aria')} onClick={onToggleTheme}>
              <ThemeIcon theme={theme} />
            </button>
            <button
              className="btn btn-primary btn-sm nav-cta-desktop"
              onClick={() => { closeMobile(); onCTA(); }}
              style={{height: 36}}
            >
              {t('nav.cta')}
              <span className="arrow">→</span>
            </button>
            <button
              className="icon-btn nav-hamburger"
              aria-label="Menu"
              aria-expanded={mobileOpen}
              onClick={() => setMobileOpen(o => !o)}
            >
              {mobileOpen ? (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6l-12 12"/></svg>
              ) : (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
              )}
            </button>
          </div>
        </nav>
      </div>
    </header>

    {/* Drawer is rendered OUTSIDE .nav-wrap on purpose: when nav-wrap
        is scrolled it picks up `backdrop-filter`, which makes it the
        containing block for any `position: fixed` descendant - that
        would clamp the drawer's `bottom: 0` to the nav's own height,
        leaving the drawer ~0px tall and only the first item visible. */}
    <div className={`mobile-drawer ${mobileOpen ? 'open' : ''}`} aria-hidden={!mobileOpen}>
      <a href="#work" onClick={closeMobile}>{t('nav.work')}</a>
      <a href="#services" onClick={closeMobile}>{t('nav.services')}</a>
      <a href="#process" onClick={closeMobile}>{t('nav.process')}</a>
      <a href="#about" onClick={closeMobile}>{t('nav.about')}</a>
      <button className="btn btn-violet btn-cta-hero" onClick={() => { closeMobile(); onCTA(); }}>
        {t('nav.cta')} <span className="arrow">→</span>
      </button>
    </div>

    {/* Scrim - tap outside drawer to close */}
    {mobileOpen && (
      <div className="mobile-scrim" onClick={closeMobile} aria-hidden="true"></div>
    )}
    </>
  );
}

// ---------- Hero animation (loader that evolves through 4 stages)

const HA_SCATTER = [
  [12,14],[28,8],[44,18],[62,10],[82,16],[94,22],
  [6,36],[22,32],[40,38],[58,30],[76,38],[92,32],
  [16,56],[34,52],[52,60],[70,54],[88,58],
  [10,78],[28,84],[46,80],[64,76],[82,84],[94,78],
  [20,104],[56,108],[76,102],[38,98],[90,106],
];
const HA_WAVE = Array.from({length: 12}, (_, i) => [8 + i * 8, 62]);
const HA_GRID = (() => {
  const out = [];
  for (let j = 0; j < 5; j++) for (let i = 0; i < 6; i++) {
    out.push([10 + i * 16, 15 + j * 24]);
  }
  return out;
})();
const HA_N = [
  [24,22],[24,38],[24,54],[24,70],[24,86],[24,102],
  [34.4,38],[44.8,54],[55.2,70],[65.6,86],
  [76,22],[76,38],[76,54],[76,70],[76,86],[76,102],
];

function HeroAnim() {
  const { t } = window.useT();
  return (
    <div className="hero-anim">
      <svg viewBox="0 0 100 125" preserveAspectRatio="xMidYMid meet" className="ha-svg">
        <g className="ha-frame ha-frame-1">
          {HA_SCATTER.map(([x, y], i) => (
            <circle key={i} className={`ha-dot ha-scatter d${i % 4}`}
                    cx={x} cy={y} r="0.9" fill="currentColor"
                    style={{ animationDelay: `${-i * 0.13}s` }}/>
          ))}
        </g>
        <g className="ha-frame ha-frame-2">
          <line x1="6" y1="62" x2="94" y2="62"
                stroke="currentColor" strokeOpacity="0.16" strokeWidth="0.3"
                strokeDasharray="1 2"/>
          {HA_WAVE.map(([x, y], i) => (
            <circle key={i} className="ha-dot ha-wave-dot"
                    cx={x} cy={y} r="1.1" fill="currentColor"
                    style={{ animationDelay: `${-i * 0.16}s` }}/>
          ))}
        </g>
        <g className="ha-frame ha-frame-3">
          {HA_GRID.map(([x, y], i) => (
            <circle key={i} className="ha-dot ha-grid-dot"
                    cx={x} cy={y} r="1" fill="currentColor"
                    style={{ animationDelay: `${-i * 0.04}s` }}/>
          ))}
          <rect className="ha-scan" x="-2" y="6" width="2" height="112"
                fill="var(--accent-alt)" opacity="0.5"/>
        </g>
        <g className="ha-frame ha-frame-4">
          <line x1="24" y1="22" x2="24" y2="102"
                stroke="currentColor" strokeOpacity="0.18" strokeWidth="0.3"/>
          <line x1="76" y1="22" x2="76" y2="102"
                stroke="currentColor" strokeOpacity="0.18" strokeWidth="0.3"/>
          <line x1="24" y1="22" x2="76" y2="102"
                stroke="currentColor" strokeOpacity="0.18" strokeWidth="0.3"/>
          {HA_N.map(([x, y], i) => (
            <circle key={i} className="ha-dot ha-n-dot"
                    cx={x} cy={y} r="1.4" fill="currentColor"
                    style={{ animationDelay: `${-i * 0.06}s` }}/>
          ))}
          <circle cx="76" cy="22" r="2.6" fill="var(--accent-alt)" className="ha-n-accent"/>
        </g>
      </svg>

      <div className="ha-caption">
        {[1,2,3,4].map(n => (
          <span key={n} className={`ha-stage ha-stage-${n}`}>
            <span className="ha-stage-num">{String(n).padStart(2,'0')}</span>
            <span className="ha-stage-name">{t(`hero.stage.${n}`)}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function HeroEditorial({ onCTA }) {
  const { t, tR } = window.useT();
  return (
    <section className="hero shell" id="top">
      <div className="hero-grid">
        <div>
          <div className="hero-eyebrow">
            <span className="pulse"></span>
            <span>{t('hero.eyebrow')}</span>
          </div>
          <h1 className="serif hero-title">
            <span className="word" style={{animationDelay:'.05s'}}>{t('hero.title.line1.a')}</span>{' '}
            <span className="word" style={{animationDelay:'.18s'}}>{t('hero.title.line1.b')}</span>
            <br/>
            <span className="word" style={{animationDelay:'.32s'}}>{t('hero.title.line2.a')}</span>{' '}
            <span className="word em" style={{animationDelay:'.45s'}}>{t('hero.title.line2.b')}</span>
          </h1>
          <p className="hero-sub">{t('hero.sub')}</p>
          <div className="hero-ctas">
            <button className="btn btn-violet btn-cta-hero" onClick={onCTA}>
              {t('hero.cta.explore')} <span className="arrow">→</span>
            </button>
            <a className="btn btn-ghost" href="#process">{t('hero.cta.process')}</a>
          </div>
          <div className="hero-meta">
            <div className="item">
              <span className="k">{t('hero.meta.inhouse.k')}</span>
              <span className="v serif">{tR('hero.meta.inhouse.v')}</span>
            </div>
            <div className="item">
              <span className="k">{t('hero.meta.based.k')}</span>
              <span className="v serif">{t('hero.meta.based.v')}</span>
            </div>
            <div className="item">
              <span className="k">{t('hero.meta.avg.k')}</span>
              <span className="v serif">{tR('hero.meta.avg.v')}</span>
            </div>
          </div>
        </div>

        <div className="hero-figure" aria-hidden="false">
          <HeroAnim />
        </div>
      </div>
    </section>
  );
}

function HeroTypeOnly({ onCTA }) {
  const { t, tR } = window.useT();
  return (
    <section className="hero shell" id="top" style={{paddingTop: 140}}>
      <div className="eyebrow-row">
        <span className="mono">FIG. 01 - HERO / TYPEFORWARD</span>
        <span className="line"></span>
      </div>
      <h1 className="serif hero-typeonly">{tR('hero.typeonly.title')}</h1>
      <p className="hero-sub" style={{maxWidth: 640, fontSize: 22}}>{t('hero.sub.short')}</p>
      <div className="hero-ctas">
        <button className="btn btn-violet btn-cta-hero" onClick={onCTA}>
          {t('hero.cta.explore')} <span className="arrow">→</span>
        </button>
        <a className="btn btn-ghost" href="#process">{t('hero.cta.process')}</a>
      </div>
    </section>
  );
}

function HeroGlow({ onCTA }) {
  const { t, tR } = window.useT();
  return (
    <section className="hero shell hero-glow" id="top">
      <div className="hero-eyebrow" style={{marginLeft:'auto', marginRight:'auto'}}>
        <span className="pulse"></span>
        <span>{t('hero.glow.eyebrow')}</span>
      </div>
      <h1 className="serif hero-title" style={{textAlign:'center'}}>{tR('hero.glow.title')}</h1>
      <p className="hero-sub" style={{marginLeft:'auto', marginRight:'auto', textAlign:'center'}}>{t('hero.sub.short')}</p>
      <div className="hero-ctas" style={{justifyContent:'center'}}>
        <button className="btn btn-violet" onClick={onCTA}>
          {t('hero.cta.explore')} <span className="arrow">→</span>
        </button>
        <a className="btn btn-ghost" href="#process">{t('hero.cta.process')}</a>
      </div>
    </section>
  );
}

function Hero({ variant, onCTA }) {
  if (variant === 'typeonly') return <HeroTypeOnly onCTA={onCTA} />;
  if (variant === 'glow') return <HeroGlow onCTA={onCTA} />;
  return <HeroEditorial onCTA={onCTA} />;
}

function LangBanner({ lang, onAccept, onDismiss }) {
  const { t, tR } = window.useT();
  const detected = useMemo(() => {
    const b = (navigator.language || 'en').toUpperCase().slice(0, 2);
    if (window.NX_LANGS.some(l => l.code === b)) return b;
    return null;
  }, []);
  if (!detected || detected === lang) return null;
  const matched = window.NX_LANGS.find(l => l.code === detected);
  return (
    <div className="lang-banner" role="status">
      <span>{tR('banner.text', { lang: matched.name })}</span>
      <button className="switch" onClick={() => onAccept(detected)}>{t('banner.switch')}</button>
      <button className="dismiss" onClick={onDismiss} aria-label={t('banner.dismiss')}>×</button>
    </div>
  );
}

function CursorAccent() {
  const ref = useRef(null);
  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    if (window.matchMedia('(pointer: coarse)').matches) return;
    const el = ref.current;
    let raf = null;
    let x = -9999, y = -9999, tx = -9999, ty = -9999;
    const onMove = (e) => {
      tx = e.clientX; ty = e.clientY;
      el.style.opacity = '1';
      if (!raf) raf = requestAnimationFrame(loop);
    };
    const loop = () => {
      x += (tx - x) * 0.12;
      y += (ty - y) * 0.12;
      el.style.transform = `translate3d(${x - 280}px, ${y - 280}px, 0)`;
      if (Math.abs(tx - x) > 0.5 || Math.abs(ty - y) > 0.5) {
        raf = requestAnimationFrame(loop);
      } else { raf = null; }
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  return <div className="cursor-accent" ref={ref} aria-hidden="true"></div>;
}

window.NXNav = Nav;
window.NXHero = Hero;
window.NXLangBanner = LangBanner;
window.NXCursorAccent = CursorAccent;
window.useTheme = useTheme;
window.useLang = useLang;
window.useReveal = useReveal;
