// sections.jsx — all landing page sections.
// Reads T (data), Icon, DragonMark, Terminal from window.

const { useState, useEffect, useRef } = React;

// ─── Reveal hook ─────────────────────────────────────────────────────────
// Adds .in class when element enters viewport. One-shot.
// Includes a safety fallback: if the IO doesn't fire within ~600ms after the
// element is on-screen, just reveal it. Some embedded iframe contexts choke
// on IO entirely; we'd rather show content than hide it forever.
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const targets = Array.from(ref.current.querySelectorAll('.reveal'));
    if (!targets.length) return;

    // Opt this section into "reveal-on-scroll" mode. The styles only set
    // opacity:0 when the parent has data-reveal-on="1" — so anything that
    // never reaches this branch (no JS, no IO support) stays visible.
    ref.current.setAttribute('data-reveal-on', '1');

    const revealIfInView = () => {
      targets.forEach((el) => {
        if (el.classList.contains('in')) return;
        const r = el.getBoundingClientRect();
        if (r.top < window.innerHeight - 20 && r.bottom > 0) {
          el.classList.add('in');
        }
      });
    };

    // Run on next frame so the browser registers the opacity:0 transition
    // origin before we flip to .in (otherwise it snaps without animating).
    const raf = requestAnimationFrame(() => requestAnimationFrame(revealIfInView));

    let io;
    try {
      io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) {
              e.target.classList.add('in');
              io.unobserve(e.target);
            }
          });
        },
        { threshold: 0.05, rootMargin: '0px 0px -40px 0px' }
      );
      targets.forEach((el) => io.observe(el));
    } catch (err) {}

    const onScroll = () => revealIfInView();
    window.addEventListener('scroll', onScroll, { passive: true });

    return () => {
      cancelAnimationFrame(raf);
      if (io) io.disconnect();
      window.removeEventListener('scroll', onScroll);
    };
  }, []);
  return ref;
}

// Pick localized string {en, vi} | string
function pick(s, lang) {
  if (s == null) return '';
  if (typeof s === 'string') return s;
  return s[lang] ?? s.en ?? '';
}

// ─── Nav ─────────────────────────────────────────────────────────────────
function Nav({ lang, setLang, theme, setTheme }) {
  const isDark = theme === 'dark';
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#top" className="brand">
          <svg viewBox="0 0 32 32" fill="none">
            <defs>
              <linearGradient id="navg" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#9bffaf" />
                <stop offset="100%" stopColor="#00b82e" />
              </linearGradient>
            </defs>
            <polygon points="6,18 14,8 22,8 28,14 22,16 14,12 8,22" fill="url(#navg)" />
            <polygon points="16,8 17,2 20,9" fill="url(#navg)" />
            <polygon points="11,11 13,5 14,12" fill="url(#navg)" />
            <circle cx="20" cy="12" r="1.2" fill="#050706" />
          </svg>
          <b>KALI</b><small>// linux</small>
        </a>
        <div className="nav-links">
          {T.nav.map((n) => (
            <a key={n.id} href={`#${n.id}`}>{pick(n, lang)}</a>
          ))}
        </div>
        <div className="nav-right">
          <button
            className="theme-toggle"
            title={isDark ? (lang === 'vi' ? 'Chuyển sang Light mode' : 'Switch to Light mode')
                          : (lang === 'vi' ? 'Chuyển sang Dark mode' : 'Switch to Dark mode')}
            aria-label="Toggle theme"
            onClick={() => setTheme(isDark ? 'light' : 'dark')}
          >
            {isDark ? (
              /* Sun icon — shown in dark mode (click to go light) */
              <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
                <circle cx="12" cy="12" r="4" />
                <path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.5 4.5l2.1 2.1M17.4 17.4l2.1 2.1M4.5 19.5l2.1-2.1M17.4 6.6l2.1-2.1" />
              </svg>
            ) : (
              /* Moon icon — shown in light mode (click to go dark) */
              <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z" />
              </svg>
            )}
            <span className="theme-toggle-label">{isDark ? 'LIGHT' : 'DARK'}</span>
          </button>
          <div className="lang-switch" role="tablist">
            <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
            <button className={lang === 'vi' ? 'on' : ''} onClick={() => setLang('vi')}>VI</button>
          </div>
          <a href="#install" className="btn primary" style={{ padding: '8px 14px', fontSize: 12 }}>
            ./download.sh
          </a>
        </div>
      </div>
    </nav>
  );
}

// ─── Hero ────────────────────────────────────────────────────────────────
// Hero terminal — a "boot" sequence with whoami/uname/ls
function HeroTerminal({ lang }) {
  const scenes = [
    {
      path: '~',
      cmd: 'whoami && uname -a',
      output: [
        { text: 'root', cls: 'term-ok' },
        { text: 'Linux kali 6.12.0-kali1-amd64 #1 SMP Debian 6.12.0-1kali1 (2026-02-04) x86_64 GNU/Linux', cls: 'term-out' },
      ],
    },
    {
      path: '~',
      cmd: 'sudo apt list --installed | grep -c .',
      output: [
        { text: '4,182', cls: 'term-ok' },
        { text: lang === 'vi' ? '# 600+ là số đếm thủ công những tool mặc định trong meta-packages' : '# 600+ is the hand-curated count from kali-linux-default meta-package', cls: 'term-out' },
      ],
    },
    {
      path: '/opt/lab',
      cmd: 'nmap -sV --top-ports 50 scanme.nmap.org',
      output: [
        { text: 'Starting Nmap 7.95 ( https://nmap.org ) at 2026-05-27 03:14 UTC', cls: 'term-out' },
        { text: 'Nmap scan report for scanme.nmap.org (45.33.32.156)', cls: 'term-out' },
        { text: 'Host is up (0.012s latency).', cls: 'term-out' },
        { text: 'PORT    STATE SERVICE  VERSION', cls: 'term-out' },
        { text: '22/tcp  open  ssh      OpenSSH 6.6.1p1', cls: 'term-ok' },
        { text: '80/tcp  open  http     Apache httpd 2.4.7', cls: 'term-ok' },
        { text: '9929/tcp open nping-echo Nping echo', cls: 'term-ok' },
        { text: 'Nmap done: 1 IP address (1 host up) scanned in 6.21s', cls: 'term-ok' },
      ],
    },
    {
      path: '~',
      cmd: 'echo "the quieter you become, the more you are able to hear."',
      output: [
        { text: 'the quieter you become, the more you are able to hear.', cls: 'term-ok' },
      ],
    },
  ];
  return <Terminal scenes={scenes} title="root@kali:~ — bash" />;
}

function Hero({ lang }) {
  const ref = useReveal();
  return (
    <section className="hero wrap" id="top" ref={ref}>
      <div className="hero-grid">
        <div className="reveal">
          <div className="hero-eyebrow">{pick(T.hero.eyebrow, lang)}</div>
          <h1>
            <span>{pick(T.hero.line1, lang)}</span>
            <br />
            <span className="grad">{pick(T.hero.line2, lang)}</span>
            <br />
            <span>{pick(T.hero.line3, lang)}<span className="cursor" /></span>
          </h1>
          <p className="hero-lead">
            <span className={lang === 'vi' ? 'vn' : ''}>{pick(T.hero.lead, lang)}</span>
          </p>
          <div className="hero-cta">
            <a className="btn primary" href="#install">
              {pick(T.hero.primary, lang)}
              <span className="arrow">→</span>
            </a>
            <a className="btn" href="#tools">
              <span style={{ color: 'var(--neon)' }}>$</span> {pick(T.hero.secondary, lang)}
            </a>
          </div>
          <div className="hero-meta">
            {T.hero.meta.map((m) => (
              <div key={m.k}>
                <div style={{ color: 'var(--txt-mute)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>{m.k}</div>
                <div><b>{m.v}</b> <span className="mute" style={{ fontSize: 11 }}>{pick(m.sub, lang)}</span></div>
              </div>
            ))}
          </div>
        </div>
        <div className="reveal d1" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="dragon-stage" style={{ aspectRatio: 'auto', height: 'auto', marginBottom: -8 }}>
            <DragonMark size={360} />
          </div>
          <HeroTerminal lang={lang} />
        </div>
      </div>
    </section>
  );
}

// ─── Stats ───────────────────────────────────────────────────────────────
function StatsBar({ lang }) {
  const ref = useReveal();
  return (
    <section className="wrap" ref={ref} style={{ paddingTop: 12 }}>
      <div className="stats reveal">
        {T.stats.map((s, i) => (
          <div className="stat" key={i}>
            <div className="stat-num">{s.num}<span className="unit">{s.unit}</span></div>
            <div className="stat-label">{pick(s.label, lang)}</div>
            <div className="stat-sub">{pick(s.sub, lang)}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Features ────────────────────────────────────────────────────────────
function Features({ lang }) {
  const ref = useReveal();
  return (
    <section className="section wrap" id="features" data-screen-label="features" ref={ref}>
      <div className="reveal">
        <span className="section-tag">// {lang === 'vi' ? 'TÍNH NĂNG' : 'FEATURES'}</span>
        <h2 className="section-title">
          {lang === 'vi' ? 'Sáu thứ ' : 'Six things that '}
          <em>{lang === 'vi' ? 'làm nên Kali.' : 'make Kali, Kali.'}</em>
        </h2>
        <p className="section-sub">
          {lang === 'vi'
            ? 'Không phải distro Linux nào cũng phù hợp pentest. Đây là sáu lý do Kali là tiêu chuẩn ngành.'
            : 'Not every Linux distro is right for offensive work. Here are six reasons Kali is the industry standard.'}
        </p>
      </div>
      <div className="features reveal d1">
        {T.features.map((f, i) => (
          <div className="feature" key={f.id}>
            <div className="feature-id">[<span className="neon">{f.id}</span>] {lang === 'vi' ? 'TÍNH NĂNG' : 'FEATURE'}</div>
            <div className="feature-icon"><Icon name={f.icon} size={36} /></div>
            <h3>
              {pick(f.title, lang)}
              {lang === 'vi' && f.title.en && <span className="vn">{f.title.en}</span>}
              {lang === 'en' && <span className="vn">{f.title.vi}</span>}
            </h3>
            <p>{pick(f.desc, lang)}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Tools showcase ──────────────────────────────────────────────────────
function ToolsShowcase({ lang }) {
  const [activeId, setActiveId] = useState(T.tools[0].id);
  const ref = useReveal();
  const active = T.tools.find((t) => t.id === activeId) || T.tools[0];
  return (
    <section className="section wrap" id="tools" data-screen-label="tools" ref={ref}>
      <div className="reveal">
        <span className="section-tag">{pick(T.toolsHeader.tag, lang)}</span>
        <h2 className="section-title">
          {pick(T.toolsHeader.title, lang)}
          <em>{pick(T.toolsHeader.titleEm, lang)}</em>
        </h2>
        <p className="section-sub">{pick(T.toolsHeader.sub, lang)}</p>
      </div>
      <div className="tools-grid reveal d1">
        <div className="tools-list">
          {T.tools.map((tool, i) => (
            <div
              key={tool.id}
              className={`tool-row ${tool.id === activeId ? 'active' : ''}`}
              onClick={() => setActiveId(tool.id)}
              onMouseEnter={() => setActiveId(tool.id)}
            >
              <span className="idx">{String(i + 1).padStart(2, '0')}</span>
              <span className="name">{tool.name}</span>
              <span className="cat">{tool.category}</span>
            </div>
          ))}
        </div>
        <div className="tool-detail">
          <div className="tool-header">
            <div>
              <h3>{active.name}</h3>
              <div className="tagline">{pick(active.tagline, lang)}</div>
            </div>
            <div className="meta">
              <div>VERSION</div>
              <b>{active.version}</b>
              <div style={{ marginTop: 8 }}>{active.category.toUpperCase()}</div>
            </div>
          </div>
          <Terminal
            key={active.id}
            scenes={active.scenes}
            title={`${active.name} — bash`}
          />
        </div>
      </div>
    </section>
  );
}

// ─── Use Cases ───────────────────────────────────────────────────────────
function UseCases({ lang }) {
  const ref = useReveal();
  return (
    <section className="section wrap" id="usecases" data-screen-label="usecases" ref={ref}>
      <div className="reveal">
        <span className="section-tag">{pick(T.usecasesHeader.tag, lang)}</span>
        <h2 className="section-title">
          {pick(T.usecasesHeader.title, lang)}
          <em>{pick(T.usecasesHeader.titleEm, lang)}</em>
        </h2>
        <p className="section-sub">{pick(T.usecasesHeader.sub, lang)}</p>
      </div>
      <div className="usecases reveal d1">
        {T.usecases.map((u, i) => (
          <div className="usecase" key={u.id}>
            <div className="usecase-id">[ CASE_{String(i + 1).padStart(2, '0')} ] / {u.id.toUpperCase()}</div>
            <h3>
              {pick(u.title, lang)}
              <span className="vn">{lang === 'vi' ? u.title.en : u.title.vi}</span>
            </h3>
            <p>{pick(u.desc, lang)}</p>
            <div className="usecase-tools">
              {u.tools.map((t) => <span key={t}>{t}</span>)}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Install ─────────────────────────────────────────────────────────────
const INSTALL_ICONS = {
  baremetal: 'metal',
  vm: 'vm',
  wsl: 'wsl',
  docker: 'docker',
  liveusb: 'usb',
  cloud: 'cloud',
  arm: 'pi',
  nethunter: 'phone',
};

function Install({ lang }) {
  const ref = useReveal();
  return (
    <section className="section wrap" id="install" data-screen-label="install" ref={ref}>
      <div className="reveal">
        <span className="section-tag">{pick(T.installHeader.tag, lang)}</span>
        <h2 className="section-title">
          {pick(T.installHeader.title, lang)}
          <em>{pick(T.installHeader.titleEm, lang)}</em>
        </h2>
        <p className="section-sub">{pick(T.installHeader.sub, lang)}</p>
      </div>
      <div className="install-grid reveal d1">
        {T.installs.map((i) => (
          <div className="install-card" key={i.id}>
            <div className="install-icon"><Icon name={INSTALL_ICONS[i.id] || 'free'} size={32} /></div>
            <h4>
              {lang === 'vi' ? i.vi : i.title}
              <div className="vn">{lang === 'vi' ? i.title : i.vi}</div>
            </h4>
            <p>{pick(i.desc, lang)}</p>
            <div className="meta">
              <span>{i.arch}</span>
              <b>{i.size}</b>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── Community / Certifications ──────────────────────────────────────────
function Community({ lang }) {
  const ref = useReveal();
  return (
    <section className="section wrap" id="docs" data-screen-label="community" ref={ref}>
      <div className="reveal">
        <span className="section-tag">{pick(T.communityHeader.tag, lang)}</span>
        <h2 className="section-title">
          {pick(T.communityHeader.title, lang)}
          <em>{pick(T.communityHeader.titleEm, lang)}</em>
        </h2>
        <p className="section-sub">{pick(T.communityHeader.sub, lang)}</p>
      </div>
      <div className="community reveal d1">
        <div className="community-block">
          <h3>
            {lang === 'vi' ? 'Chứng chỉ chính thức' : 'Official Certifications'}
            <span className="vn">{lang === 'vi' ? 'Official Certifications' : 'Chứng chỉ chính thức'}</span>
          </h3>
          <ul className="community-list">
            {T.certs.map((c) => (
              <li key={c.badge}>
                <span className="badge">{c.badge}</span>
                <span className="label">{pick(c.label, lang)}</span>
                <span className="meta">{pick(c.meta, lang)}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="community-block">
          <h3>
            {lang === 'vi' ? 'Tài liệu & Cộng đồng' : 'Docs & Community'}
            <span className="vn">{lang === 'vi' ? 'Docs & Community' : 'Tài liệu & Cộng đồng'}</span>
          </h3>
          <ul className="community-list">
            {T.communityResources.map((c) => (
              <li key={c.badge}>
                <span className="badge">{c.badge}</span>
                <span className="label">{pick(c.label, lang)}</span>
                <span className="meta">{pick(c.meta, lang)}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ─── Testimonials ────────────────────────────────────────────────────────
function Testimonials({ lang }) {
  const ref = useReveal();
  return (
    <section className="section wrap" data-screen-label="testimonials" ref={ref}>
      <div className="reveal">
        <span className="section-tag">{pick(T.testimonialsHeader.tag, lang)}</span>
        <h2 className="section-title">
          {pick(T.testimonialsHeader.title, lang)}
          <em>{pick(T.testimonialsHeader.titleEm, lang)}</em>
        </h2>
      </div>
      <div className="testimonials reveal d1">
        {T.testimonials.map((t, i) => (
          <div className="testimonial" key={i}>
            <p className="testimonial-quote">{pick(t.quote, lang)}</p>
            <div className="testimonial-author">
              <div className="avatar">{t.initial}</div>
              <div>
                <b>{t.name}</b>
                <small>{pick(t.role, lang)}</small>
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── FAQ ─────────────────────────────────────────────────────────────────
function FAQ({ lang }) {
  const [openIdx, setOpenIdx] = useState(0);
  const ref = useReveal();
  return (
    <section className="section wrap" id="faq" data-screen-label="faq" ref={ref}>
      <div className="reveal">
        <span className="section-tag">{pick(T.faqHeader.tag, lang)}</span>
        <h2 className="section-title">{pick(T.faqHeader.title, lang)}</h2>
      </div>
      <div className="faq reveal d1">
        {T.faqs.map((f, i) => {
          const isOpen = openIdx === i;
          return (
            <div className={`faq-item ${isOpen ? 'open' : ''}`} key={i} onClick={() => setOpenIdx(isOpen ? -1 : i)}>
              <div className="faq-q">
                <span className="num">Q.{String(i + 1).padStart(2, '0')}</span>
                <span>{pick(f.q, lang)}</span>
                <span className="arrow">▸</span>
              </div>
              <div className="faq-a">
                {pick(f.a, lang)}
                <span className="vn">{lang === 'vi' ? f.a.en : f.a.vi}</span>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ─── CTA Banner ──────────────────────────────────────────────────────────
function CTABanner({ lang }) {
  const ref = useReveal();
  return (
    <section className="wrap" ref={ref}>
      <div className="cta-banner reveal">
        <div className="cta-banner-left">
          <h2>
            {pick(T.ctaBanner.title, lang)}
            <em>{pick(T.ctaBanner.titleEm, lang)}</em>
          </h2>
          <p>{pick(T.ctaBanner.sub, lang)}</p>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--neon)', marginTop: 6 }}>
            <span style={{ color: 'var(--txt-mute)' }}>$</span> curl -O https://kali.org/get-kali/sha256sum.txt
          </div>
        </div>
        <div className="cta-banner-right">
          <a className="btn primary" href="#install">
            {pick(T.hero.primary, lang)}
            <span className="arrow">→</span>
          </a>
          <a className="btn" href="#docs">{lang === 'vi' ? 'Đọc tài liệu' : 'Read the Docs'}</a>
        </div>
      </div>
    </section>
  );
}

// ─── Footer ──────────────────────────────────────────────────────────────
function Footer({ lang }) {
  return (
    <footer className="footer wrap">
      <div className="footer-grid">
        <div>
          <div className="brand" style={{ marginBottom: 8 }}>
            <svg viewBox="0 0 32 32" width="28" height="28" fill="none">
              <defs>
                <linearGradient id="fg" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#9bffaf" />
                  <stop offset="100%" stopColor="#00b82e" />
                </linearGradient>
              </defs>
              <polygon points="6,18 14,8 22,8 28,14 22,16 14,12 8,22" fill="url(#fg)" />
              <polygon points="16,8 17,2 20,9" fill="url(#fg)" />
              <polygon points="11,11 13,5 14,12" fill="url(#fg)" />
              <circle cx="20" cy="12" r="1.2" fill="#050706" />
            </svg>
            <b>KALI</b><small>// linux</small>
          </div>
          <p className="footer-tagline">{pick(T.footer.tagline, lang)}</p>
        </div>
        {T.footer.cols.map((col, i) => (
          <div key={i}>
            <h4>{pick(col.h, lang)}</h4>
            <ul>
              {col.links.map((l) => <li key={l}><a href="#">{l}</a></li>)}
            </ul>
          </div>
        ))}
      </div>
      <div className="footer-bottom">
        <div style={{ whiteSpace: 'pre-line' }}>{pick(T.footer.legal, lang)}</div>
        <div className="blink">{pick(T.footer.status, lang)}</div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, Hero, StatsBar, Features, ToolsShowcase, UseCases,
  Install, Community, Testimonials, FAQ, CTABanner, Footer,
  pick,
});
