const state={products:[],quantities:{},paymentTimer:null,pollTimer:null,thankTimer:null,pollSince:0,thankYouSeconds:3};
const debug=(...args)=>console.log('[FIKAKASSA]',new Date().toISOString(),...args);
// Kioskläge: blockera webbläsarens vanliga touch-, markerings- och kontextmenyer.
document.addEventListener('contextmenu',e=>e.preventDefault());
document.addEventListener('selectstart',e=>e.preventDefault());
document.addEventListener('dragstart',e=>e.preventDefault());
document.addEventListener('gesturestart',e=>e.preventDefault(),{passive:false});
document.addEventListener('gesturechange',e=>e.preventDefault(),{passive:false});
document.addEventListener('gestureend',e=>e.preventDefault(),{passive:false});
document.addEventListener('wheel',e=>{if(e.ctrlKey)e.preventDefault()},{passive:false});
document.addEventListener('keydown',e=>{
if((e.ctrlKey||e.metaKey)&&(['+','-','=','0'].includes(e.key)))e.preventDefault();
});
const shopView=document.getElementById('shopView'),paymentView=document.getElementById('paymentView'),thanksView=document.getElementById('thanksView'),productGrid=document.getElementById('productGrid'),summary=document.getElementById('summary'),paymentTotal=document.getElementById('paymentTotal'),qr=document.getElementById('qr'),posterAmount=document.getElementById('posterAmount'),posterNumber=document.getElementById('posterNumber'),posterName=document.getElementById('posterName'),timeoutBar=document.getElementById('timeoutBar'),nextCustomer=document.getElementById('nextCustomer'),cancelPurchase=document.getElementById('cancelPurchase');
const money=v=>`${v} kr`;
function formatSwishNumber(v){const d=String(v||'').replace(/\D/g,'');if(d.startsWith('46')&&d.length===11){const n='0'+d.slice(2);return `${n.slice(0,3)}-${n.slice(3,6)} ${n.slice(6,8)} ${n.slice(8,10)}`}return v||''}
function total(){return state.products.reduce((s,p)=>s+(state.quantities[p.id]||0)*p.price,0)}
const imageCache=new Map();
let qrObjectUrl=null;
async function prepareQr(orderId){
const response=await fetch(`/api/order/${encodeURIComponent(orderId)}/qr.png?ts=${Date.now()}`,{cache:'no-store'});
if(!response.ok)throw new Error('Kunde inte hämta QR-koden');
const blob=await response.blob();
if(qrObjectUrl)URL.revokeObjectURL(qrObjectUrl);
qrObjectUrl=URL.createObjectURL(blob);
qr.src=qrObjectUrl;
if(qr.decode){
try{await qr.decode();}catch(e){
await new Promise((resolve,reject)=>{qr.onload=resolve;qr.onerror=reject;});
}
}else{
await new Promise((resolve,reject)=>{qr.onload=resolve;qr.onerror=reject;});
}
}
function productImages(p){
const images=p.images||[p.image];
const rotations=p.image_rotations||[p.rotate||0];
const xOffsets=p.image_x_offsets||[];
if(images.length>1){
return `
${images.map((img,i)=>``).join('')}
`;
}
return ``;
}
async function loadTransparentImage(src){
if(imageCache.has(src))return imageCache.get(src);
const promise=new Promise((resolve,reject)=>{
const img=new Image();
img.onload=()=>{
const scale=Math.min(1,900/Math.max(img.naturalWidth,img.naturalHeight));
const w=Math.max(1,Math.round(img.naturalWidth*scale));
const h=Math.max(1,Math.round(img.naturalHeight*scale));
const c=document.createElement('canvas'); c.width=w; c.height=h;
const ctx=c.getContext('2d',{willReadFrequently:true});
ctx.drawImage(img,0,0,w,h);
const data=ctx.getImageData(0,0,w,h);
const px=data.data, seen=new Uint8Array(w*h), queue=new Int32Array(w*h);
let head=0,tail=0;
const nearWhite=i=>px[i]>=244&&px[i+1]>=244&&px[i+2]>=244&&px[i+3]>0;
const push=(x,y)=>{const n=y*w+x;if(!seen[n]){seen[n]=1;queue[tail++]=n}};
for(let x=0;x0)push(x-1,y); if(x0)push(x,y-1); if(y8){if(xmaxX)maxX=x;if(ymaxY)maxY=y}}
if(maxX<0){resolve(null);return}
const pad=8; minX=Math.max(0,minX-pad); minY=Math.max(0,minY-pad); maxX=Math.min(w-1,maxX+pad); maxY=Math.min(h-1,maxY+pad);
const out=document.createElement('canvas'); out.width=maxX-minX+1; out.height=maxY-minY+1;
out.getContext('2d').drawImage(c,minX,minY,out.width,out.height,0,0,out.width,out.height);
resolve(out);
};
img.onerror=reject; img.src=src;
});
imageCache.set(src,promise);
return promise;
}
async function hydrateProductCanvases(){
const canvases=[...document.querySelectorAll('.product-canvas')];
await Promise.all(canvases.map(async canvas=>{
try{
const source=await loadTransparentImage(canvas.dataset.src);
if(!source)return;
const rotation=(Number(canvas.dataset.rotation)||0)*Math.PI/180;
const sin=Math.abs(Math.sin(rotation)),cos=Math.abs(Math.cos(rotation));
const rw=Math.max(1,Math.round(source.width*cos+source.height*sin));
const rh=Math.max(1,Math.round(source.width*sin+source.height*cos));
canvas.width=rw; canvas.height=rh;
if(canvas.classList.contains('combo-canvas')) canvas.style.setProperty('--combo-x', `${Number(canvas.dataset.xOffset)||0}px`);
const ctx=canvas.getContext('2d');
ctx.clearRect(0,0,rw,rh); ctx.translate(rw/2,rh/2); ctx.rotate(rotation);
ctx.drawImage(source,-source.width/2,-source.height/2);
}catch(e){console.error('Kunde inte behandla produktbild',canvas.dataset.src,e)}
}));
}
function applyGridConfig(grid){
const columns=Math.max(1,Number(grid?.columns)||4);
const rows=Math.max(1,Number(grid?.rows)||2);
productGrid.style.setProperty('--grid-columns',columns);
productGrid.style.setProperty('--grid-rows',rows);
}
function priceMarkup(p){
if(p.offer){
return `${p.offer_label||'ERBJUDANDE'}${money(p.price)}
`;
}
return `${money(p.price)}
`;
}
function renderProducts(){
productGrid.innerHTML='';
state.products.forEach(p=>{
const q=state.quantities[p.id]||0;
const c=document.createElement('article');
c.className=`product-card${p.offer?' offer-card':''}`;
c.innerHTML=`${priceMarkup(p)}${productImages(p)}
${p.name}
${q}
`;
c.querySelector('.minus').onclick=()=>changeQty(p.id,-1);
c.querySelector('.plus').onclick=()=>changeQty(p.id,1);
productGrid.appendChild(c);
});
const t=document.createElement('article');
t.className='total-card';
const amount=total();
t.innerHTML=`Totalt
${money(amount)}
`;
t.querySelector('.pay-button').onclick=startPayment;
t.querySelector('.clear-button').onclick=resetShop;
productGrid.appendChild(t);
hydrateProductCanvases();
}
function changeQty(id,d){state.quantities[id]=Math.max(0,(state.quantities[id]||0)+d);renderProducts()}
function clearTimers(){if(state.paymentTimer)clearTimeout(state.paymentTimer);if(state.pollTimer)clearTimeout(state.pollTimer);if(state.thankTimer)clearTimeout(state.thankTimer);state.paymentTimer=state.pollTimer=state.thankTimer=null}
function resetShop(){
debug('resetShop()');
clearTimers();state.quantities={};state.pollSince=Date.now()/1000;
paymentView.classList.add('hidden');thanksView.classList.add('hidden');shopView.classList.remove('hidden');renderProducts()
}
async function startPayment(){
const items=state.products.map(p=>({id:p.id,quantity:state.quantities[p.id]||0})).filter(x=>x.quantity>0);
if(!items.length)return;
debug('startPayment()',items);
const r=await fetch('/api/order',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items})});
if(!r.ok){debug('POST /api/order failed',r.status);return}
const order=await r.json();
debug('order created',order.id,'total=',order.total,'created_at=',order.created_at);
summary.innerHTML=order.items.map(i=>`${i.quantity} ×${i.name}
`).join('');
paymentTotal.textContent=money(order.total);posterAmount.textContent=`Betala ${money(order.total)}`;
posterNumber.textContent=formatSwishNumber(order.swish_number);posterName.textContent=order.swish_name||'Joakim Svensson';
try{await prepareQr(order.id)}catch(e){debug('QR failed',e);console.error(e);return}
shopView.classList.add('hidden');thanksView.classList.add('hidden');paymentView.classList.remove('hidden');
timeoutBar.style.transition='none';timeoutBar.style.transform='scaleX(1)';
requestAnimationFrame(()=>requestAnimationFrame(()=>{timeoutBar.style.transition='transform 30s linear';timeoutBar.style.transform='scaleX(0)'}));
// Use order.created_at rather than "now". A fast payment can arrive while the QR is loading.
state.pollSince=Math.max(0,Number(order.created_at)-0.01);
debug('payment polling started, after=',state.pollSince);
pollPayment();
state.paymentTimer=setTimeout(()=>{debug('payment timeout');resetShop()},30000)
}
async function pollPayment(){
try{
const after=state.pollSince;
const r=await fetch(`/api/payment/event?after=${after}`,{cache:'no-store'});
if(r.ok){
const e=await r.json();
debug('payment event poll',e);
if(e.event==='payment'){
state.pollSince=e.received_at;
showThanks();
return
}
}else debug('payment event HTTP',r.status);
}catch(e){debug('payment poll error',e)}
if(!paymentView.classList.contains('hidden'))state.pollTimer=setTimeout(pollPayment,700)
}
function showThanks(){
debug('showThanks(): payment accepted, switching to thanks screen');
clearTimers();
paymentView.classList.add('hidden');shopView.classList.add('hidden');thanksView.classList.remove('hidden');
debug('thanks timer started',state.thankYouSeconds*1000,'ms');
state.thankTimer=setTimeout(()=>{debug('thanks timer expired');resetShop()},state.thankYouSeconds*1000)
}
nextCustomer.onclick=resetShop;cancelPurchase.onclick=resetShop;
Promise.all([fetch('/api/products').then(r=>r.json()),fetch('/api/shop').then(r=>r.json())]).then(([pd,sd])=>{
state.products=pd.products;applyGridConfig(sd.grid);state.thankYouSeconds=Number(sd.thank_you_seconds)||3;
debug('shop config loaded',sd);
state.products.forEach(p=>state.quantities[p.id]=0);renderProducts()
}).catch(e=>debug('initial load failed',e));