// Tobeads — Homepage (pixel arcade)
// Boot → Hero → Select Mode → How to Play → Product preview → Creator bar → Footer

const { useState: useStateHome, useEffect: useEffectHome, useRef: useRefHome } = React;

function HomePage({ onNavigate, addToCart }) {
  const [entered, setEntered] = useStateHome(() => {
    try { return sessionStorage.getItem('tobeads.booted') === '1'; } catch (e) { return false; }
  });
  function finishEntry() {
    setEntered(true);
    try { sessionStorage.setItem('tobeads.booted', '1'); } catch (e) {}
    // Land at the top so the hero logo + full arcade preview are visible on mobile
    requestAnimationFrame(() => window.scrollTo(0, 0));
  }

  return (
    <div data-screen-label="01 Home" className={`aw-stage ${!entered ? 'aw-stage-entry' : ''}`}>
      {!entered && window.ArcadeEntry && <window.ArcadeEntry onEnter={finishEntry}/>}
      {entered && (
        <>
          <window.ArcadeHero onNavigate={onNavigate}/>
          <SelectMode onNavigate={onNavigate}/>
          {window.VideoCarousel && <window.VideoCarousel light={true}/>}
          <HowToPlay/>
          <ProductPreview onNavigate={onNavigate} addToCart={addToCart}/>
          <window.ArcadeFooter onNavigate={onNavigate}/>
        </>
      )}
    </div>
  );
}
window.HomePage = HomePage;

// ============ SELECT MODE ============
const MODES = [
  { id: 'quickstart', n: '01', route: 'quickstart', title: 'Quick Start', sub: '30-minute bead builds.', tag: '~30 MIN · 1 BUILD', stat: 'EASY', bars: 1, icon: 'Bolt', acc: 'var(--ylw)' },
  { id: 'presets',    n: '02', route: 'presets',    title: 'Preset World', sub: 'Ready-made bead kits.', tag: '50×50 · PACKED BOX', stat: 'POPULAR', bars: 2, icon: 'Grid', acc: 'var(--cyn)' },
  { id: 'create',     n: '03', route: 'create',     title: 'Creator Mode', sub: 'Upload. Pixelize. Build.', tag: 'ANY PHOTO → MAP', stat: 'PRO', bars: 3, icon: 'Sparkle', acc: 'var(--pnk)' },
];

function SelectMode({ onNavigate }) {
  const [sel, setSel] = useStateHome(0);
  const selRef = useRefHome(0); selRef.current = sel;
  const ref = useRefHome(null);
  const slotsRef = useRefHome(null);
  const scrollSyncRef = useRefHome(false);

  function scrollToSlot(i, smooth) {
    const row = slotsRef.current;
    const card = row && row.children[i];
    if (!card) return;
    scrollSyncRef.current = true;
    card.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto', inline: 'center', block: 'nearest' });
    window.setTimeout(() => { scrollSyncRef.current = false; }, smooth ? 420 : 60);
  }

  useEffectHome(() => {
    const row = slotsRef.current;
    if (!row) return;
    function onScroll() {
      if (scrollSyncRef.current) return;
      const cards = row.children;
      if (!cards.length) return;
      const mid = row.scrollLeft + row.clientWidth / 2;
      let best = 0, bestDist = Infinity;
      for (let i = 0; i < cards.length; i++) {
        const c = cards[i];
        const center = c.offsetLeft + c.offsetWidth / 2;
        const d = Math.abs(center - mid);
        if (d < bestDist) { bestDist = d; best = i; }
      }
      if (best !== selRef.current) {
        window.AudioManager && window.AudioManager.playHover();
        setSel(best);
      }
    }
    row.addEventListener('scroll', onScroll, { passive: true });
    return () => row.removeEventListener('scroll', onScroll);
  }, []);

  useEffectHome(() => {
    let active = false;
    const io = new IntersectionObserver(([e]) => { active = e.isIntersecting; }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    function onKey(e) {
      if (!active) return;
      if (e.key === 'ArrowRight') {
        e.preventDefault();
        window.AudioManager && window.AudioManager.playHover();
        setSel(s => { const n = (s + 1) % MODES.length; scrollToSlot(n, true); return n; });
      } else if (e.key === 'ArrowLeft') {
        e.preventDefault();
        window.AudioManager && window.AudioManager.playHover();
        setSel(s => { const n = (s - 1 + MODES.length) % MODES.length; scrollToSlot(n, true); return n; });
      } else if (e.key === 'Enter') { window.AudioManager && window.AudioManager.playSelect(); onNavigate(MODES[selRef.current].route); }
    }
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('keydown', onKey); io.disconnect(); };
  }, []);

  const active = MODES[sel];

  return (
    <section id="modes" ref={ref} className="home-modes" style={{ minHeight: '82vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '56px 24px', position: 'relative' }}>
      <div className="ms-wrap" style={{ position: 'relative', margin: '0 auto' }}>
        {/* outer label on the light page */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, marginBottom: 18 }}>
          <div className="aw-eyebrow" style={{ color: 'var(--ink2)' }}><span className="blk" style={{ background: 'var(--v)' }}/>GAME SELECT</div>
          <span className="px" style={{ fontSize: 8, color: 'var(--ink2)' }}>INSERT BEAD · CHOOSE A MODE</span>
        </div>

        {/* arcade monitor: bezel + pixel corner brackets wrapping the screen */}
        <div className="ms-bezel ms-handheld">
          <div className="ms-screen">
          {/* top status row */}
          <div className="ms-hud">
            <span className="ms-hud-l"><span className="ms-led"/>GAME SELECT</span>
            <span className="ms-hud-c">
              <span style={{ color: 'var(--scr-cyan)' }}>3 MODES</span>
              <span style={{ opacity: 0.4 }}>·</span>
              <span style={{ color: 'var(--wh)' }}>1 PLAYER</span>
            </span>
            <span style={{ color: 'var(--ylw)' }}>CREDIT 01</span>
          </div>

          <div className="ms-swipe-hint aw-only-mob" aria-hidden="true">
            <span className="ms-swipe-arrow">◀</span>
            <span className="px ms-swipe-label blink">SWIPE TO BROWSE</span>
            <span className="ms-swipe-arrow">▶</span>
          </div>

          <div className="ms-slots-wrap">
          <div className="ms-slots" ref={slotsRef}>
            {MODES.map((m, i) => {
              const Icon = window.Icon[m.icon];
              const on = sel === i;
              return (
                <div
                  key={m.id}
                  className={`ms-slot ${on ? 'on' : ''}`}
                  style={{ '--mc': m.acc }}
                  onMouseEnter={() => { if (!on) { window.AudioManager && window.AudioManager.playHover(); setSel(i); } }}
                  onClick={() => { window.AudioManager && window.AudioManager.playSelect(); onNavigate(m.route); }}
                >
                  <div className="ms-cursor" style={{ color: m.acc }}>▼</div>
                  <div className="ms-slot-top">
                    <div className="ms-num" style={{ color: m.acc }}>{m.n}</div>
                    <span className="ms-stat px" style={{ color: m.acc, borderColor: m.acc }}>{m.stat}</span>
                  </div>
                  <div className="ms-sprite" style={{ borderColor: m.acc, color: m.acc, boxShadow: on ? `0 0 18px -2px ${m.acc}, inset 0 0 16px -6px ${m.acc}` : 'none' }}>
                    <Icon size={34}/>
                  </div>
                  <h3 className="px ms-title">{m.title}</h3>
                  <p className="ms-sub">{m.sub}</p>
                  <div className="ms-tag px" style={{ color: m.acc }}>{m.tag}</div>
                  {/* difficulty bars */}
                  <div className="ms-bars" aria-hidden="true">
                    {[0,1,2].map(k => (
                      <span key={k} style={{ background: k < m.bars ? m.acc : 'rgba(255,255,255,0.12)', boxShadow: k < m.bars ? `0 0 6px ${m.acc}` : 'none' }}/>
                    ))}
                  </div>
                  {/* mini stage-preview bead row for density */}
                  <div className="ms-dots" aria-hidden="true">
                    {Array.from({ length: 12 }).map((_, k) => (
                      <span key={k} style={{ background: (k % 4 === i % 4 || (on && k % 3 === 0)) ? m.acc : 'rgba(255,255,255,0.14)' }}/>
                    ))}
                  </div>
                  <div className="ms-play px" style={{ color: m.acc, opacity: on ? 1 : 0.35 }}>▶ PLAY</div>
                </div>
              );
            })}
          </div>
          </div>

          <div className="ms-pager aw-only-mob" role="tablist" aria-label="Game modes">
            {MODES.map((m, i) => (
              <button
                key={m.id}
                type="button"
                role="tab"
                aria-selected={sel === i}
                aria-label={m.title}
                className={`ms-pager-dot ${sel === i ? 'on' : ''}`}
                style={sel === i ? { borderColor: m.acc, background: m.acc, boxShadow: `0 0 8px ${m.acc}` } : undefined}
                onClick={() => {
                  window.AudioManager && window.AudioManager.playHover();
                  setSel(i);
                  scrollToSlot(i, true);
                }}
              />
            ))}
          </div>

          {/* bottom instruction row */}
          <div className="ms-foot">
            <span className="aw-hide-mob">◀ ▶ <span style={{ color: 'var(--scr-cyan)' }}>MOVE</span></span>
            <span className="aw-hide-mob">⏎ / CLICK <span style={{ color: 'var(--ylw)' }}>SELECT</span></span>
            <span className="aw-only-mob px" style={{ color: 'var(--scr-cyan)' }}>SWIPE ◀ ▶ · TAP CARD TO PLAY</span>
            <span className="blink aw-hide-mob" style={{ color: 'var(--ylw)' }}>PRESS START</span>
          </div>

          {/* scanline overlay */}
          <div className="ms-scan"/>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ HOW TO PLAY (light section) ============
function HowToPlay() {
  const steps = [
    { n: '1', title: 'CHOOSE MODE', body: 'Quick Start, Preset World, or Creator Mode.', acc: 'var(--ylw)' },
    { n: '2', title: 'GET BEAD MAP', body: 'We generate the pattern, colors & bead count.', acc: 'var(--cyn)' },
    { n: '3', title: 'BUILD IT IRL', body: 'A physical kit ships. You build the real thing.', acc: 'var(--pnk)' },
  ];
  return (
    <section className="sec-light sec-light-grid" style={{ padding: '80px 24px 84px' }}>
      <div className="wrap">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 34 }}>
          <div>
            <div className="aw-eyebrow" style={{ color: 'var(--ink2)' }}><span className="blk" style={{ background: 'var(--v)' }}/>HOW IT WORKS</div>
            <h2 className="px" style={{ fontSize: 'clamp(16px,2.6vw,26px)', color: 'var(--ink)', marginTop: 16 }}>HOW TO PLAY</h2>
          </div>
          <span className="px" style={{ fontSize: 8, color: 'var(--ink2)' }}>3 STEPS · NO BOSS</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }} className="aw-steps-grid">
          {steps.map((s, i) => (
            <div key={s.n} className="lt-step" style={{ padding: 24, boxShadow: `5px 5px 0 0 ${s.acc}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span className="aw-step-num" style={{ background: s.acc, color: 'var(--ink)', borderColor: 'var(--ink)' }}>{s.n}</span>
                {i < 2 && <span className="aw-hide-mob" style={{ flex: 1, height: 3, background: `repeating-linear-gradient(90deg, ${s.acc} 0 6px, transparent 6px 12px)` }}/>}
              </div>
              <h3 className="px" style={{ fontSize: 12, marginTop: 18, color: 'var(--ink)' }}>{s.title}</h3>
              <p className="aw-disp" style={{ fontSize: 15, color: 'var(--ink2)', marginTop: 10, lineHeight: 1.45 }}>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
      <style>{`@media (max-width: 760px){ .aw-steps-grid { grid-template-columns: 1fr !important; gap: 18px !important; } }`}</style>
    </section>
  );
}

// ============ PRODUCT PREVIEW (light · game-cartridge cards) ============
function ProductPreview({ onNavigate, addToCart }) {
  const items = [
    { id: 'qs-30', seed: 'starter-48', title: '30-MIN BEAD KIT', line: 'One small build. Done today.', price: 18, beads: 540, route: 'quickstart', acc: 'var(--ylw)' },
    { id: 'preset', seed: 'creator-96', title: 'READY-MADE WORLD', line: 'A curated bead map, packed.', price: 34, beads: 2500, route: 'presets', acc: 'var(--cyn)' },
    { id: 'custom', seed: 'custom-kit', title: 'CUSTOM PHOTO KIT', line: 'Your photo → bead map.', price: 38, beads: 4800, route: 'create', acc: 'var(--pnk)' },
  ];
  return (
    <section className="sec-light home-pick-build" style={{ padding: '8px 24px 88px' }}>
      <div className="wrap">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 28 }}>
          <h2 className="px" style={{ fontSize: 'clamp(16px,2.6vw,26px)', color: 'var(--ink)' }}>PICK A BUILD</h2>
          <button onClick={() => onNavigate('presets')} className="pbtn pbtn-sm" style={{ background: 'var(--lt2)', color: 'var(--ink)', borderColor: 'var(--ink)', boxShadow: '3px 3px 0 var(--v)' }}>
            ALL KITS <window.Icon.Arrow size={12}/>
          </button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }} className="aw-prod-grid">
          {items.map(it => (
            <div key={it.id} className="lt-card" style={{ overflow: 'hidden' }}>
              {/* cartridge screen */}
              <div className="cart-scan" style={{ aspectRatio: '4/3', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#05050F', borderBottom: '3px solid var(--ink)' }}>
                <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(60% 60% at 50% 45%, ${it.acc}2E, transparent 70%)` }}/>
                <div style={{ width: '50%', position: 'relative' }}><window.PixelArt seed={it.seed} size={12}/></div>
                <span className="px hh-badge" style={{ position: 'absolute', top: 10, left: 10, fontSize: 8, color: it.acc, border: `2px solid ${it.acc}`, padding: '4px 6px' }}>{it.beads} BEADS</span>
              </div>
              <div style={{ padding: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <h3 className="px" style={{ fontSize: 11, color: 'var(--ink)' }}>{it.title}</h3>
                  <span className="px" style={{ fontSize: 13, color: 'var(--v)' }}>${it.price}</span>
                </div>
                <p className="aw-disp" style={{ fontSize: 14, color: 'var(--ink2)', marginTop: 10 }}>{it.line}</p>
                <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
                  <button onClick={() => { window.AudioManager && window.AudioManager.playSelect(); addToCart({ id: it.id, title: it.title, estimatedPrice: it.price }); }} className="pbtn pbtn-ylw pbtn-sm" style={{ flex: 1 }}>ADD</button>
                  <button onClick={() => onNavigate(it.route)} className="pbtn pbtn-sm" style={{ background: 'var(--lt2)', color: 'var(--ink)', borderColor: 'var(--ink)', boxShadow: '3px 3px 0 var(--ink)' }}>PLAY</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ FOOTER ============
function ArcadeFooter({ onNavigate }) {
  return (
    <footer style={{ marginTop: 0, borderTop: '3px solid var(--ink)', background: 'var(--lt2)' }}>
      <div className="wrap" style={{ padding: '48px 24px 36px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 28 }}>
          <div style={{ maxWidth: 300 }}>
            <window.TobeadsMark size={26} onLight/>
            <p className="aw-disp" style={{ marginTop: 16, fontSize: 14, color: 'var(--ink2)', lineHeight: 1.5 }}>
              Pixel play, made physical. 
              <br/>Beads → Maps → Kits.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 48, flexWrap: 'wrap' }}>
            <FooterCol title="PLAY" links={[['Quick Start','quickstart'],['Preset World','presets'],['Creator Mode','create'],['Gallery','gallery']]} onNavigate={onNavigate}/>
            <FooterCol title="BRAND" links={[['About','home'],['Sustainability','home'],['Contact','home']]} onNavigate={onNavigate}/>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 44, paddingTop: 22, borderTop: '3px solid var(--lt3)', flexWrap: 'wrap', gap: 12 }}>
          <span className="px" style={{ fontSize: 8, color: 'var(--ink2)' }}>© 2026 TOBEADS</span>
          <span className="px blink" style={{ fontSize: 8, color: 'var(--pnk)' }}>● INSERT COIN</span>
        </div>
      </div>
    </footer>
  );
}
window.ArcadeFooter = ArcadeFooter;

function FooterCol({ title, links, onNavigate }) {
  return (
    <div>
      <div className="px" style={{ fontSize: 9, color: 'var(--v)', marginBottom: 16 }}>{title}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {links.map(([label, route]) => (
          <li key={label}><a href="#" onClick={(e) => { e.preventDefault(); onNavigate(route); }} className="aw-disp" style={{ fontSize: 14, color: 'var(--ink2)' }}>{label}</a></li>
        ))}
      </ul>
    </div>
  );
}
