// 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: 'Who Are We?', num: '02' },
  { href: '#roster', label: 'Roster', num: '03' },
  { href: '#coaches', label: 'Coaches', num: '04' },
  { href: '#schedule', label: 'Schedule', num: '05' },
  { href: '#recruit', label: 'Tryouts', 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-main.png" alt="NG Wolfpack Chastain" style={{ height: 56 }} />
          <div className="nav-logo-text" style={{ fontSize: 14 }}>
            North Georgia 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)' }}>◆ GRIT · FAMILY · COMMITMENT</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 }}>
            <a href="https://www.facebook.com/profile.php?id=100090483468332" target="_blank" rel="noopener" aria-label="Facebook" style={{ width: 40, height: 40, border: '1px solid rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-head)', fontSize: 11, letterSpacing: '0.1em' }}>FB</a>
            <a href="https://web.gc.com/teams/hOv2dnrLHWLy?utm_source=Web&utm_campaign=team_share_link" target="_blank" rel="noopener" aria-label="GameChanger" style={{ width: 40, height: 40, border: '1px solid rgba(255,255,255,0.12)', display: 'grid', placeItems: 'center' }}>
              <img src="assets/gc-logo.png" alt="" style={{ width: 22, height: 22, display: 'block' }}/>
            </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>
          <a href="#contact" style={{ display: 'block', fontSize: 13, padding: '6px 0', color: 'var(--bone-dim)' }}>Open Workouts</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/>howl@ngwolfpack.com
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 North Georgia Wolfpack Chastain · All Rights Reserved</span>
        <span style={{ color: 'var(--wolf-red-hot)' }}>◆ GRIT ◆ FAMILY ◆ COMMITMENT ◆</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, photo, photoPos }) {
  const hasPhoto = !!photo;
  const overlayShadow = hasPhoto ? '0 1px 4px rgba(0,0,0,0.9), 0 0 8px rgba(0,0,0,0.7)' : undefined;
  return (
    <div className="ph" style={{ aspectRatio: '3 / 4' }}>
      {hasPhoto && (
        <>
          <img src={photo} alt={name} loading="lazy"
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                     objectFit: 'cover', objectPosition: photoPos || 'center 30%',
                     filter: 'contrast(1.05) saturate(1.05)' }} />
          <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
                        background: 'linear-gradient(180deg, rgba(0,0,0,0.35) 0%, transparent 22%, transparent 55%, rgba(0,0,0,0.88) 100%)' }} />
          <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
                        boxShadow: 'inset 0 0 60px rgba(196,30,58,0.22)' }} />
        </>
      )}
      <div style={{ position: 'absolute', top: 12, left: 12, fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--wolf-red-hot)', letterSpacing: '0.2em', zIndex: 2, textShadow: overlayShadow }}>
        #{String(num).padStart(2, '0')}
      </div>
      <div style={{ position: 'absolute', top: 12, right: 12, fontFamily: 'var(--font-mono)', fontSize: 9, color: hasPhoto ? 'var(--bone)' : 'var(--bone-dim)', letterSpacing: '0.2em', zIndex: 2, textShadow: overlayShadow }}>
        {pos}
      </div>
      {!hasPhoto && (
        <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', zIndex: 2, textShadow: overlayShadow }}>
        {name}
        {nickname && (
          <div className="mono" style={{ fontSize: 9, color: 'var(--wolf-red-hot)', letterSpacing: '0.2em', marginTop: 2, textTransform: 'none', fontFamily: 'var(--font-mono)', textShadow: overlayShadow }}>
            {nickname}
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================================
// PASSWORD GATE — dev-only, client-side. Password: pack.
// Not real security; obfuscates site from casual visitors while under dev.
// ============================================================
const GATE_KEY = 'wp-gate-v1';
const GATE_PW  = 'pack';

function isGateOpen() {
  try { return sessionStorage.getItem(GATE_KEY) === 'ok' || localStorage.getItem(GATE_KEY) === 'ok'; }
  catch { return false; }
}

function PasswordGate({ onPass }) {
  const [value, setValue] = useState('');
  const [error, setError] = useState(false);
  const [shake, setShake] = useState(false);

  function submit(e) {
    e.preventDefault();
    if (value.trim().toLowerCase() === GATE_PW) {
      try { localStorage.setItem(GATE_KEY, 'ok'); } catch {}
      setError(false);
      onPass();
    } else {
      setError(true);
      setShake(true);
      setTimeout(() => setShake(false), 500);
      setValue('');
    }
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'radial-gradient(ellipse 60% 60% at 50% 40%, rgba(196,30,58,0.18), transparent 65%), var(--ink)',
      display: 'grid', placeItems: 'center',
      padding: 'var(--pad)',
      overflow: 'hidden',
    }}>
      {/* Dotted grid bg */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        backgroundImage: 'radial-gradient(rgba(255,255,255,0.06) 1px, transparent 1.5px)',
        backgroundSize: '120px 120px',
        opacity: 0.5,
      }}/>
      {/* Scan lines */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'repeating-linear-gradient(0deg, rgba(255,255,255,0.02) 0 1px, transparent 1px 3px)',
        mixBlendMode: 'overlay',
      }}/>
      {/* Scan line sweep */}
      <div className="scanline" style={{ top: 0 }}/>

      <form onSubmit={submit} style={{
        position: 'relative',
        width: 'min(440px, 100%)',
        background: 'linear-gradient(160deg, var(--ink-3), var(--ink-2))',
        border: '1px solid rgba(230,57,70,0.4)',
        boxShadow: '0 40px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(230,57,70,0.15), inset 0 0 40px rgba(230,57,70,0.05)',
        padding: 'clamp(28px, 5vw, 44px)',
        transform: shake ? 'translateX(0)' : undefined,
        animation: shake ? 'gateShake 0.45s cubic-bezier(.36,.07,.19,.97)' : undefined,
      }}>
        {/* HUD corners */}
        {['tl','tr','bl','br'].map(pos => {
          const s = {
            tl: { top: -1, left: -1, borderTop: '2px solid var(--wolf-red)', borderLeft: '2px solid var(--wolf-red)' },
            tr: { top: -1, right: -1, borderTop: '2px solid var(--wolf-red)', borderRight: '2px solid var(--wolf-red)' },
            bl: { bottom: -1, left: -1, borderBottom: '2px solid var(--wolf-red)', borderLeft: '2px solid var(--wolf-red)' },
            br: { bottom: -1, right: -1, borderBottom: '2px solid var(--wolf-red)', borderRight: '2px solid var(--wolf-red)' },
          }[pos];
          return <span key={pos} aria-hidden style={{ position: 'absolute', width: 18, height: 18, ...s }}/>;
        })}

        <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="live-dot"/>RESTRICTED · UNDER DEVELOPMENT
        </div>
        <h1 className="display" style={{
          fontSize: 'clamp(44px, 9vw, 72px)', marginTop: 14, lineHeight: 0.92,
          color: 'var(--bone)',
        }}>
          THE PACK IS<br/><span style={{ color: 'var(--wolf-red-hot)' }}>NOT OPEN.</span>
        </h1>
        <p className="mono" style={{ marginTop: 14, color: 'var(--bone-dim)', lineHeight: 1.7 }}>
          ◆ Enter credentials to proceed.
        </p>

        <label style={{ display: 'block', marginTop: 24 }}>
          <div className="mono" style={{ marginBottom: 8, color: 'var(--wolf-red-hot)' }}>PASSWORD</div>
          <input
            autoFocus
            type="password"
            value={value}
            onChange={(e) => { setValue(e.target.value); if (error) setError(false); }}
            placeholder="• • • •"
            style={{
              width: '100%', padding: '14px 16px',
              background: 'var(--ink)',
              border: error ? '1px solid var(--wolf-red-hot)' : '1px solid rgba(255,255,255,0.12)',
              color: 'var(--bone)', fontFamily: 'var(--font-mono)', fontSize: 16,
              letterSpacing: '0.3em', outline: 'none',
              transition: 'border-color 180ms ease, box-shadow 180ms ease',
              boxShadow: error ? '0 0 20px rgba(230,57,70,0.25)' : 'none',
            }}/>
        </label>

        {error && (
          <div className="mono" style={{ marginTop: 10, color: 'var(--wolf-red-hot)', fontSize: 10 }}>
            ◆ ACCESS DENIED · TRY AGAIN
          </div>
        )}

        <button type="submit" className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 24 }}>
          UNLOCK <span className="arrow">→</span>
        </button>

        <div className="mono" style={{ marginTop: 18, color: 'var(--bone-dim)', fontSize: 9, letterSpacing: '0.2em', textAlign: 'center' }}>
          NG WOLFPACK · CHASTAIN · 2012
        </div>
      </form>

      <style>{`
        @keyframes gateShake {
          10%, 90% { transform: translateX(-2px); }
          20%, 80% { transform: translateX(4px); }
          30%, 50%, 70% { transform: translateX(-8px); }
          40%, 60% { transform: translateX(8px); }
        }
      `}</style>
    </div>
  );
}

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