/* ============================================================
   CHAINUS — Nav + Hero (asymmetric, cinematic) + live ticker
   ============================================================ */

function Nav({ t, theme, onToggleTheme }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const go = (id) => (e) => {
    e.preventDefault();
    setOpen(false);
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 78, behavior: reduceMotion() ? 'auto' : 'smooth' });
  };
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="nav-logo" onClick={go('top')}><Logo /></a>
        <div className="nav-mid glass">
          {t.nav.links.map((l) => (
            <a key={l.id} href={`#${l.id}`} className="nav-link" onClick={go(l.id)}>{l.label}</a>
          ))}
        </div>
        <div className="nav-cta">
          <ThemeToggle theme={theme} onToggle={onToggleTheme} />
          <MagneticButton className="btn btn-primary btn-sm hide-mobile" onClick={go('download')}>{t.nav.cta}</MagneticButton>
          <button className={`nav-burger show-mobile ${open ? 'on' : ''}`} onClick={() => setOpen(!open)} aria-label="Menu"><span></span><span></span></button>
        </div>
      </div>
      <div className={`nav-sheet ${open ? 'open' : ''}`}>
        {t.nav.links.map((l) => <a key={l.id} href={`#${l.id}`} className="nav-sheet-link" onClick={go(l.id)}>{l.label}</a>)}
        <MagneticButton className="btn btn-primary" onClick={go('download')}>{t.nav.cta}<ArrowIcon /></MagneticButton>
      </div>
    </nav>
  );
}

/* native live market mini-card (used in hero composition) */
function HeroMarketCard({ t }) {
  const d = [58,60,59,62,61,64,63,66,65,68,67,71];
  return (
    <div className="hm-card card card-hi">
      <div className="hm-top">
        <div className="hm-coin">
          <span className="hm-mark">₿</span>
          <div>
            <b className="hm-sym">{t.hero.cardCoin}<span className="faint"> · Bitcoin</span></b>
            <span className="hm-live tag"><span className="chip-dot" style={{ animation: 'pulse-dot 1.6s infinite' }}></span>Live</span>
          </div>
        </div>
        <span className="hm-chg pos tnum">▲ {t.hero.cardCoinChg}</span>
      </div>
      <div className="hm-price"><LiveNumber value={71204} prefix="$" live /></div>
      <div className="hm-spark"><Sparkline data={d} color="var(--up)" w={180} h={46} strokeW={2.4} id="hmspark" /></div>
      <div className="hm-foot">
        <span className="tag">24h Vol <b className="tnum">$28.4B</b></span>
        <span className="tag">{t.hero.cardMood} <b className="brand-text">{t.hero.cardMoodVal}</b></span>
      </div>
    </div>
  );
}

function Hero({ t }) {
  const heroRef = useRef(null);
  const openWebApp = () => { window.location.href = 'https://app.chainus.org'; };

  useEffect(() => {
    const el = heroRef.current;
    if (!el) return;
    const video = el.querySelector('.hero-video-player');
    let wasReady = false;
    const setProgress = () => {
      const wantsReduced = reduceMotion();
      let ready = false;
      if (wantsReduced) {
        el.style.setProperty('--hero-scroll', '1');
        ready = true;
      } else {
        const rect = el.getBoundingClientRect();
        const range = Math.max(1, rect.height - window.innerHeight);
        const p = Math.min(1, Math.max(0, -rect.top / range));
        el.style.setProperty('--hero-scroll', p.toFixed(3));
        ready = p > 0.56;
      }
      el.dataset.videoReady = ready ? 'true' : 'false';
      if (video && ready !== wasReady) {
        if (ready && !wantsReduced) {
          video.currentTime = 0;
          video.play().catch(() => {});
        } else {
          if (ready) video.currentTime = 0;
          video.pause();
        }
      }
      wasReady = ready;
    };
    setProgress();
    window.addEventListener('scroll', setProgress, { passive: true });
    window.addEventListener('resize', setProgress);
    return () => {
      window.removeEventListener('scroll', setProgress);
      window.removeEventListener('resize', setProgress);
    };
  }, []);

  return (
    <header ref={heroRef} className="hero hero-scroll" id="top">
      <div className="aurora grain"></div>
      <div className="wrap hero-inner">
        <div className="hero-copy">
          <h1 className="display hero-title" aria-label={`${t.hero.title[0]} ${t.hero.title[1]}`}>
            <Reveal as="span" className="hero-title-l1" delay={80} aria-hidden="true">{t.hero.title[0]} </Reveal>
            <Reveal as="span" className="ink-grad hero-title-l2" delay={180} aria-hidden="true">{t.hero.title[1]}</Reveal>
          </h1>
          <Reveal className="lead hero-sub" delay={320}>{t.hero.sub}</Reveal>
          <Reveal delay={420} className="hero-cta">
            <MascotDownload label={t.hero.ctaPrimary} t={t} />
            <button className="btn btn-ghost" onClick={openWebApp}>{t.hero.ctaSecondary}<ArrowIcon /></button>
          </Reveal>
        </div>

        <Reveal scale delay={240} className="hero-stage">
          <div className="hero-web">
            <DesktopFrame slotId="hero-web" placeholder={t.dir === 'zh' ? '官网 · 社区首页' : 'Website · community home'} url="chainus.org" ratio="16 / 10" />
            <HeroVideoTeaser t={t} />
          </div>
        </Reveal>
      </div>
    </header>
  );
}

function HeroVideoTeaser({ t }) {
  return (
    <div className="hero-video" aria-label={t.dir === 'zh' ? '自动播放产品预览' : 'Autoplay product preview'}>
      <video
        className="hero-video-player"
        src="assets/v3/chainus-v3-demo.mp4?v=real-v3-clicks-slow-003"
        poster="assets/v3/overview-page-desktop.png"
        muted
        loop
        playsInline
        preload="auto"
      />
    </div>
  );
}

Object.assign(window, { Nav, Hero, HeroVideoTeaser });
