/* global React, spriteStyle, fmtUsd */
// Browsing never places a bet. Five worlds share base reels and each has its own bonus adventure.
function SlotPicker(props) {
  const themes = window.SLOT_THEMES;
  const [selected, setSelected] = React.useState(function () {
    return Math.max(0, themes.findIndex(function (t) { return t.id === props.themeId; }));
  });
  const rootRef = React.useRef(null);
  const touchRef = React.useRef(null);
  const timerRef = React.useRef(null);
  const swipeRef = React.useRef(false);
  const [entering, setEntering] = React.useState(false);
  const theme = themes[selected];
  function compactCredits(n) {
    if (n >= 1000000000) return (n / 1000000000).toFixed(1) + 'B';
    if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
    if (n >= 10000) return (n / 1000).toFixed(1) + 'K';
    return n.toLocaleString();
  }
  function choose(i) {
    if (entering) return;
    setSelected(i);
    if (window.SLOT_SFX && window.SLOT_SFX.feature) window.SLOT_SFX.feature(themes[i].id, 'browse');
  }
  function move(dir) { choose((selected + dir + themes.length) % themes.length); }
  function enter() {
    if (entering) return;
    setEntering(true);
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    timerRef.current = setTimeout(function () { props.onPlay(theme.id); }, reduced ? 0 : 460);
  }
  React.useEffect(function () { return function () { clearTimeout(timerRef.current); }; }, []);
  React.useEffect(function () { if (rootRef.current) rootRef.current.focus({ preventScroll: true }); }, []);
  function key(e) {
    if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
      e.preventDefault(); move(e.key === 'ArrowLeft' ? -1 : 1);
    }
  }
  function endTouch(e) {
    const start = touchRef.current;
    touchRef.current = null;
    if (!start || !e.changedTouches.length) return;
    const end = e.changedTouches[0];
    const dx = end.clientX - start.x, dy = end.clientY - start.y;
    if (Math.abs(dx) > 35 && Math.abs(dx) > Math.abs(dy)) { swipeRef.current = true; move(dx < 0 ? 1 : -1); }
  }
  return (
    <div className={'slot-root slot-picker world-' + theme.id + ' picker-' + props.mode + (entering ? ' picker-entering' : '')}
      ref={rootRef} tabIndex={-1} style={{ minHeight: props.height + 'px', '--picker-accent': theme.accent }} onKeyDown={key}>
      <SlotWorld theme={theme} />
      <div className="picker-rail">
        <a className="slot-back" href="../casino/">← Lobby</a>
        <span className="picker-rail-label">LIMESTONE SLOTS</span>
        <div className="slot-bank"><button type="button" className="picker-sound" aria-label="Sound" aria-pressed={props.soundOn} onClick={props.onSound}>{props.soundOn ? 'Sound on' : 'Sound off'}</button><span className="slot-bank-amt">{fmtUsd(props.bankroll)}</span>
          <a className="picker-profile" href="/profile/" aria-label="Player Profile" title="Player Profile"><span>{props.playerName ? props.playerName.charAt(0).toUpperCase() : '♟'}</span>{props.mode === 'desktop' ? (props.playerName || 'Profile') : null}</a></div>
      </div>
      <div className="picker-heading">
        <h2>Pick your machine.</h2><span>Five worlds. Find your favorite.</span></div>
      <div className="picker-showroom"><div className="picker-gallery">
      <div className="picker-carousel" role="region" aria-roledescription="carousel" aria-label="Choose a slot machine"
        onTouchStart={function (e) { swipeRef.current = false; if (e.touches.length === 1) touchRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; }}
        onTouchEnd={endTouch} onTouchCancel={function () { touchRef.current = null; }}>
        {themes.map(function (t, i) {
          const offset = ((i - selected + 7) % 5) - 2;
          const active = offset === 0;
          return <button type="button" key={t.id}
            className={'picker-machine machine-' + t.id + ' position-' + offset + (active ? ' selected' : '')}
            style={{ '--machine-accent': t.accent, '--machine-deep': t.accentDim }}
            aria-label={active ? 'Play ' + t.name + ' machine' : t.name + ', preview machine'}
            aria-pressed={active} tabIndex={active ? 0 : -1}
            onClick={function () { if (swipeRef.current) { swipeRef.current = false; return; } if (active) enter(); else choose(i); }}>
            <span className="picker-cabinet">
              <SlotShell theme={t} />
              <span className="picker-marquee"><i className="picker-hero-art" /><span className="picker-crest">{t.mark}</span><small>LIMESTONE</small><strong>{t.name}</strong></span>
              <span className="picker-wild"><span>WILD JACKPOT</span><strong>{window.SLOT_ENGINE.PAYOUTS[window.SLOT_ENGINE.WILD]}×</strong></span>
              <span className="picker-preview" aria-hidden="true">
                {[0, 2, 5].map(function (sym, r) {
                  return <span className="picker-reel" key={r}><span className="picker-symbol-track">
                    {[(sym + 5) % 6, sym, (sym + 1) % 6, (sym + 5) % 6, sym, (sym + 1) % 6].map(function (v, k) {
                      return <span key={k} className="slot-pt-sym" style={spriteStyle(v, t.spriteRow, 70)} />;
                    })}
                  </span></span>;
                })}
              </span>
              <span className="picker-meters" aria-hidden="true"><span><small>CREDITS</small><b>{compactCredits(props.bankroll)}</b></span><span><small>BET</small><b>{props.bet || 5}</b></span><span><small>WIN</small><b>—</b></span></span>
              <span className="picker-control-deck" aria-hidden="true"><span className="picker-coin-slot"><i /><small>FREE PLAY</small></span><span className="picker-mini-spin">SPIN</span></span>
              <span className="picker-base">{t.feature}</span>
              <span className="picker-service-door" aria-hidden="true"><span>{t.mark}</span><i /></span>
              <span className="picker-coin-tray" aria-hidden="true"><i /><i /><i /></span>
            </span>
            <span className="picker-sidewall" aria-hidden="true" />
            <span className="picker-handle cabinet-preview-lever" aria-hidden="true" style={{'--metal-hi':t.accent,'--metal-mid':t.accentDim,'--metal-dark':'#17212b'}}><SlotHandleParts /></span>
            <span className="picker-plinth" aria-hidden="true" />
          </button>;
        })}
      </div>
      <div className="picker-navigation">
        <button type="button" className="picker-arrow" aria-label="Previous machine" onClick={function () { move(-1); }}>←</button>
        <div className="picker-dots" aria-label="Machine shortcuts">
          {themes.map(function (t, i) { return <button type="button" key={t.id} aria-label={'Preview ' + t.name} title={t.name}
            aria-pressed={i === selected} className={i === selected ? 'active' : ''} onClick={function () { choose(i); }}>{t.mark}</button>; })}
        </div>
        <button type="button" className="picker-arrow" aria-label="Next machine" onClick={function () { move(1); }}>→</button>
      </div>
      <p className="picker-browse-hint">{props.mode === 'desktop' ? 'Click the front machine to play · Arrows to browse' : 'Tap the front machine to play · Swipe to browse'}</p>
      </div>
      <div className="picker-selection">
        <div className="picker-caption" aria-live="polite" aria-atomic="true"><span>MACHINE {('0' + (selected + 1)).slice(-2)} / 05</span><h3>{theme.name}</h3><p>{theme.reelRule}</p></div>
        <div className="picker-actions">
          <button type="button" className="picker-play" aria-label={'Play ' + theme.name} disabled={entering} onClick={enter}>{entering ? 'Entering…' : 'Play now'} <span>→</span></button>
          <button type="button" className="picker-demo" disabled={entering} onClick={function () { props.onDemo(theme.id); }}>Try bonus</button>
        </div>
        <div className="picker-feature"><span>{theme.mark}</span><div><small>EXCLUSIVE BONUS</small><strong>{theme.feature}</strong><p>{theme.featureDesc}</p><em>{theme.featureTag}</em></div></div>
        <p className="picker-note">Play money. One shared bankroll.</p>
        <p className="picker-hint">Bonus chance: 1 in 25 paid spins.</p>
      </div></div>
    </div>
  );
}
