
(function(){
var SETS={
 "Everyday words":[["begin","to start"],["huge","very big"],["reply","to answer"],["buy","to purchase something"],["tired","needing rest"],["quick","fast"]],
 "Adjectives":[["ancient","very old"],["freezing","extremely cold"],["delighted","very happy"],["exhausted","very tired"],["tiny","very small"],["furious","very angry"]],
 "Phrasal verbs":[["give up","to stop trying"],["find out","to discover"],["put off","to postpone"],["look after","to take care of"],["turn down","to refuse"],["carry on","to continue"]],
 "Opposites":[["arrive","leave"],["buy","sell"],["remember","forget"],["accept","refuse"],["borrow","lend"],["increase","decrease"]]
};
var cat="Everyday words",pairs,left,right,selL,selR,done;
function $(s){return document.querySelector(s);}
function shuffle(a){return a.slice().sort(function(){return Math.random()-0.5;});}
function build(){
 pairs=SETS[cat];done=0;selL=null;selR=null;
 left=shuffle(pairs.map(function(p,i){return{t:p[0],i:i};}));
 right=shuffle(pairs.map(function(p,i){return{t:p[1],i:i};}));
 render();
}
function render(){
 var L=$("#gmLeft"),R=$("#gmRight");L.innerHTML="";R.innerHTML="";
 left.forEach(function(o){var b=document.createElement("button");b.textContent=o.t;b.className="gm-item";
  b.setAttribute("data-i",o.i);if(o.done)b.className+=" done";if(selL===o.i)b.className+=" sel";
  b.onclick=function(){if(o.done)return;selL=o.i;check();render();};L.appendChild(b);});
 right.forEach(function(o){var b=document.createElement("button");b.textContent=o.t;b.className="gm-item";
  b.setAttribute("data-i",o.i);if(o.done)b.className+=" done";if(selR===o.i)b.className+=" sel";
  b.onclick=function(){if(o.done)return;selR=o.i;check();render();};R.appendChild(b);});
 var m=$("#gmMsg");
 if(done===pairs.length){m.textContent="\uD83C\uDF89 All matched \u2014 brilliant!";m.className="gm-msg win";}
 else m.textContent=done+" / "+pairs.length+" matched";
}
function check(){
 if(selL===null||selR===null)return;
 if(selL===selR){
  left.forEach(function(o){if(o.i===selL)o.done=true;});
  right.forEach(function(o){if(o.i===selR)o.done=true;});
  done++;selL=null;selR=null;
 }else{var a=selL,b=selR;selL=null;selR=null;setTimeout(function(){render();},250);
  var m=$("#gmMsg");m.textContent="Not a match \u2014 try again";m.className="gm-msg";}
}
document.addEventListener("DOMContentLoaded",function(){
 var cw=$("#gmCats");Object.keys(SETS).forEach(function(c){
  var b=document.createElement("button");b.textContent=c;if(c===cat)b.className="on";
  b.onclick=function(){cat=c;[].forEach.call(cw.children,function(x){x.className="";});b.className="on";build();};
  cw.appendChild(b);});
 $("#gmNew").onclick=build;build();
});
})();
