/* global React */
function SlotWorld(props) {
  return <div className={'slot-world world-' + props.theme.id} aria-hidden="true">
    <div className="slot-world-art" />
    <div className="slot-world-vignette" />
    <div className="slot-world-motes">{[0, 1, 2, 3, 4, 5, 6, 7].map(function (n) {
      return <i key={n} style={{ left: (8 + n * 12) + '%', animationDelay: (-n * 1.7) + 's', animationDuration: (12 + n % 3 * 4) + 's' }} />;
    })}</div>
    <div className="slot-world-floor" />
  </div>;
}

function SlotBonus(props) {
  const r = props.round;
  const theme = window.SLOT_THEMES.find(function (t) { return t.id === r.themeId; });
  const rootRef = React.useRef(null);
  const resultRef = React.useRef(null);
  const actionRef = React.useRef(props.onAction);
  actionRef.current = props.onAction;
  React.useEffect(function () {
    window.scrollTo(0,0);
    if (rootRef.current) rootRef.current.focus({ preventScroll: true });
  }, [r.id]);
  React.useEffect(function () {
    if (r.phase !== 'wheel') return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const ticks = [];
    if (!reduced && window.SLOT_SFX) {
      [0,65,140,225,320,430,560,710,880,1070,1280,1510,1760,2030].forEach(function (ms) {
        ticks.push(setTimeout(function () { window.SLOT_SFX.feature('classic','wheel'); },ms));
      });
    }
    const timer = setTimeout(function () { actionRef.current({ type: 'reveal' }); }, reduced ? 120 : 2300);
    return function () { clearTimeout(timer); ticks.forEach(clearTimeout); };
  }, [r.phase, r.id]);
  React.useEffect(function () {
    if (r.phase === 'complete' && resultRef.current) {
      resultRef.current.focus({ preventScroll: true });
      if (window.LGFeedback) window.LGFeedback.mount(resultRef.current);
    }
  }, [r.phase]);
  function action(type, index) { props.onAction({ type: type, index: index }); }
  const count = r.themeId === 'neon' ? r.beats.length : r.picks.length;
  const score = r.score * r.bet;
  return <div className={'slot-root slot-bonus bonus-' + theme.id + ' bonus-' + props.mode + ' phase-' + r.phase}
    style={{ minHeight: props.height + 'px', '--accent': theme.accent }}>
    <SlotWorld theme={theme} />
    <div className="bonus-top"><span className="bonus-wordmark">LIMESTONE / {theme.name.toUpperCase()}</span>
      <span className="bonus-mode">{r.demo ? 'FREE PRACTICE · NO CHIPS AT STAKE' : 'BONUS ROUND · NO EXTRA BET'}</span><button type="button" className="picker-sound" aria-label="Sound" aria-pressed={props.soundOn} onClick={props.onSound}>{props.soundOn ? 'Sound on' : 'Sound off'}</button></div>
    <div className="bonus-content" ref={rootRef} tabIndex={-1}>
      <div className="bonus-heading">{r.themeId === 'classic' ? <span className="bonus-emblem">{theme.mark}</span> : <span className="bonus-art-emblem" aria-hidden="true" style={spriteStyle(r.themeId === 'lucky' ? 0 : r.themeId === 'neon' ? 1 : 5,theme.spriteRow,80)} />}<p>{r.demo ? 'TRY THE FEATURE' : 'YOU UNLOCKED THE FEATURE'}</p><h2>{theme.feature}</h2><span>{theme.featureDesc}</span></div>
        {r.themeId === 'classic' && <div className="bonus-wheel-stage">
          <span className="bonus-wheel-pointer" aria-hidden="true">▼</span>
          <div className={'bonus-wheel' + (r.phase === 'wheel' || r.phase === 'complete' ? ' turning' : '')}
            style={{ '--wheel-stop': (1800 - (r.wheelIndex * 72 + 36)) + 'deg' }} aria-hidden="true">
            {r.wheel.map(function (v, i) { return <span key={i} style={{ transform: 'rotate(' + (i * 72 + 36) + 'deg) translateY(-109px)' }}>{v}×</span>; })}
            <b>✦</b>
          </div>
          {r.phase !== 'complete' && <button type="button" className="bonus-primary" disabled={r.phase === 'wheel'} onClick={function () { action('spin'); }}>{r.phase === 'wheel' ? 'Wheel in motion…' : 'Spin the golden wheel'}</button>}
        </div>}
      {r.phase === 'complete' ? <div className="bonus-result" ref={resultRef} tabIndex={-1}>
        <p>{r.shark ? 'SHARK ENCOUNTER · HALF YOUR HAUL SAVED' : r.gambled && !r.gambleWins ? 'THE DRAGON CLAIMED YOUR PRIZE' : r.demo ? 'PRACTICE COMPLETE' : 'BONUS COMPLETE'}</p>
        <div className="bonus-recap" aria-label="Bonus reveals">
          {(r.themeId === 'classic' ? [r.score] : r.themeId === 'neon' ? r.beats : r.themeId === 'mythic' ? [r.runes[r.picks[0]]] : r.picks.map(function (i) { return r.themeId === 'lucky' ? r.clovers[i] : r.seabed[i]; })).map(function (v,i) { return <span key={i}><i aria-hidden="true" className="bonus-recap-art" style={spriteStyle(r.themeId === 'neon' ? 1 : r.themeId === 'lucky' ? 3 : 5,theme.spriteRow,42)} />{v < 0 ? 'Shark' : v+'×'}</span>; })}
        </div>
        <strong>{fmtUsd(score)}</strong><span>{r.demo ? 'Practice prize only — your bankroll stays the same.' : 'Your bonus prize is ready to collect.'}</span>
        <button type="button" className="bonus-primary" onClick={props.onClose}>{r.demo ? 'Back to browsing' : 'Collect & return to reels'} →</button>
      </div> : <div className="bonus-stage">
        {r.themeId === 'lucky' && <div className="bonus-picks-stage"><p className="bonus-step">{3 - count} clover picks remaining</p>
          <div className="bonus-clovers">{r.clovers.map(function (v, i) {
            const picked = r.picks.indexOf(i) >= 0;
            return <button type="button" key={i} className={'bonus-pick clover' + (picked ? ' revealed' : '')} disabled={picked}
              aria-label={picked ? 'Clover ' + (i + 1) + ', ' + v + ' times bet' : 'Pick clover ' + (i + 1)} onClick={function () { action('pick', i); }}>
              <i aria-hidden="true" className="bonus-hidden-symbol" style={spriteStyle(picked ? 3 : 0, 1, 64)} />{picked && <span>{v + '×'}</span>}<small>{picked ? 'FOUND' : 'PICK ME'}</small></button>;
          })}</div><div className="bonus-haul">Prize so far <strong>{fmtUsd(score)}</strong></div></div>}
        {r.themeId === 'mythic' && <div className="bonus-runes-stage">
          {r.phase === 'ready' ? <><p className="bonus-step">Choose one ancient rune</p><div className="bonus-runes">{r.runes.map(function (v, i) {
            return <button type="button" key={i} className="bonus-pick rune" aria-label={'Choose rune ' + (i + 1)} onClick={function () { action('pick', i); }}><i aria-hidden="true" className="bonus-rune-art" style={spriteStyle([2,3,4][i],2,72)} /><span>{['ᚠ', 'ᛟ', 'ᛉ'][i]}</span><small>{['EMBER', 'SHADOW', 'CROWN'][i]}</small></button>;
          })}</div></> : <div className="bonus-dragon-offer"><i aria-hidden="true" className="bonus-dragon-art" style={spriteStyle(5,2,100)} /><span className="bonus-offer-value">{r.score}×</span><h3>The dragon makes an offer.</h3><p>Keep {fmtUsd(score)}, or take a 50/50 chance at {fmtUsd(score * 2)}. A loss pays zero.</p>
            <div className="bonus-actions"><button type="button" className="bonus-primary" onClick={function () { action('bank'); }}>Bank {fmtUsd(score)}</button><button type="button" className="bonus-secondary" onClick={function () { action('gamble'); }}>Risk it for double</button></div></div>}
        </div>}
        {r.themeId === 'neon' && <div className="bonus-rhythm-stage"><div className="bonus-equalizer" aria-hidden="true">{[0,1,2,3,4,5,6,7,8,9,10,11].map(function (n) { return <i key={n} style={{height:(14+(n*17)%38)+'px',animationDelay:(-n*.13)+'s'}} />; })}</div><p className="bonus-step">{r.phase === 'ready' ? 'Three pulses. Hit the center for 2× each.' : 'Pulse ' + (count + 1) + ' of 3 · hit the bright center'}</p>
          <div className="bonus-beats">{[0, 1, 2].map(function (i) { return <span key={i} className={r.beats.length > i ? 'done' : ''}>{r.beats.length > i ? r.beats[i] + '×' : '·'}</span>; })}</div>
          <div className="bonus-pulse"><span className="pulse-good" /><span className="pulse-perfect" />{r.phase === 'rhythm' && <i key={r.beatAt} className="pulse-cursor" style={{ animationDelay: '-' + ((Date.now() - r.beatAt) % 1400) + 'ms' }} />}</div>
          <p className="bonus-pulse-label">OUTSIDE 0× · INNER ZONE 1× · CENTER 2×</p>
          <button type="button" className="bonus-primary" onClick={function () { action(r.phase === 'ready' ? 'begin' : 'stop'); }}>{r.phase === 'ready' ? 'Start the pulse' : 'Stop the pulse'}</button>
          <p className="bonus-small">Timing uses a 1.4-second loop. Press Enter or tap to stop.</p></div>}
        {r.themeId === 'ocean' && <div className="bonus-ocean-stage"><p className="bonus-step">{3 - count} dives left · 2 sharks hidden in 9 sites</p>
          <div className="bonus-seabed">{r.seabed.map(function (v, i) {
            const picked = r.picks.indexOf(i) >= 0;
            return <button type="button" key={i} className={'bonus-pick dive' + (picked ? ' revealed' : '') + (picked && v < 0 ? ' shark' : '')} disabled={picked}
              aria-label={picked ? 'Site ' + (i + 1) + ', ' + v + ' times bet' : 'Dive at site ' + (i + 1)} onClick={function () { action('pick', i); }}>{picked ? <span>{v < 0 ? 'Shark' : v + '×'}</span> : <><i aria-hidden="true" className="bonus-hidden-symbol" style={spriteStyle(0, 4, 52)} /><small>{('0'+(i+1)).slice(-2)}</small></>}</button>;
          })}</div><div className="bonus-haul">Treasure aboard <strong>{fmtUsd(score)}</strong></div>
          <button type="button" className="bonus-secondary" disabled={!count} onClick={function () { action('bank'); }}>Surface & bank treasure</button>
          <p className="bonus-small">A shark ends the dive and keeps half your prize, rounded down.</p></div>}
      </div>}
      {r.demo && r.phase !== 'complete' && <button type="button" className="bonus-exit" onClick={props.onClose}>← Leave practice</button>}
      <p className="bonus-footer">{r.demo ? 'Practice never spends or awards chips.' : 'All prizes are play money. Refreshing resumes this bonus.'}</p>
    </div>
  </div>;
}
