// Shared components for the Wolfpack site
// Exports via window.* at the end so all page scripts can use them.

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

// ============================================================
// HOOKS
// ============================================================
function useRoute() {
  const [route, setRoute] = useState(() => (window.location.hash || '#home').slice(1));
  useEffect(() => {
    const onHash = () => {
      setRoute((window.location.hash || '#home').slice(1));
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function useTick(intervalMs = 1000) {
  const [n, setN] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setN(x => x + 1), intervalMs);
    return () => clearInterval(id);
  }, [intervalMs]);
  return n;
}

function useInView(ref, opts = { threshold: 0.15 }) {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setSeen(true); });
    }, opts);
    io.observe(ref.current);
    return () => io.disconnect();
  }, [ref]);
  return seen;
}

// ============================================================
// NAV
// ============================================================
const NAV_ITEMS = [
  { href: '#home', label: 'Home', num: '01' },
  { href: '#about', label: 'The Standard', num: '02' },
  { href: '#roster', label: 'Roster', num: '03' },
  { href: '#schedule', label: 'Schedule', num: '04' },
  { href: '#coaches', label: 'Coaches', num: '05' },
  { href: '#fundraise', label: 'Fundraise', num: '06' },
  { href: '#contact', label: 'Contact', num: '07' },
];

function Nav({ route }) {
  const [open, setOpen] = useState(false);
  useEffect(() => { setOpen(false); }, [route]);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
  }, [open]);

  return (
    <>
      <nav className="nav">
        <a href="#home" className="nav-logo">
          <img src="assets/logo-icon.png" alt="WP" style={{ height: 56 }} />
          <div className="nav-logo-text" style={{ fontSize: 14 }}>
            NG Wolfpack
            <small>Chastain</small>
          </div>
        </a>
        <div className="nav-links">
          {NAV_ITEMS.map(it => (
            <a key={it.href} href={it.href}
              className={'nav-link' + (route === it.href.slice(1) ? ' active' : '')}>
              {it.label}
            </a>
          ))}
        </div>
        <button className="nav-menu-btn" onClick={() => setOpen(o => !o)} aria-label="Menu">
          <span></span><span></span><span></span>
        </button>
      </nav>
      <div className={'mobile-menu' + (open ? ' open' : '')}>
        {NAV_ITEMS.map((it, i) => (
          <a key={it.href} href={it.href} style={{ animationDelay: `${i * 40}ms` }}>
            <span className="num">{it.num}</span>{it.label}
          </a>
        ))}
        <div style={{ marginTop: 'auto', paddingTop: 32, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', color: 'var(--bone-dim)', textTransform: 'uppercase' }}>
          <div style={{ color: 'var(--wolf-red-hot)' }}>◆ THE STANDARD</div>
          <div style={{ marginTop: 6 }}>Bartow County · Georgia</div>
        </div>
      </div>
    </>
  );
}

// ============================================================
// FOOTER
// ============================================================
function Footer() {
  return (
    <footer>
      <div className="footer-grid">
        <div>
          <img src="assets/logo-horizontal-transparent.png" alt="Wolfpack" style={{ maxWidth: 280, marginBottom: 20, display: 'block', mixBlendMode: 'screen' }} />
          <p style={{ fontSize: 13, color: 'var(--bone-dim)', lineHeight: 1.6, maxWidth: 340 }}>
            North Georgia Wolfpack — Chastain. Fastpitch travel softball based in Bartow County, Georgia. Raising athletes who compete at the highest level.
          </p>
          <div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
            {['IG','FB','X','YT'].map(s => (
              <a key={s} href="#" style={{ width: 36, height: 36, border: '1px solid rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-head)', fontSize: 11, letterSpacing: '0.1em' }}>{s}</a>
            ))}
          </div>
        </div>
        <div>
          <h4 className="head" style={{ fontSize: 12, color: 'var(--wolf-red-hot)', marginBottom: 14, letterSpacing: '0.2em' }}>Program</h4>
          {['About','Roster','Coaches'].map(x => (
            <a key={x} href={'#' + x.toLowerCase()} style={{ display: 'block', fontSize: 13, padding: '6px 0', color: 'var(--bone-dim)' }}>{x}</a>
          ))}
        </div>
        <div>
          <h4 className="head" style={{ fontSize: 12, color: 'var(--wolf-red-hot)', marginBottom: 14, letterSpacing: '0.2em' }}>Get Involved</h4>
          {['Tryouts','Fundraise','Sponsorship','Merch'].map(x => (
            <a key={x} href={x === 'Tryouts' ? '#contact' : '#fundraise'} style={{ display: 'block', fontSize: 13, padding: '6px 0', color: 'var(--bone-dim)' }}>{x}</a>
          ))}
        </div>
        <div>
          <h4 className="head" style={{ fontSize: 12, color: 'var(--wolf-red-hot)', marginBottom: 14, letterSpacing: '0.2em' }}>Contact</h4>
          <div className="mono" style={{ fontSize: 10, color: 'var(--bone-dim)', lineHeight: 1.8 }}>
            Bartow County<br/>Georgia<br/>info@ngwolfpack.com
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 NG Wolfpack Chastain · All Rights Reserved</span>
        <span style={{ color: 'var(--wolf-red-hot)' }}>◆ THE STANDARD ◆ WHO ARE WE ◆ WP ◆</span>
      </div>
    </footer>
  );
}

// ============================================================
// Ambient pieces
// ============================================================
function ScanLines({ count = 2 }) {
  return (
    <>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} className="scanline" style={{ animationDelay: `${i * 3}s`, animationDuration: `${6 + i * 2}s` }} />
      ))}
    </>
  );
}

function Marquee({ items, speed = 30 }) {
  const content = items.concat(items);
  return (
    <div style={{ overflow: 'hidden', padding: '14px 0', borderTop: '1px solid rgba(255,255,255,0.06)', borderBottom: '1px solid rgba(255,255,255,0.06)', background: 'var(--ink-2)' }}>
      <div style={{ display: 'inline-flex', whiteSpace: 'nowrap', animation: `marquee ${speed}s linear infinite` }}>
        {content.map((it, i) => (
          <span key={i} className="head" style={{ padding: '0 40px', fontSize: 14, color: i % 2 ? 'var(--wolf-red-hot)' : 'var(--bone)' }}>
            ◆ {it}
          </span>
        ))}
      </div>
    </div>
  );
}

// Numeric ticker
function Ticker({ value, prefix = '', suffix = '', duration = 1400 }) {
  const [display, setDisplay] = useState(0);
  const ref = useRef();
  const seen = useInView(ref);
  useEffect(() => {
    if (!seen) return;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const k = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - k, 3);
      setDisplay(Math.round(value * eased));
      if (k < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [seen, value, duration]);
  return <span ref={ref} className="tabnum">{prefix}{display.toLocaleString()}{suffix}</span>;
}

// Corner brackets wrapper
function Frame({ children, style, className = '' }) {
  return (
    <div className={'corners ' + className} style={{ position: 'relative', ...style }}>
      {children}
    </div>
  );
}

// ============================================================
// PLACEHOLDER for player portraits
// ============================================================
function PlayerPlaceholder({ num, pos, name = 'ROSTER TBD', nickname }) {
  return (
    <div className="ph" style={{ aspectRatio: '3 / 4' }}>
      <div style={{ position: 'absolute', top: 12, left: 12, fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--wolf-red-hot)', letterSpacing: '0.2em' }}>
        #{String(num).padStart(2, '0')}
      </div>
      <div style={{ position: 'absolute', top: 12, right: 12, fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--bone-dim)', letterSpacing: '0.2em' }}>
        {pos}
      </div>
      <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)', textAlign: 'center' }}>
        <div className="display" style={{ fontSize: 96, color: 'var(--wolf-red)', opacity: 0.35 }}>{String(num).padStart(2,'0')}</div>
        <div className="mono" style={{ fontSize: 9 }}>[PLAYER PHOTO]</div>
      </div>
      <div style={{ position: 'absolute', bottom: 12, left: 12, right: 12, fontFamily: 'var(--font-head)', fontSize: 12, letterSpacing: '0.12em' }}>
        {name}
        {nickname && (
          <div className="mono" style={{ fontSize: 9, color: 'var(--wolf-red-hot)', letterSpacing: '0.2em', marginTop: 2, textTransform: 'none', fontFamily: 'var(--font-mono)' }}>
            {nickname}
          </div>
        )}
      </div>
    </div>
  );
}

// Export to window
Object.assign(window, {
  useRoute, useTick, useInView,
  Nav, Footer, ScanLines, Marquee, Ticker, Frame, PlayerPlaceholder,
  NAV_ITEMS,
});
