(function(){let stream=null,detector=null,active=false;function status(text){let el=document.getElementById('scannerStatus');if(el)el.textContent=text;}async function start(){const modal=document.getElementById('posCameraModal');const video=document.getElementById('posScannerVideo');if(!modal||!video)return;if(!('BarcodeDetector' in window)){status('Camera barcode scanner is not available in this browser. Use hardware scanner or manual input.');return;}try{detector=new BarcodeDetector({formats:['ean_13','ean_8','code_128','code_39','qr_code','upc_a','upc_e']});stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'environment'}});video.srcObject=stream;await video.play();modal.hidden=false;active=true;scanLoop(video);}catch(e){status('Camera permission denied or scanner unavailable.');}}
async function scanLoop(video){if(!active||!detector)return;try{let codes=await detector.detect(video);if(codes&&codes.length){let val=codes[0].rawValue;status('Scanned: '+val);if(window.phPosAddByCode)window.phPosAddByCode(val);stop();return;}}catch(e){}requestAnimationFrame(()=>scanLoop(video));}
function stop(){active=false;if(stream){stream.getTracks().forEach(t=>t.stop());stream=null;}let modal=document.getElementById('posCameraModal');if(modal)modal.hidden=true;}
document.addEventListener('DOMContentLoaded',()=>{document.body.addEventListener('click',e=>{if(e.target.matches('[data-camera-start]'))start();if(e.target.matches('[data-camera-stop]'))stop();});});window.phPosStartCamera=start;window.phPosStopCamera=stop;})();
