/* VE GAMERZ — shared chrome, hooks, and layout primitives. Exports to window.VG. */
const { Button, Badge, Eyebrow } = window.VEGAMERZDesignSystem_63bcb5;
const D = window.VG_DATA;

const wrap = { maxWidth: 'var(--wrap-max)', margin: '0 auto', padding: '0 var(--wrap-pad)', position: 'relative', zIndex: 1 };
const NOTCH = 'polygon(10px 0,100% 0,100% calc(100% - 10px),calc(100% - 10px) 100%,0 100%,0 10px)';

const ROUTES = [
  { id: 'home', label: 'Home' },
  { id: 'about', label: 'About' },
  { id: 'videos', label: 'Videos' },
  { id: 'membership', label: 'Membership' },
  { id: 'contact', label: 'Contact' }
];

/* ── Hooks ─────────────────────────────────────────── */
function useReducedMotion() {
  const [rm, setRm] = React.useState(() =>
    typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches);
  React.useEffect(() => {
    const m = matchMedia('(prefers-reduced-motion: reduce)');
    const on = () => setRm(m.matches);
    m.addEventListener ? m.addEventListener('change', on) : m.addListener(on);
    return () => { m.removeEventListener ? m.removeEventListener('change', on) : m.removeListener(on); };
  }, []);
  return rm;
}

function useInView(opts) {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
    }, { threshold: (opts && opts.threshold) || 0.18, rootMargin: '0px 0px -8% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, seen];
}

/* Fade + rise reveal wrapper. Honors reduced motion. */
function Reveal({ children, delay = 0, y = 22, style = {}, as = 'div' }) {
  const rm = useReducedMotion();
  const [ref, seen] = useInView();
  const El = as;
  const on = rm || seen;
  return (
    <El ref={ref} style={{
      opacity: on ? 1 : 0,
      transform: on ? 'none' : `translateY(${y}px)`,
      transition: rm ? 'none' : `opacity .6s var(--ease) ${delay}ms, transform .6s var(--ease) ${delay}ms`,
      willChange: 'opacity, transform', ...style
    }}>{children}</El>
  );
}

function useCountUp(target, { decimals = 0, duration = 1400, run = true } = {}) {
  const rm = useReducedMotion();
  const [val, setVal] = React.useState(rm ? target : 0);
  React.useEffect(() => {
    if (!run) return;
    if (rm) { setVal(target); return; }
    let raf, t0;
    const ease = (t) => 1 - Math.pow(1 - t, 3);
    const step = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / duration);
      setVal(target * ease(p));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [run, target, rm]);
  return decimals ? val.toFixed(decimals) : Math.round(val).toString();
}

/* ── Brand marks ───────────────────────────────────── */
function LogoMark({ size = 40 }) {
  return (
    <span style={{ width: size, height: size, flex: 'none', clipPath: NOTCH, overflow: 'hidden', border: '1px solid var(--c-line-strong)', boxShadow: 'var(--glow-sm)', display: 'block' }}>
      <img src="assets/logo.jpg" alt="VE GAMERZ logo" width={size} height={size} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 40%', display: 'block' }} />
    </span>
  );
}
function Wordmark({ size = 20 }) {
  return (
    <span style={{ fontFamily: 'var(--f-display)', fontWeight: 700, fontSize: size, letterSpacing: '.04em', lineHeight: 1, color: 'var(--c-text)' }}>
      VE <span style={{ color: 'var(--c-primary)' }}>GAMERZ</span>
    </span>
  );
}

/* ── Nav ───────────────────────────────────────────── */
function NavLink({ label, active, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      aria-current={active ? 'page' : undefined}
      style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '6px 2px', fontFamily: 'var(--f-display)', fontWeight: 600, fontSize: 13, letterSpacing: '.1em', textTransform: 'uppercase', color: active ? 'var(--c-primary)' : (hover ? 'var(--c-text)' : 'var(--c-muted)'), borderBottom: `2px solid ${active ? 'var(--c-primary)' : 'transparent'}`, transition: 'color var(--dur-fast) var(--ease)' }}>
      {label}
    </button>
  );
}

function Hamburger({ open, onClick }) {
  const bar = { display: 'block', width: 22, height: 2, background: 'var(--c-primary)', transition: 'transform .25s var(--ease), opacity .2s var(--ease)' };
  return (
    <button onClick={onClick} aria-label={open ? 'Close menu' : 'Open menu'} aria-expanded={open} aria-controls="vg-mobile-nav"
      style={{ display: 'none', flexDirection: 'column', gap: 5, background: 'rgba(0,229,255,.06)', border: '1px solid var(--c-line-strong)', clipPath: 'polygon(8px 0,100% 0,100% calc(100% - 8px),calc(100% - 8px) 100%,0 100%,0 8px)', padding: '11px 10px', cursor: 'pointer' }}
      className="vg-burger">
      <span style={{ ...bar, transform: open ? 'translateY(7px) rotate(45deg)' : 'none' }} />
      <span style={{ ...bar, opacity: open ? 0 : 1 }} />
      <span style={{ ...bar, transform: open ? 'translateY(-7px) rotate(-45deg)' : 'none' }} />
    </button>
  );
}

function NavBar({ route, go }) {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => { setOpen(false); }, [route]);
  const nav = (id) => { go(id); setOpen(false); };
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 40, background: 'rgba(5,11,18,.82)', backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)', borderBottom: '1px solid var(--c-line)' }}>
      <div style={{ ...wrap, display: 'flex', alignItems: 'center', gap: 20, height: 72 }}>
        <button onClick={() => nav('home')} aria-label="VE GAMERZ home" style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, padding: 0 }}>
          <LogoMark size={40} /><Wordmark size={19} />
        </button>
        <nav aria-label="Primary" className="vg-desktop-nav" style={{ display: 'flex', gap: 24, marginLeft: 18 }}>
          {ROUTES.map(r => <NavLink key={r.id} label={r.label} active={route === r.id} onClick={() => nav(r.id)} />)}
        </nav>
        <div className="vg-desktop-nav" style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 14 }}>
          <Badge variant="live">Live Now</Badge>
          <Button variant="youtube" size="sm" icon="▶" href={D.YOUTUBE}>Subscribe</Button>
        </div>
        <div style={{ marginLeft: 'auto' }} className="vg-mobile-only">
          <Hamburger open={open} onClick={() => setOpen(o => !o)} />
        </div>
      </div>
      <div id="vg-mobile-nav" style={{ overflow: 'hidden', maxHeight: open ? 460 : 0, transition: 'max-height .35s var(--ease)', borderTop: open ? '1px solid var(--c-line)' : 'none', background: 'rgba(5,11,18,.96)' }}>
        <nav aria-label="Mobile" style={{ ...wrap, display: 'grid', gap: 4, padding: open ? '14px var(--wrap-pad) 20px' : '0 var(--wrap-pad)' }}>
          {ROUTES.map(r => (
            <button key={r.id} onClick={() => nav(r.id)} aria-current={route === r.id ? 'page' : undefined}
              style={{ textAlign: 'left', background: route === r.id ? 'rgba(0,229,255,.08)' : 'none', border: 'none', borderLeft: `2px solid ${route === r.id ? 'var(--c-primary)' : 'transparent'}`, cursor: 'pointer', padding: '12px 14px', fontFamily: 'var(--f-display)', fontWeight: 600, fontSize: 15, letterSpacing: '.08em', textTransform: 'uppercase', color: route === r.id ? 'var(--c-primary)' : 'var(--c-text)' }}>
              {r.label}
            </button>
          ))}
          <div style={{ display: 'flex', gap: 12, marginTop: 12, flexWrap: 'wrap' }}>
            <Button variant="youtube" size="sm" icon="▶" href={D.YOUTUBE}>Subscribe</Button>
            <Button variant="ghost" size="sm" onClick={() => nav('membership')}>Join the Squad</Button>
          </div>
        </nav>
      </div>
    </header>
  );
}

/* ── Section head + breadcrumbs ────────────────────── */
function SectionHead({ eyebrow, title, sub, align = 'left', style = {} }) {
  return (
    <div style={{ marginBottom: 38, maxWidth: '62ch', marginInline: align === 'center' ? 'auto' : undefined, textAlign: align, ...style }}>
      {eyebrow ? <div style={{ marginBottom: 14, display: 'flex', justifyContent: align === 'center' ? 'center' : 'flex-start' }}><Eyebrow>{eyebrow}</Eyebrow></div> : null}
      <h2 style={{ fontFamily: 'var(--f-display)', fontWeight: 700, fontSize: 'clamp(26px,4vw,40px)', textTransform: 'uppercase', letterSpacing: '-.01em', lineHeight: 1.05, margin: 0, textWrap: 'balance' }}>{title}</h2>
      {sub ? <p style={{ color: 'var(--c-muted)', marginTop: 12, fontSize: 16, lineHeight: 1.6, maxWidth: '58ch', marginInline: align === 'center' ? 'auto' : undefined, textWrap: 'pretty' }}>{sub}</p> : null}
    </div>
  );
}

function Breadcrumbs({ trail, go }) {
  return (
    <nav aria-label="Breadcrumb" style={{ ...wrap, paddingTop: 22 }}>
      <ol style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center', listStyle: 'none', margin: 0, padding: 0, fontFamily: 'var(--f-data)', fontSize: 11, letterSpacing: '.16em', textTransform: 'uppercase' }}>
        {trail.map((c, i) => {
          const last = i === trail.length - 1;
          return (
            <li key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {last
                ? <span aria-current="page" style={{ color: 'var(--c-primary)' }}>{c.label}</span>
                : <button onClick={() => go(c.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, font: 'inherit', letterSpacing: 'inherit', textTransform: 'inherit', color: 'var(--c-muted)' }}>{c.label}</button>}
              {!last ? <span aria-hidden="true" style={{ color: 'var(--c-line-strong)' }}>/</span> : null}
            </li>
          );
        })}
      </ol>
    </nav>
  );
}

/* ── Carousel (arrows + drag + snap) ───────────────── */
function Carousel({ children, ariaLabel = 'Carousel' }) {
  const ref = React.useRef(null);
  const drag = React.useRef({ down: false, x: 0, left: 0, moved: 0 });
  const [atStart, setAtStart] = React.useState(true);
  const [atEnd, setAtEnd] = React.useState(false);
  const update = React.useCallback(() => {
    const el = ref.current; if (!el) return;
    setAtStart(el.scrollLeft <= 2);
    setAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - 2);
  }, []);
  React.useEffect(() => { update(); const el = ref.current; if (!el) return; el.addEventListener('scroll', update, { passive: true }); window.addEventListener('resize', update); return () => { el.removeEventListener('scroll', update); window.removeEventListener('resize', update); }; }, [update]);
  const step = (dir) => { const el = ref.current; if (!el) return; const card = el.querySelector('[data-slide]'); const d = (card ? card.offsetWidth + 20 : el.clientWidth * 0.8) * dir; el.scrollBy({ left: d, behavior: 'smooth' }); };
  const onDown = (e) => { const el = ref.current; drag.current = { down: true, x: e.clientX, left: el.scrollLeft, moved: 0 }; el.setPointerCapture && el.setPointerCapture(e.pointerId); };
  const onMove = (e) => { if (!drag.current.down) return; const dx = e.clientX - drag.current.x; drag.current.moved = Math.abs(dx); ref.current.scrollLeft = drag.current.left - dx; };
  const onUp = () => { drag.current.down = false; };
  const arrow = (side, disabled, onClick) => (
    <button onClick={onClick} disabled={disabled} aria-label={side === 'l' ? 'Previous' : 'Next'}
      style={{ position: 'absolute', top: '50%', [side === 'l' ? 'left' : 'right']: -6, transform: 'translateY(-50%)', zIndex: 3, width: 44, height: 44, display: 'grid', placeItems: 'center', cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.3 : 1, background: 'rgba(5,11,18,.85)', color: 'var(--c-primary)', border: '1px solid var(--c-line-strong)', clipPath: 'polygon(8px 0,100% 0,100% calc(100% - 8px),calc(100% - 8px) 100%,0 100%,0 8px)', boxShadow: disabled ? 'none' : 'var(--glow-sm)', fontSize: 18 }} className="vg-carousel-arrow">
      {side === 'l' ? '‹' : '›'}
    </button>
  );
  return (
    <div style={{ position: 'relative' }} role="group" aria-label={ariaLabel} aria-roledescription="carousel">
      {arrow('l', atStart, () => step(-1))}
      {arrow('r', atEnd, () => step(1))}
      <div ref={ref} onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp} onClickCapture={(e) => { if (drag.current.moved > 6) { e.preventDefault(); e.stopPropagation(); } }}
        style={{ display: 'grid', gridAutoFlow: 'column', gridAutoColumns: 'minmax(300px,1fr)', gap: 20, overflowX: 'auto', scrollSnapType: 'x mandatory', scrollbarWidth: 'none', padding: '6px 2px 18px', cursor: 'grab', touchAction: 'pan-y' }} className="vg-carousel-track">
        {React.Children.map(children, (ch, i) => <div data-slide key={i} style={{ scrollSnapAlign: 'start' }}>{ch}</div>)}
      </div>
    </div>
  );
}

/* ── Stat counter (count-up on view) ───────────────── */
function StatCounter({ value, suffix = '', decimals = 0, label }) {
  const { StatCard } = window.VEGAMERZDesignSystem_63bcb5;
  const [ref, seen] = useInView({ threshold: 0.4 });
  const n = useCountUp(value, { decimals, run: seen });
  return <div ref={ref}><StatCard value={<span>{n}{suffix}</span>} label={label} /></div>;
}

/* ── Social row ────────────────────────────────────── */
function SocialRow({ size = 'md' }) {
  const big = size === 'lg';
  return (
    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
      {D.SOCIAL.map(s => (
        <a key={s.id} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.label + ' ' + s.handle}
          style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none', padding: big ? '12px 16px' : '9px 13px', background: 'rgba(0,229,255,.06)', border: '1px solid var(--c-line-strong)', clipPath: 'polygon(9px 0,100% 0,100% calc(100% - 9px),calc(100% - 9px) 100%,0 100%,0 9px)', color: 'var(--c-text)', transition: 'all var(--dur-btn) var(--ease)' }}
          onMouseEnter={e => { e.currentTarget.style.background = 'rgba(0,229,255,.12)'; e.currentTarget.style.boxShadow = 'var(--glow-sm)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(0,229,255,.06)'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
          <span aria-hidden="true" style={{ color: 'var(--c-primary)', fontSize: big ? 18 : 15 }}>{s.glyph}</span>
          <span style={{ display: 'grid', lineHeight: 1.15 }}>
            <span style={{ fontFamily: 'var(--f-display)', fontWeight: 600, fontSize: big ? 15 : 13, letterSpacing: '.06em', textTransform: 'uppercase' }}>{s.label}</span>
            <span style={{ fontFamily: 'var(--f-data)', fontSize: 11, color: 'var(--c-muted)' }}>{s.handle}</span>
          </span>
        </a>
      ))}
    </div>
  );
}

/* ── Background + footer ───────────────────────────── */
function SiteBackground() {
  return <div aria-hidden="true" style={{ position: 'fixed', inset: 0, zIndex: 0, pointerEvents: 'none', background: ['radial-gradient(600px 400px at 15% -5%,rgba(0,229,255,.10),transparent 60%)', 'radial-gradient(700px 500px at 100% 10%,rgba(0,184,212,.10),transparent 55%)', 'linear-gradient(transparent 96%,rgba(0,229,255,.05) 96%) 0 0/100% 34px', 'linear-gradient(90deg,transparent 96%,rgba(0,229,255,.05) 96%) 0 0/34px 100%'].join(',') }} />;
}

function Footer({ go }) {
  return (
    <footer style={{ borderTop: '1px solid var(--c-line)', padding: '52px 0 60px', position: 'relative', zIndex: 1, marginTop: 40 }}>
      <div style={{ ...wrap, display: 'grid', gap: 28 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.4fr) repeat(2,minmax(0,1fr))', gap: 32 }} className="vg-footer-grid">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <LogoMark size={46} />
              <div><Wordmark size={22} /><div style={{ fontFamily: 'var(--f-data)', fontSize: 11, letterSpacing: '.32em', color: 'var(--c-muted)', textTransform: 'uppercase', marginTop: 7 }}>Play · Create · Dominate</div></div>
            </div>
            <p style={{ color: 'var(--c-muted)', fontSize: 14, lineHeight: 1.6, marginTop: 16, maxWidth: '42ch' }}>A growing gaming creator and a community that plays together. Never miss a drop from the squad.</p>
          </div>
          <nav aria-label="Footer">
            <h3 style={{ fontFamily: 'var(--f-data)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--c-dim)', margin: '0 0 14px' }}>// Explore</h3>
            <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 10 }}>
              {ROUTES.map(r => <li key={r.id}><button onClick={() => go(r.id)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--c-muted)', fontFamily: 'var(--f-body)', fontSize: 14 }} onMouseEnter={e => e.currentTarget.style.color = 'var(--c-primary)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--c-muted)'}>{r.label}</button></li>)}
            </ul>
          </nav>
          <div>
            <h3 style={{ fontFamily: 'var(--f-data)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--c-dim)', margin: '0 0 14px' }}>// Connect</h3>
            <SocialRow />
          </div>
        </div>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid var(--c-line)', paddingTop: 22 }}>
          <p style={{ color: 'var(--c-dim)', fontSize: 12, fontFamily: 'var(--f-data)', letterSpacing: '.1em', margin: 0 }}>© 2026 VE GAMERZ · ALL RIGHTS RESERVED</p>
          <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            <Button variant="ghost" size="sm" onClick={() => go('videos')}>Browse Videos</Button>
            <Button variant="primary" size="sm" onClick={() => go('membership')}>Join the Squad</Button>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* Notched panel helper used across pages. */
function Panel({ children, style = {}, glow = false, hover = false }) {
  const [h, setH] = React.useState(false);
  return (
    <div onMouseEnter={() => hover && setH(true)} onMouseLeave={() => hover && setH(false)}
      style={{ background: 'var(--grad-panel)', border: `1px solid ${h ? 'var(--c-line-strong)' : 'var(--c-line)'}`, clipPath: 'polygon(var(--notch) 0,100% 0,100% calc(100% - var(--notch)),calc(100% - var(--notch)) 100%,0 100%,0 var(--notch))', padding: 24, boxShadow: h ? 'var(--glow-md)' : (glow ? 'var(--glow-sm)' : 'none'), transform: h ? 'translateY(-4px)' : 'none', transition: 'all var(--dur-card) var(--ease)', ...style }}>
      {children}
    </div>
  );
}

window.VG = {
  wrap, NOTCH, ROUTES, useReducedMotion, useInView, Reveal, useCountUp,
  LogoMark, Wordmark, NavBar, SectionHead, Breadcrumbs, Carousel, StatCounter,
  SocialRow, SiteBackground, Footer, Panel
};
