// ONYX PERFORMANCE LAB — Shared Components
// Exports: OnyxNav, OnyxFooter, useInView, AnimatedNumber, PageHero, SectionLabel
// All exported to window for cross-file access.

const { useState, useEffect, useRef } = React;

// ── useInView ────────────────────────────────────────────────
function useInView(threshold = 0.12) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) setInView(true); },
      { threshold }
    );
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
}

// ── AnimatedNumber ───────────────────────────────────────────
function AnimatedNumber({ target, suffix = '', duration = 1800, prefix = '' }) {
  const [val, setVal] = useState(0);
  const [ref, inView] = useInView(0.3);
  const started = useRef(false);
  useEffect(() => {
    if (!inView || started.current) return;
    started.current = true;
    const start = performance.now();
    const tick = (now) => {
      const p = Math.min((now - start) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(eased * target));
      if (p < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [inView]);
  return <span ref={ref}>{prefix}{val.toLocaleString()}{suffix}</span>;
}

// ── SectionLabel ─────────────────────────────────────────────
function SectionLabel({ children, light = false }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24,
    }}>
      <div style={{ width: 24, height: 1, background: light ? '#ccc' : '#444', flexShrink: 0 }} />
      <span style={{
        fontFamily: 'var(--font)', fontSize: 10, fontWeight: 600,
        letterSpacing: '0.22em', textTransform: 'uppercase',
        color: light ? '#999' : '#666',
      }}>{children}</span>
    </div>
  );
}

// ── PageHero ─────────────────────────────────────────────────
function PageHero({ label, title, sub, bg = '#000', fg = '#fff', eyebrow, cta, ctaLink = 'contact' }) {
  return (
    <section style={{
      background: bg, color: fg,
      padding: '160px 40px 100px',
      borderBottom: `1px solid ${fg === '#fff' ? '#1A1A1A' : '#E5E5E5'}`,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(#1A1A1A 1px, transparent 1px), linear-gradient(90deg, #1A1A1A 1px, transparent 1px)',
        backgroundSize: '80px 80px', opacity: bg === '#000' ? 0.35 : 0,
        pointerEvents: 'none',
      }} />
      <div style={{ maxWidth: 1280, margin: '0 auto', position: 'relative', zIndex: 1 }}>
        {label && <SectionLabel light={fg === '#fff'}>{label}</SectionLabel>}
        <h1 style={{
          fontFamily: 'var(--font)',
          fontSize: 'clamp(44px, 6vw, 88px)',
          fontWeight: 700, letterSpacing: '0.04em',
          lineHeight: 1.0, textTransform: 'uppercase',
          maxWidth: 900, marginBottom: sub ? 32 : 0,
        }}>{title}</h1>
        {sub && (
          <p style={{
            fontFamily: 'var(--font)', fontSize: 17, fontWeight: 300,
            lineHeight: 1.75, color: fg === '#fff' ? '#666' : '#777',
            maxWidth: 560, marginBottom: cta ? 48 : 0,
          }}>{sub}</p>
        )}
        {cta && (
          <a href={ctaLink} className="btn-primary">{cta}</a>
        )}
      </div>
    </section>
  );
}

// ── Nav ──────────────────────────────────────────────────────
function OnyxNav() {
  const [scrolled, setScrolled] = useState(false);
  const [servicesOpen, setServicesOpen] = useState(false);
  const [methodOpen, setMethodOpen] = useState(false);
  const [aboutOpen, setAboutOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const closeTimer = useRef(null);
  const methodCloseTimer = useRef(null);
  const aboutCloseTimer = useRef(null);

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

  useEffect(() => {
    document.body.classList.toggle('nav-locked', mobileOpen);
    return () => document.body.classList.remove('nav-locked');
  }, [mobileOpen]);

  const openServices = () => {
    clearTimeout(closeTimer.current);
    setServicesOpen(true);
  };
  const scheduleCloseServices = () => {
    clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setServicesOpen(false), 220);
  };

  const openMethod = () => {
    clearTimeout(methodCloseTimer.current);
    setMethodOpen(true);
  };
  const scheduleCloseMethod = () => {
    clearTimeout(methodCloseTimer.current);
    methodCloseTimer.current = setTimeout(() => setMethodOpen(false), 220);
  };

  const openAbout = () => {
    clearTimeout(aboutCloseTimer.current);
    setAboutOpen(true);
  };
  const scheduleCloseAbout = () => {
    clearTimeout(aboutCloseTimer.current);
    aboutCloseTimer.current = setTimeout(() => setAboutOpen(false), 220);
  };

  const linkStyle = {
    fontFamily: 'var(--font)', fontSize: 11, fontWeight: 500,
    letterSpacing: '0.18em', textTransform: 'uppercase',
    color: '#888', background: 'none', border: 'none',
    cursor: 'pointer', transition: 'color 200ms', padding: '4px 0',
    position: 'relative',
  };

  const serviceLinks = [
    { label: 'Athlete Training', href: 'athlete-training' },
    { label: 'Youth Performance', href: 'youth-performance' },
    { label: 'Private Training', href: 'private-training' },
    { label: 'Performance Testing', href: 'performance-testing' },
    { label: 'Memberships', href: 'memberships' },
    { label: 'Onyx Vault', href: 'vault' },
  ];

  const methodLinks = [
    { label: 'Our Methodology', href: 'methodology' },
    { label: 'Onyx Performance OS', href: 'performance-os' },
  ];

  const aboutLinks = [
    { label: 'About Onyx', href: 'about' },
    { label: 'Gallery', href: 'gallery' },
    { label: 'Blog', href: 'blog' },
  ];

  const topLinks = [
    { label: 'Schedule', href: 'schedule' },
  ];

  return (
    <>
      <nav style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1000,
        background: scrolled || mobileOpen ? 'rgba(0,0,0,0.97)' : 'transparent',
        borderBottom: scrolled || mobileOpen ? '1px solid #1A1A1A' : 'none',
        backdropFilter: scrolled && !mobileOpen ? 'blur(12px)' : 'none',
        WebkitBackdropFilter: scrolled && !mobileOpen ? 'blur(12px)' : 'none',
        transition: 'all 350ms var(--ease)',
        padding: '0 40px',
      }}>
        <div style={{
          maxWidth: 1280, margin: '0 auto',
          display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', height: 72,
        }}>
          {/* Logo */}
          <a href="/" style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
            <img src="assets/mark-tight-white-on-black.png" alt="Onyx" style={{ height: 30, width: 30, objectFit: 'contain' }} />
            <div>
              <div style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 700, letterSpacing: '0.22em', color: '#fff', textTransform: 'uppercase', lineHeight: 1.1 }}>Onyx</div>
              <div style={{ fontFamily: 'var(--font)', fontSize: 9, fontWeight: 300, letterSpacing: '0.18em', color: '#555', textTransform: 'uppercase', lineHeight: 1.1 }}>Performance Lab</div>
            </div>
          </a>

          {/* Desktop Nav */}
          <div className="nav-desktop-links" style={{ display: 'flex', alignItems: 'center', gap: 36 }}>
            {/* Services dropdown */}
            <div
              style={{ position: 'relative' }}
              onMouseEnter={openServices}
              onMouseLeave={scheduleCloseServices}
            >
              <a href="services" style={{ ...linkStyle, color: servicesOpen ? '#fff' : '#888', textDecoration: 'none' }}>
                Services ▾
              </a>
              {servicesOpen && (
                <div
                  onMouseEnter={openServices}
                  onMouseLeave={scheduleCloseServices}
                  style={{
                    position: 'absolute', top: '100%', left: '50%',
                    transform: 'translateX(-50%)',
                    paddingTop: 16,
                    zIndex: 200,
                  }}
                >
                  <div style={{
                    background: '#000', border: '1px solid #1A1A1A',
                    minWidth: 220,
                    animation: 'fadeUp 150ms ease',
                  }}>
                    {serviceLinks.map(sl => (
                      <a key={sl.href} href={sl.href} style={{
                        display: 'block', padding: '14px 20px',
                        fontFamily: 'var(--font)', fontSize: 11,
                        fontWeight: 500, letterSpacing: '0.14em',
                        textTransform: 'uppercase', color: '#666',
                        borderBottom: '1px solid #111',
                        transition: 'color 150ms, background 150ms',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.color = '#fff'; e.currentTarget.style.background = '#111'; }}
                      onMouseLeave={e => { e.currentTarget.style.color = '#666'; e.currentTarget.style.background = 'transparent'; }}
                      >{sl.label}</a>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Methodology dropdown */}
            <div
              style={{ position: 'relative' }}
              onMouseEnter={openMethod}
              onMouseLeave={scheduleCloseMethod}
            >
              <a href="methodology" style={{ ...linkStyle, color: methodOpen ? '#fff' : '#888', textDecoration: 'none' }}>
                Methodology ▾
              </a>
              {methodOpen && (
                <div
                  onMouseEnter={openMethod}
                  onMouseLeave={scheduleCloseMethod}
                  style={{
                    position: 'absolute', top: '100%', left: '50%',
                    transform: 'translateX(-50%)',
                    paddingTop: 16,
                    zIndex: 200,
                  }}
                >
                  <div style={{
                    background: '#000', border: '1px solid #1A1A1A',
                    minWidth: 240,
                    animation: 'fadeUp 150ms ease',
                  }}>
                    {methodLinks.map(ml => (
                      <a key={ml.href} href={ml.href} style={{
                        display: 'block', padding: '14px 20px',
                        fontFamily: 'var(--font)', fontSize: 11,
                        fontWeight: 500, letterSpacing: '0.14em',
                        textTransform: 'uppercase', color: '#666',
                        borderBottom: '1px solid #111',
                        transition: 'color 150ms, background 150ms',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.color = '#fff'; e.currentTarget.style.background = '#111'; }}
                      onMouseLeave={e => { e.currentTarget.style.color = '#666'; e.currentTarget.style.background = 'transparent'; }}
                      >{ml.label}</a>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* About dropdown */}
            <div
              style={{ position: 'relative' }}
              onMouseEnter={openAbout}
              onMouseLeave={scheduleCloseAbout}
            >
              <button style={{ ...linkStyle }}
                onMouseEnter={e => e.currentTarget.style.color = '#fff'}
                onMouseLeave={e => e.currentTarget.style.color = '#888'}
              >About</button>
              {aboutOpen && (
                <div className="nav-dropdown" style={{
                  position: 'absolute', top: 'calc(100% + 12px)', left: '50%',
                  transform: 'translateX(-50%)',
                  opacity: 1, pointerEvents: 'all',
                }}>
                  <div style={{ background: '#000', border: '1px solid #1A1A1A', minWidth: 200, animation: 'fadeUp 150ms ease' }}>
                    {aboutLinks.map(al => (
                      <a key={al.href} href={al.href} style={{
                        display: 'block', padding: '14px 20px',
                        fontFamily: 'var(--font)', fontSize: 11,
                        fontWeight: 500, letterSpacing: '0.14em',
                        textTransform: 'uppercase', color: '#666',
                        borderBottom: '1px solid #111',
                        transition: 'color 150ms, background 150ms',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.color = '#fff'; e.currentTarget.style.background = '#111'; }}
                      onMouseLeave={e => { e.currentTarget.style.color = '#666'; e.currentTarget.style.background = 'transparent'; }}
                      >{al.label}</a>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {topLinks.map(l => (
              <a key={l.href} href={l.href} style={{ ...linkStyle, textDecoration: 'none' }}
                onMouseEnter={e => e.currentTarget.style.color = '#fff'}
                onMouseLeave={e => e.currentTarget.style.color = '#888'}
              >{l.label}</a>
            ))}
          </div>

          {/* CTA */}
          <a href="https://www.onyxperformanceos.com/login" target="_blank" rel="noopener noreferrer" style={{ fontFamily:'var(--font)', fontSize:11, fontWeight:600, letterSpacing:'0.14em', textTransform:'uppercase', color:'#666', textDecoration:'none', transition:'color 200ms' }}
            onMouseEnter={e => e.currentTarget.style.color='#fff'}
            onMouseLeave={e => e.currentTarget.style.color='#666'}>Member Login</a>
          <a href="contact" className="btn-primary nav-desktop-cta" style={{ fontSize: 11, padding: '10px 24px' }}>Book Assessment</a>

          {/* Hamburger (mobile only, shown via CSS) */}
          <button
            type="button"
            className={`nav-burger${mobileOpen ? ' open' : ''}`}
            aria-label="Toggle menu"
            aria-expanded={mobileOpen}
            onClick={() => setMobileOpen(v => !v)}
          >
            <span className="nav-burger-icon"><span /></span>
          </button>
        </div>
      </nav>

      {/* Mobile drawer — sibling of nav so backdrop-filter doesn't clip it */}
      <div className={`nav-mobile-drawer${mobileOpen ? ' open' : ''}`} aria-hidden={!mobileOpen}>
        <a href="services" onClick={() => setMobileOpen(false)}>Services</a>
        {serviceLinks.map(sl => (
          <a key={sl.href} href={sl.href} className="sub" onClick={() => setMobileOpen(false)}>{sl.label}</a>
        ))}
        <a href="methodology" onClick={() => setMobileOpen(false)}>Methodology</a>
        <a href="performance-os" className="sub" onClick={() => setMobileOpen(false)}>Onyx Performance OS</a>
        <a href="schedule" onClick={() => setMobileOpen(false)}>Schedule</a>
        <a href="about" onClick={() => setMobileOpen(false)}>About</a>
        {aboutLinks.slice(1).map(al => (
          <a key={al.href} href={al.href} className="sub" onClick={() => setMobileOpen(false)}>{al.label}</a>
        ))}
        <a href="contact" className="nav-mobile-drawer-cta" onClick={() => setMobileOpen(false)}>Book Assessment</a>
      </div>

      {/* Sticky mobile bottom CTA — hidden on desktop via CSS */}
      <div className="sticky-mobile-cta">
        <a href="https://calendly.com/onyx-onyxperformancelab/intro-consultation" className="sticky-mobile-cta__book">Book Intro Consult</a>
        <a href="tel:+17867610304" className="sticky-mobile-cta__call">Call</a>
      </div>

      <EmailCapture />
    </>
  );
}

// ── Footer ───────────────────────────────────────────────────
function FooterNewsletter() {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState('idle'); // idle | submitting | done | error
  const [focused, setFocused] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === 'submitting' || status === 'done') return;
    setStatus('submitting');
    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      setStatus(res.ok && data.success ? 'done' : 'error');
    } catch {
      setStatus('error');
    }
  };

  return (
    <div className="footer-newsletter" style={{ borderTop: '1px solid #111', borderBottom: '1px solid #111', padding: '40px 0', marginBottom: 48, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 40, flexWrap: 'wrap' }}>
      <div>
        <div style={{ fontFamily: 'var(--font)', fontSize: 9, fontWeight: 700, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#444', marginBottom: 8 }}>From the Lab</div>
        <div style={{ fontFamily: 'var(--font)', fontSize: 14, fontWeight: 600, color: '#fff', letterSpacing: '0.04em' }}>Training science and performance insights.</div>
      </div>
      {status === 'done' ? (
        <div style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 300, color: '#555' }}>You're in. We'll be in touch when there's something worth reading.</div>
      ) : (
        <form onSubmit={handleSubmit} className="footer-newsletter-form" style={{ display: 'flex', gap: 0, flexShrink: 0 }}>
          <input
            type="email" required placeholder="your@email.com"
            value={email} onChange={e => setEmail(e.target.value)}
            onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
            style={{
              fontFamily: 'var(--font)', fontSize: 13, fontWeight: 300,
              background: 'transparent', border: 'none',
              borderBottom: `1px solid ${focused ? '#fff' : '#2A2A2A'}`,
              color: '#fff', padding: '10px 0', width: 220, outline: 'none',
              letterSpacing: '0.04em', marginRight: 20, transition: 'border-color 200ms',
            }}
          />
          <button type="submit" disabled={status === 'submitting'} style={{
            fontFamily: 'var(--font)', fontSize: 10, fontWeight: 700, letterSpacing: '0.18em',
            textTransform: 'uppercase', background: 'transparent', border: '1px solid #333',
            color: '#666', padding: '10px 20px', cursor: 'pointer', transition: 'all 200ms',
            opacity: status === 'submitting' ? 0.5 : 1,
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = '#fff'; e.currentTarget.style.color = '#fff'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = '#333'; e.currentTarget.style.color = '#666'; }}
          >{status === 'submitting' ? 'Subscribing…' : 'Subscribe'}</button>
        </form>
      )}
    </div>
  );
}

function OnyxFooter() {
  const cols = [
    { head: 'Services', links: [
      { label: 'Athlete Training', href: 'athlete-training' },
      { label: 'Youth Performance', href: 'youth-performance' },
      { label: 'Private Training', href: 'private-training' },
      { label: 'Onyx Vault', href: 'vault' },
      { label: 'All Services', href: 'services' },
    ]},
    { head: 'Performance', links: [
      { label: 'Testing & Evaluation', href: 'performance-testing' },
      { label: 'Our Methodology', href: 'methodology' },
      { label: 'Onyx Performance OS', href: 'performance-os' },
      { label: 'Memberships', href: 'memberships' },
      { label: 'Schedule', href: 'schedule' },
    ]},
    { head: 'Company', links: [
      { label: 'About Onyx', href: 'about' },
      { label: 'Contact', href: 'contact' },
      { label: 'Book Assessment', href: 'contact' },
    ]},
  ];

  return (
    <footer style={{ background: '#000', borderTop: '1px solid #111', padding: '80px 40px 40px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr',
          gap: 60, paddingBottom: 60, borderBottom: '1px solid #111', marginBottom: 40,
        }}>
          <div>
            <a href="/" style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24, textDecoration: 'none' }}>
              <img src="assets/mark-tight-white-on-black.png" alt="Onyx" style={{ height: 26, width: 26, objectFit: 'contain' }} />
              <div>
                <div style={{ fontFamily: 'var(--font)', fontSize: 12, fontWeight: 700, letterSpacing: '0.22em', color: '#fff', textTransform: 'uppercase', lineHeight: 1.1 }}>Onyx</div>
                <div style={{ fontFamily: 'var(--font)', fontSize: 9, fontWeight: 300, letterSpacing: '0.18em', color: '#444', textTransform: 'uppercase', lineHeight: 1.1 }}>Performance Lab</div>
              </div>
            </a>
            <p style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 300, lineHeight: 1.8, color: '#444', maxWidth: 260, marginBottom: 24 }}>
              Miami's Premier Sports Science and Performance Training Facility.
            </p>
            <div style={{ fontFamily: 'var(--font)', fontSize: 12, fontWeight: 300, color: '#555', lineHeight: 1.9, marginBottom: 18 }}>
              <div>2048 NW 22nd Ct</div>
              <div>Miami, FL 33142</div>
            </div>
            <div style={{ fontFamily: 'var(--font)', fontSize: 12, fontWeight: 300, lineHeight: 1.9, marginBottom: 24 }}>
              <a href="tel:+17867610304" style={{ color: '#555', textDecoration: 'none', transition: 'color 200ms', display: 'block' }}
                onMouseEnter={e => e.currentTarget.style.color = '#fff'}
                onMouseLeave={e => e.currentTarget.style.color = '#555'}
              >+1 (786) 761-0304</a>
              <a href="mailto:onyx@onyxperformancesystems.com" style={{ color: '#555', textDecoration: 'none', transition: 'color 200ms', display: 'block' }}
                onMouseEnter={e => e.currentTarget.style.color = '#fff'}
                onMouseLeave={e => e.currentTarget.style.color = '#555'}
              >onyx@onyxperformancesystems.com</a>
            </div>
            <div style={{ display: 'flex', gap: 18, fontFamily: 'var(--font)', fontSize: 10, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
              {[
                { label: 'Instagram', href: 'https://instagram.com/onyxperformancelab' },
                { label: 'Facebook', href: 'https://facebook.com/onyxperformancelab' },
                { label: 'LinkedIn', href: 'https://linkedin.com/company/onyxperformancelab' },
              ].map(s => (
                <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" style={{ color: '#555', textDecoration: 'none', transition: 'color 200ms' }}
                  onMouseEnter={e => e.currentTarget.style.color = '#fff'}
                  onMouseLeave={e => e.currentTarget.style.color = '#555'}
                >{s.label}</a>
              ))}
            </div>
          </div>
          {cols.map(col => (
            <div key={col.head}>
              <div style={{ fontFamily: 'var(--font)', fontSize: 10, fontWeight: 700, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#444', marginBottom: 24 }}>{col.head}</div>
              {col.links.map(l => (
                <div key={l.label} style={{ marginBottom: 14 }}>
                  <a href={l.href} style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 300, color: '#444', transition: 'color 200ms' }}
                    onMouseEnter={e => e.target.style.color = '#fff'}
                    onMouseLeave={e => e.target.style.color = '#444'}
                  >{l.label}</a>
                </div>
              ))}
            </div>
          ))}
        </div>
        <FooterNewsletter />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontFamily: 'var(--font)', fontSize: 11, color: '#2A2A2A', letterSpacing: '0.06em' }}>© 2026 Onyx Performance Lab</span>
          <span style={{ fontFamily: 'var(--font)', fontSize: 11, fontWeight: 500, letterSpacing: '0.2em', textTransform: 'uppercase', color: '#2A2A2A' }}>Performance, Measured.</span>
        </div>
      </div>
    </footer>
  );
}

// ── Email Capture ─────────────────────────────────────────────
const WEB3FORMS_EMAIL_KEY = '90de3a41-4bb8-491c-aeab-fd4ff166bd2d';

function EmailCapture() {
  const [visible, setVisible] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [email, setEmail] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [focused, setFocused] = useState(false);

  useEffect(() => {
    if (localStorage.getItem('onyx-email-capture')) return;
    const onScroll = () => {
      const pct = window.scrollY / (document.body.scrollHeight - window.innerHeight);
      if (pct > 0.55) {
        setVisible(true);
        window.removeEventListener('scroll', onScroll);
      }
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const dismiss = () => {
    setVisible(false);
    localStorage.setItem('onyx-email-capture', 'dismissed');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (res.ok && data.success) {
        setSubmitted(true);
        localStorage.setItem('onyx-email-capture', 'submitted');
      }
    } finally {
      setSubmitting(false);
    }
  };

  if (!visible) return null;

  return (
    <div className="email-capture" style={{
      position: 'fixed', bottom: 24, right: 24, width: 320,
      background: '#000', border: '1px solid #1A1A1A',
      padding: '28px 24px', zIndex: 995,
      animation: 'fadeUp 300ms ease',
    }}>
      <button onClick={dismiss} aria-label="Close" style={{
        position: 'absolute', top: 12, right: 16,
        background: 'none', border: 'none', color: '#444',
        fontSize: 20, cursor: 'pointer', lineHeight: 1,
        transition: 'color 150ms',
      }}
        onMouseEnter={e => e.currentTarget.style.color = '#fff'}
        onMouseLeave={e => e.currentTarget.style.color = '#444'}>×</button>

      {submitted ? (
        <div>
          <div style={{ fontFamily: 'var(--font)', fontSize: 16, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#fff', marginBottom: 10 }}>You're in.</div>
          <p style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 300, color: '#555', lineHeight: 1.7 }}>We'll be in touch when there's something worth reading.</p>
        </div>
      ) : (
        <>
          <div style={{ fontFamily: 'var(--font)', fontSize: 9, fontWeight: 700, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#555', marginBottom: 14 }}>From the Lab</div>
          <div style={{ fontFamily: 'var(--font)', fontSize: 16, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#fff', lineHeight: 1.15, marginBottom: 10 }}>Performance insights worth reading.</div>
          <p style={{ fontFamily: 'var(--font)', fontSize: 12, fontWeight: 300, color: '#555', lineHeight: 1.75, marginBottom: 22 }}>Training science, testing methodology, and athlete development. No noise. Published when it's ready.</p>
          <form onSubmit={handleSubmit}>
            <input
              type="email" required placeholder="your@email.com"
              value={email} onChange={e => setEmail(e.target.value)}
              onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
              style={{
                fontFamily: 'var(--font)', fontSize: 13, fontWeight: 300,
                background: 'transparent', border: 'none',
                borderBottom: `1px solid ${focused ? '#fff' : '#2A2A2A'}`,
                color: '#fff', padding: '10px 0', width: '100%',
                outline: 'none', letterSpacing: '0.04em',
                marginBottom: 16, display: 'block', transition: 'border-color 200ms',
              }}
            />
            <button type="submit" disabled={submitting} className="btn-primary" style={{
              width: '100%', fontSize: 11, padding: '13px 20px',
              opacity: submitting ? 0.6 : 1, cursor: submitting ? 'wait' : 'pointer',
            }}>
              {submitting ? 'Submitting…' : 'Subscribe →'}
            </button>
          </form>
        </>
      )}
    </div>
  );
}

// ── Export to window ─────────────────────────────────────────
Object.assign(window, {
  OnyxNav,
  OnyxFooter,
  useInView,
  AnimatedNumber,
  SectionLabel,
  PageHero,
  EmailCapture,
});
