(function(){
var csrf = document.querySelector('meta[name="csrf-token"]').content;
var val = '';
var MAX = 6;
var dotsEl = document.getElementById('pin-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='pin-dot';dotsEl.appendChild(d);}
function updateDots(){var dots=dotsEl.children;for(var i=0;i<MAX;i++){dots[i].className=i<val.length?'pin-dot filled':'pin-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++){
var b=document.createElement('button');b.className='k-btn';b.type='button';
b.textContent=digits[i];b.dataset.v=digits[i];
b.onclick=function(){onDigit(this.dataset.v);};
gridEl.appendChild(b);
}
var clr=document.createElement('button');clr.className='k-act k-clr';clr.type='button';clr.textContent='CLR';clr.id='clr-btn';
clr.disabled=val.length===0;
clr.onclick=function(){val='';updateDots();updateBtns();errEl.textContent='';};
gridEl.appendChild(clr);
var b10=document.createElement('button');b10.className='k-btn';b10.type='button';
b10.textContent=digits[9];b10.dataset.v=digits[9];
b10.onclick=function(){onDigit(this.dataset.v);};
gridEl.appendChild(b10);
var ent=document.createElement('button');ent.className='k-act k-ent';ent.type='button';ent.textContent='ENT';ent.id='ent-btn';
ent.disabled=val.length!==MAX;
ent.onclick=submit;
gridEl.appendChild(ent);
}
function updateBtns(){
var c=document.getElementById('clr-btn');if(c)c.disabled=val.length===0;
var e=document.getElementById('ent-btn');if(e)e.disabled=val.length!==MAX;
}
function onDigit(d){
if(val.length>=MAX)return;
val+=d;
updateDots();
buildGrid();
updateBtns();
}
function submit(){
if(val.length!==MAX)return;
errEl.textContent='';
var pin=val;val='';updateDots();
fetch('login.php',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'_csrf='+encodeURIComponent(csrf)+'&pin='+encodeURIComponent(pin)})
.then(function(r){return r.json();})
.then(function(d){
if(d.success){if(d._csrf)csrf=d._csrf;window.location.href='login2.php';}
else{errEl.textContent=d.error||'Failed.';document.getElementById('auth-card').classList.add('shake');setTimeout(function(){document.getElementById('auth-card').classList.remove('shake');},500);buildGrid();}
})
.catch(function(){errEl.textContent='Connection error.';buildGrid();});
}
buildGrid();
})();