var GKEY="AIzaSyCl8now0usLtADlCtmAIl40ruO-zq7DYNQ";
var SURL="https://script.google.com/macros/s/AKfycby__Fs9eQg7SKkFxU9QsjpOQMTO-_D4a1SXa6kEnKz0L3s_3h1laqDGgFbOKkz0kt3n/exec";
var WCC={18:[139,0,0],19:[165,42,42],20:[178,34,34],21:[205,92,92],22:[220,20,60],24:[210,105,30],25:[204,85,0],26:[230,126,34],27:[212,120,26],28:[218,165,32],30:[184,134,11],31:[155,135,12],32:[128,128,0],33:[107,142,35],34:[85,107,47],36:[34,139,34],37:[46,139,87],38:[32,178,170],39:[0,139,139],40:[0,128,128],42:[70,130,180],43:[65,105,225],44:[0,0,205],45:[0,0,139],46:[25,25,112],48:[75,0,130],49:[106,13,173],50:[128,0,128],51:[139,0,139],52:[199,21,133]};
var CM2IN={'81':32,'81.00':32,'86.5':34,'86.50':34,'91.5':36,'91.50':36,'96.5':38,'96.50':38};
var aPin='',rid=0;
document.getElementById('pinIn').addEventListener('keyup',function(e){if(e.key==='Enter')doPin()});
function doPin(){var p=document.getElementById('pinIn').value.trim();if(p==='4872'||p==='6263'){aPin=p;document.getElementById('pin').classList.add('hide');document.getElementById('app').style.display='block'}else{document.getElementById('pinEr').textContent='Wrong PIN';document.getElementById('pinIn').value=''}}
function setTab(n){document.querySelectorAll('.tabs button').forEach(function(b,i){b.classList.toggle('on',i===n)});document.getElementById('tab0').style.display=n===0?'block':'none';document.getElementById('tab1').style.display=n===1?'block':'none'}
function addRow(off,rno,bf,gsm,w,wt,pt){rid++;var tr=document.createElement('tr');var ptOpts=['Kraft','VK','Duplex','Imported Kraft','WKL','Others'];var ptSel='';tr.innerHTML='
'+ptSel+'
x
';tr.querySelectorAll('input,select').forEach(function(el,ei,all){el.addEventListener('keydown',function(e){if((e.key==='Tab'||e.key==='Enter')&&ei===all.length-2&&!tr.nextElementSibling){e.preventDefault();addRow();document.getElementById('tb').lastElementChild.querySelector('input').focus();}});});;document.getElementById('tb').appendChild(tr);upCnt()}
function upCnt(){var rows=document.getElementById('tb').querySelectorAll('tr'),f=0,tw=0;rows.forEach(function(r){var inp=r.querySelectorAll('input');if(inp[0]&&inp[0].value.trim()){f++;tw+=parseInt(inp[5]&&inp[5].value)||0}});document.getElementById('cnt').textContent=f?'('+f+' reels)':'';document.getElementById('totalWt').textContent=tw?tw.toLocaleString()+' KG':'0 KG';// update row numbers
document.getElementById('tb').querySelectorAll('tr').forEach(function(r,i){var n=r.querySelector('.rn');if(n)n.textContent=i+1;});}
function cmToIn(v){v=String(v).trim();if(CM2IN[v])return CM2IN[v];var n=parseFloat(v);if(n>=70&&n<=100)return Math.round(n/2.54);return n}
function onPhoto(inp){if(!inp.files||!inp.files[0])return;var file=inp.files[0];document.getElementById('snapTxt').innerHTML=' Reading...';document.getElementById('ocrMsg').innerHTML='
';var prompt='This is a paper reel packing slip. Extract every reel as a JSON array. Each object must have: rollNo (string, the reel/roll number exactly as printed), gsm (number), bf (number, the BF value, default 16 if not shown), width (number in inches, convert CM to inches: 81=32 86.5=34 91.5=36 96.5=38), weight (number in kg), paperType (string: Kraft/VK/Duplex/Imported Kraft/WKL/Others). Return ONLY the JSON array, no explanation.';fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key='+GKEY,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({contents:[{parts:[{inlineData:{mimeType:'image/jpeg',data:b64}},{text:prompt}]}]})}).then(function(r){if(!r.ok)throw new Error('HTTP '+r.status);return r.json();}).then(function(result){document.getElementById('snapTxt').textContent='Camera';var raw=result.candidates&&result.candidates[0]&&result.candidates[0].content&&result.candidates[0].content.parts&&result.candidates[0].content.parts[0]&&result.candidates[0].content.parts[0].text||'';var clean=raw.replace(/```json|```/g,'').trim();try{var arr=JSON.parse(clean);if(!Array.isArray(arr)||!arr.length)throw new Error('empty');document.getElementById('tb').innerHTML='';arr.forEach(function(r){addRow(r.rollNo||'',r.rollNo||'',r.bf||16,String(r.gsm||120),r.width||r.w||0,r.weight||r.wt||0,r.paperType||'Kraft');});addRow();addRow();document.getElementById('ocrMsg').innerHTML='
Could not parse Gemini response. Raw text in Quick Paste.
';document.getElementById('pasteBox').value=clean;setTab(0);}}).catch(function(err){document.getElementById('snapTxt').textContent='Camera';var msg=err.message.match(/Load failed|Failed to fetch|NetworkError/i)?'Network error — check API key and connection':err.message;document.getElementById('ocrMsg').innerHTML='