(function(){'use strict';
let lastFocus=null,lastX=0,lastY=0,restoring=false;
function visible(el){return !!(el&&el.offsetParent!==null&&!el.disabled)}
function safeFocus(el){if(!el||typeof el.focus!=='function')return;restoring=true;try{el.focus({preventScroll:true})}catch(e){try{el.focus()}catch(_){}}window.scrollTo(lastX,lastY);setTimeout(()=>restoring=false,0)}
function editable(el){const tag=(el&&el.tagName||'').toLowerCase();return ['input','textarea','select'].includes(tag)||(el&&el.isContentEditable)}
function slug(){const m=location.pathname.match(/\/games\/([^/]+)/);return m?m[1]:''}
function setKey(el,key){if(!el||!key)return;el.dataset.key=String(key).toLowerCase();el.setAttribute('aria-keyshortcuts',String(key).toUpperCase())}
function gameplayArea(main){
  const candidates=['#playPanel','#play','#gameArea','#game-area','#game','#boardArea','#board-area'];
  for(const s of candidates){const el=document.querySelector(s);if(el)return el}
  const roll=document.querySelector('#roll,#property-roll');
  if(roll&&roll.closest('section'))return roll.closest('section');
  return main;
}
function installExplicitKeys(game){
  const maps={
    baseball:{'[data-swing="contact"]':'c','[data-swing="normal"]':'n','[data-swing="power"]':'p'},
    tennis:{'[data-shot="safe"]':'s','[data-shot="angle"]':'a','[data-shot="power"]':'p'},
    football:{'[data-play="run"]':'r','[data-play="short"]':'s','[data-play="deep"]':'d','[data-play="kick"]':'f'},
    basketball:{'[data-action="dribble"]':'d','[data-action="pass"]':'p','[data-action="pickroll"]':'k','[data-action="alleyoop"]':'a','[data-action="layup"]':'l','[data-action="dunk"]':'u','[data-action="jumper"]':'j','[data-action="three"]':'3','[data-action="halfCourt"]':'h','[data-action="rest"]':'r','[data-defense="contest"]':'c','[data-defense="block"]':'b','[data-defense="steal"]':'s','[data-defense="boxout"]':'x','#summaryButton':'g','#timeoutButton':'t','#saveGameButton':'v','#resumeGameButton':'o'},
    'bv-echo':{'#endTurn':'t','#echo':'e','#inspect':'i','#share':'s','#ready':'c','#ability':'a','#resonance':'d','#hint':'h','#repeat':'r','#save':'v','#load':'o'},
    yahtsi:{'#roll':'r'},
    dominoes:{'#draw':'d'},
    'mind-link-4':{'#describe':'b'},
    'dice-adventure':{'#roll':'r'},'dice-challenge':{'#roll':'r'},'dice-duel':{'#roll':'r'},'dice-tournament':{'#roll':'r'},'high-roller':{'#roll':'r'},'lucky-sevens':{'#roll':'r'},'roll-to-win':{'#roll':'r'},'treasure-dice':{'#roll':'r'}
  };
  const map=maps[game]||{};for(const [sel,k] of Object.entries(map))document.querySelectorAll(sel).forEach(el=>setKey(el,k));
}
function numberDynamicChoices(area){
  const groups=['#hand','#choices','#actions','#answerChoices','#dice','#cats','#board','.cards','.choices','.action-grid','#sideChoice'];
  for(const sel of groups){document.querySelectorAll(sel).forEach(group=>{const buttons=[...group.querySelectorAll('button:not([disabled])')].filter(visible);buttons.slice(0,9).forEach((b,i)=>{if(!b.dataset.key)setKey(b,String(i+1))})})}
}
function setup(){
  const main=document.querySelector('main')||document.body,game=slug(),area=gameplayArea(main);
  main.setAttribute('role','region');main.setAttribute('aria-label',(document.querySelector('h1')?.textContent||'BV game')+' game area');main.dataset.bvJawsStable='true';
  if(area){area.setAttribute('role','application');area.setAttribute('tabindex','-1');area.dataset.bvDirectKeys='true';area.setAttribute('aria-label',(document.querySelector('h1')?.textContent||'BV game')+' direct keyboard gameplay');}
  installExplicitKeys(game);numberDynamicChoices(area);
  const observer=new MutationObserver(()=>{numberDynamicChoices(area);const a=document.activeElement;if((!a||a===document.body||!a.isConnected)&&lastFocus&&lastFocus.isConnected)requestAnimationFrame(()=>safeFocus(lastFocus))});
  observer.observe(main,{childList:true,subtree:true,attributes:true,attributeFilter:['disabled','hidden']});
  document.addEventListener('focusin',e=>{if(restoring)return;if(main.contains(e.target)){lastFocus=e.target;lastX=scrollX;lastY=scrollY}},true);
  window.addEventListener('scroll',()=>{if(main.contains(document.activeElement)){lastX=scrollX;lastY=scrollY}},{passive:true});
  document.addEventListener('submit',e=>{if(main.contains(e.target)&&(!e.target.action||e.target.getAttribute('action')===''||e.target.getAttribute('action')==='#'))e.preventDefault()},true);
  const starts=[...document.querySelectorAll('#start,#startButton,#sound-start,#property-start')];starts.forEach(b=>b.addEventListener('click',()=>setTimeout(()=>{numberDynamicChoices(area);const first=area&&area.querySelector('button:not([disabled])');safeFocus(first||area)},80)));
  document.addEventListener('keydown',e=>{
    if(e.altKey||e.ctrlKey||e.metaKey||editable(e.target))return;
    const k=e.key.length===1?e.key.toLowerCase():e.key;
    if(e.key==='ArrowLeft'||e.key==='ArrowRight'){
      const group=e.target.closest&&e.target.closest('#hand,#choices,#actions,#answerChoices,#dice,#cats,#board,.cards,.choices,.action-grid,#sideChoice');
      if(group){const buttons=[...group.querySelectorAll('button:not([disabled])')].filter(visible),i=buttons.indexOf(e.target);if(i>=0&&buttons.length){e.preventDefault();safeFocus(buttons[e.key==='ArrowRight'?(i+1)%buttons.length:(i-1+buttons.length)%buttons.length]);return}}
    }
    if(!/^[a-z0-9]$/.test(k))return;
    const scope=(e.target.closest&&e.target.closest('[data-bv-direct-keys="true"],[role="application"]'))||area||main;
    const matches=[...scope.querySelectorAll('button:not([disabled]),[role="button"]:not([aria-disabled="true"])')].filter(visible).filter(el=>(el.dataset.key||'').toLowerCase()===k);
    if(matches.length){e.preventDefault();e.stopPropagation();matches[0].click();safeFocus(matches[0]);return}
    if(!e.target.closest||!e.target.closest('[data-bv-direct-keys="true"],[role="application"]')){
      const candidates=[...main.querySelectorAll('button:not([disabled]),a[href],[role="button"]')].filter(visible).filter(el=>{const explicit=(el.dataset.key||el.getAttribute('accesskey')||'').toLowerCase();const text=(el.getAttribute('aria-label')||el.textContent||'').trim().toLowerCase();return explicit===k||text.startsWith(k+' ')||text.startsWith(k+'-')||text[0]===k});
      if(candidates.length===1){e.preventDefault();candidates[0].click();safeFocus(candidates[0])}
    }
  },true);
}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',setup,{once:true});else setup();
})();
