(function(){
var csrf = document.querySelector('meta[name="csrf-token"]').content;
var tk = JSON.parse(document.getElementById('auth-card').getAttribute('data-tk'));

var seq = [];
var MAX = 4;
var dotsEl = document.getElementById('v-dots');
var gridEl = document.getElementById('grid');
var errEl = document.getElementById('error');
for(var i=0;i<MAX;i++){var d=document.createElement('span');d.className='v-dot';dotsEl.appendChild(d);}
function updateDots(){var dots=dotsEl.children;for(var i=0;i<MAX;i++){dots[i].className=i<seq.length?'v-dot filled':'v-dot';}}
function shuffle(a){for(var i=a.length-1;i>0;i--){var j=Math.floor(Math.random()*(i+1));var t=a[i];a[i]=a[j];a[j]=t;}return a;}
function buildGrid(){
gridEl.innerHTML='';
var digits=shuffle([0,1,2,3,4,5,6,7,8,9]);
for(var i=0;i<9;i++){
(function(pos){
var b=document.createElement('button');b.className='k-btn';b.type='button';
b.textContent=digits[pos];
b.onclick=function(){onSelect(pos);};
gridEl.appendChild(b);
})(i);
}
var clr=document.createElement('button');clr.className='k-act k-clr';clr.type='button';clr.textContent='CLR';clr.id='clr-btn';
clr.disabled=seq.length===0;
clr.onclick=function(){seq=[];updateDots();buildGrid();errEl.textContent='';};
gridEl.appendChild(clr);
(function(){
var b=document.createElement('button');b.className='k-btn';b.type='button';
b.textContent=digits[9];
b.onclick=function(){onSelect(9);};
gridEl.appendChild(b);
})();
var ent=document.createElement('button');ent.className='k-act k-ent';ent.type='button';ent.textContent='ENT';ent.id='ent-btn';
ent.disabled=seq.length!==MAX;
ent.onclick=submit;
gridEl.appendChild(ent);
}
function onSelect(posIdx){
if(seq.length>=MAX)return;
seq.push(tk[posIdx]);
updateDots();
buildGrid();
}
function submit(){
if(seq.length!==MAX)return;
errEl.textContent='';
var payload=seq.join(',');
seq=[];updateDots();
fetch('login3.php',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/x-www-form-urlencoded'},
body:'_csrf='+encodeURIComponent(csrf)+'&seq='+encodeURIComponent(payload)})
.then(function(r){return r.json();})
.then(function(d){
if(d.success){window.location.href=d.redirect||'index.php';}
else{
errEl.textContent=d.error||'Failed.';
document.getElementById('auth-card').classList.add('shake');
setTimeout(function(){document.getElementById('auth-card').classList.remove('shake');},500);
setTimeout(function(){window.location.reload();},1500);
}
})
.catch(function(){errEl.textContent='Connection error.';buildGrid();});
}
buildGrid();
})();