(function(){
  function ready(fn){if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);}
  var FIELDS=[{k:'name',l:'Full name',t:'text',ph:'Jane Citizen',half:false,ac:'name'},
    {k:'email',l:'Email',t:'email',ph:'jane@email.com',half:true,ac:'email'},
    {k:'phone',l:'Phone',t:'tel',ph:'0400 000 000',half:true,ac:'tel'},
    {k:'address',l:'Address line 1',t:'text',ph:'12 Example St',half:false,ac:'street-address'},
    {k:'suburb',l:'Suburb',t:'text',ph:'Sydney',half:true,ac:'address-level2'},
    {k:'postcode',l:'Postcode',t:'text',ph:'2000',half:true,ac:'postal-code'}];
  var STATES=['NSW','VIC','QLD','WA','SA','TAS','ACT','NT'];

  /* client-side image compression so receipts stay small (site stays fast) */
  function compressImage(file, cb){
    if(!file || file.type.indexOf('image/')!==0){cb(null,'Please choose an image file');return;}
    var reader=new FileReader();
    reader.onload=function(ev){
      var img=new Image();
      img.onload=function(){
        var max=1280,w=img.width,h=img.height;
        if(w>h){if(w>max){h=Math.round(h*max/w);w=max;}}else{if(h>max){w=Math.round(w*max/h);h=max;}}
        try{var cv=document.createElement('canvas');cv.width=w;cv.height=h;cv.getContext('2d').drawImage(img,0,0,w,h);cb(cv.toDataURL('image/jpeg',0.7),null);}
        catch(err){cb(ev.target.result,null);}
      };
      img.onerror=function(){cb(null,'Could not read that image');};
      img.src=ev.target.result;
    };
    reader.onerror=function(){cb(null,'Could not read that file');};
    reader.readAsDataURL(file);
  }
  function withTimeout(p,ms){return Promise.race([p,new Promise(function(res){setTimeout(function(){res({ok:false,timeout:true});},ms);})]);}

  ready(function(){
    var root=document.getElementById('checkout-root'); if(!root)return;
    var lines=IGET.cartLines();
    if(!lines.length){root.innerHTML='<div class="empty-state"><div class="big">Your cart is empty</div><a class="btn btn-cta" style="margin-top:16px" href="/iget-vape-shop.html">Shop now →</a></div>';return;}
    var cfg=IGET.getConfig(); var selected=cfg.payments.filter(function(p){return p.enabled;})[0];
    var sel=selected?selected.id:''; IGET.setPay(sel); var t=IGET.totals(sel);
    var receiptData=null;
    function selPm(){return cfg.payments.filter(function(p){return p.id===sel;})[0];}
    function needsReceipt(){var pm=selPm();return !!(pm&&(pm.type==='bank'||pm.type==='payid'));}

    function shipHtml(){var tt=IGET.totals(sel);return IGET.shipOptions().map(function(o){var on=o.id===tt.method;var free=(o.id==='express'&&tt.remainingForFree<=0);return '<label class="pay-opt'+(on?' active':'')+'"><input type="radio" name="ship" value="'+o.id+'"'+(on?' checked':'')+'><div><div class="pt">'+o.label+' <span class="muted">('+o.eta+')</span></div><div class="pd">'+(free?'<span style="color:var(--ok);font-weight:700">FREE</span>':IGET.money(o.price))+'</div></div></label>';}).join('');}
    function payRows(rows){var h='<table style="margin:4px 0 0;border-collapse:collapse;width:100%;background:#0e0e0e;border:2px solid #0e0e0e">';for(var i=0;i<rows.length;i++){h+='<tr><td style="padding:7px 12px;color:#fff;font-size:13px;white-space:nowrap;vertical-align:top">'+rows[i][0]+'</td><td style="padding:7px 12px 7px 0;font-size:18px;font-weight:700;color:#fff;word-break:break-word">'+rows[i][1]+'</td></tr>';}return h+'</table>';}
    /* receipt upload rendered INSIDE the bank/PayID tab (shown when that tab is active) */
    function receiptInline(){return '<div class="receipt-inline">'+
      '<div class="receipt-head">Upload payment receipt <span class="req">* required</span></div>'+
      '<p class="receipt-sub">After paying, upload a photo or screenshot of your receipt so we can confirm and dispatch your order.</p>'+
      '<label class="receipt-drop"><span class="receipt-label">&#128247; Tap to choose receipt from gallery</span>'+
      '<input type="file" class="receipt-file" accept="image/*" style="display:none"></label>'+
      '<div class="receipt-preview"></div><div class="receipt-err err-msg"></div></div>';}
    function payDetails(pm){var f=pm.fields||{};var note=cfg.receiptNote?('<div class="pay-note">'+cfg.receiptNote+'</div>'):'';
      if(pm.type==='contact')return '<div class="pay-note">'+(cfg.contactNote||'Our team will contact you with payment instructions after you place your order.')+'</div>';
      if(pm.type==='bank')return payRows([['Account name',IGET.esc(f.accountName)],['Account',IGET.esc(f.account)],['BSB',IGET.esc(f.bsb)]])+note+receiptInline();
      if(pm.type==='payid')return payRows([['Account name',IGET.esc(f.accountName)],['PayID',IGET.esc(f.identifier)]])+note+receiptInline();
      if(pm.type==='oxapay')return '<div class="pay-note">Save <strong>'+((f.discountPercent||15))+'%</strong> instantly with crypto. Pay securely with Bitcoin, USDT, Ethereum &amp; 50+ coins via OxaPay. After you place your order you’ll be redirected to OxaPay to complete payment.</div>';
      return IGET.esc(pm.detail||'');}
    function couponHtml(){var cp=IGET.totals(sel).coupon;return '<div class="coupon-row"><input class="input" id="coupon-code" placeholder="Coupon code" value="'+(cp?IGET.esc(cp.code):'')+'">'+(cp?'<button type="button" class="btn btn-line btn-sm" id="coupon-clear">Remove</button>':'<button type="button" class="btn btn-ghost btn-sm" id="coupon-apply">Apply</button>')+'</div>';}
    function summary(){t=IGET.totals(sel);return '<div class="summary"><h3>Order Summary</h3>'+IGET.shipBanner(t)+IGET.minBanner(t)+
      '<div class="sline"><span>Subtotal</span><span class="price">'+IGET.money(t.subtotal)+'</span></div>'+
      (t.discount>0?'<div class="sline"><span>Discount'+(t.coupon?' ('+IGET.esc(t.coupon.code)+')':'')+'</span><span class="price" style="color:var(--ok)">-'+IGET.money(t.discount)+'</span></div>':'')+
      (t.payDisc>0?'<div class="sline"><span>'+IGET.esc(t.payDiscLabel)+'</span><span class="price" style="color:var(--ok)">-'+IGET.money(t.payDisc)+'</span></div>':'')+
      '<div class="sline"><span>'+t.shipLabel+'</span><span class="price">'+(t.free?'<span style="color:var(--ok)">FREE</span>':IGET.money(t.shipping))+'</span></div>'+
      '<div class="sline total"><span>Total</span><span class="price">'+IGET.money(t.total)+'</span></div>'+
      (t.meetsMin?'<button type="submit" class="btn btn-cta" id="place-btn" style="width:100%;margin-top:18px;padding:14px">Place Order · '+IGET.money(t.total)+'</button>'
                 :'<button type="button" class="btn btn-cta" disabled style="width:100%;margin-top:18px;padding:14px">Minimum order is '+IGET.money(t.minOrder)+'</button>')+
      '<p class="muted" style="font-size:12px;margin-top:12px;text-align:center">By placing your order you confirm you are 18+ and accept our terms.</p></div>';}
    var fieldsHtml=FIELDS.map(function(f){return '<div class="field" style="'+(f.half?'':'grid-column:1/-1')+'" data-field="'+f.k+'">'+
      '<label for="f-'+f.k+'">'+f.l+'</label><input class="input" id="f-'+f.k+'" name="'+f.k+'" type="'+f.t+'" placeholder="'+f.ph+'" autocomplete="'+f.ac+'">'+
      '<div class="err-msg" id="e-'+f.k+'"></div></div>';}).join('')+
      '<div class="field" data-field="state"><label for="f-state">State</label><select id="f-state" name="state"><option value="">Select…</option>'+
      STATES.map(function(s){return '<option>'+s+'</option>';}).join('')+'</select><div class="err-msg" id="e-state"></div></div>';
    var payHtml=cfg.payments.filter(function(p){return p.enabled;}).map(function(pm){return '<label class="pay-opt'+(pm.id===sel?' active':'')+'">'+
      '<input type="radio" name="pay" value="'+pm.id+'"'+(pm.id===sel?' checked':'')+'><div style="flex:1"><div class="pt">'+IGET.esc(pm.label)+'</div><div class="pd">'+IGET.esc(pm.detail)+'</div><div class="pay-details">'+payDetails(pm)+'</div></div></label>';}).join('');
    root.innerHTML='<form class="checkout-layout" id="cform" novalidate><div>'+
      '<div class="co-card"><h3>Shipping details</h3><div class="grid-2">'+fieldsHtml+'</div></div>'+
      '<div class="co-card"><h3>Shipping method</h3><div id="ship-wrap">'+shipHtml()+'</div></div>'+
      '<div class="co-card"><h3>Payment method</h3>'+payHtml+'</div>'+
      '<div class="co-card"><h3>Have a coupon?</h3><div id="coupon-wrap">'+couponHtml()+'</div></div></div>'+
      '<div id="sum-wrap">'+summary()+'</div></form>';

    function bindReceipt(){root.querySelectorAll('.receipt-file').forEach(function(fi){fi.onchange=function(){
      var f=fi.files&&fi.files[0];if(!f)return;var box=fi.closest('.receipt-inline');var lbl=box.querySelector('.receipt-label');if(lbl)lbl.textContent='Compressing…';
      compressImage(f,function(data,err){var prev=box.querySelector('.receipt-preview');var e=box.querySelector('.receipt-err');
        if(err||!data){receiptData=null;if(e)e.textContent=err||'Could not process image';if(lbl)lbl.textContent='📷 Tap to upload receipt';return;}
        receiptData=data;var kb=Math.round(data.length*0.75/1024);if(e)e.textContent='';if(lbl)lbl.textContent='📷 Change receipt';box.classList.remove('err');
        if(prev)prev.innerHTML='<div class="receipt-thumb"><img src="'+data+'" alt="Payment receipt preview"><span>&#10003; Receipt ready ('+kb+' KB)</span></div>';});};});}
    function bindPay(){root.querySelectorAll('.pay-opt input[name="pay"]').forEach(function(r){r.addEventListener('change',function(){sel=r.value;IGET.setPay(sel);root.querySelectorAll('input[name="pay"]').forEach(function(x){x.closest('.pay-opt').classList.toggle('active',x.value===sel);});document.getElementById('sum-wrap').innerHTML=summary();document.getElementById('ship-wrap').innerHTML=shipHtml();bindShip();});});}
    function bindShip(){root.querySelectorAll('input[name="ship"]').forEach(function(r){r.addEventListener('change',function(){IGET.setShip(r.value);document.getElementById('ship-wrap').innerHTML=shipHtml();document.getElementById('sum-wrap').innerHTML=summary();bindShip();});});}
    function bindCoupon(){var ap=document.getElementById('coupon-apply');if(ap)ap.onclick=function(){if(IGET.applyCoupon(document.getElementById('coupon-code').value)){document.getElementById('coupon-wrap').innerHTML=couponHtml();document.getElementById('sum-wrap').innerHTML=summary();bindCoupon();}};var cl=document.getElementById('coupon-clear');if(cl)cl.onclick=function(){IGET.clearCoupon();document.getElementById('coupon-wrap').innerHTML=couponHtml();document.getElementById('sum-wrap').innerHTML=summary();bindCoupon();};}
    bindPay(); bindShip(); bindCoupon(); bindReceipt();

    document.getElementById('cform').addEventListener('submit',function(e){
      e.preventDefault(); var form=e.target; var data={}; var valid=true,first=null;
      var tmin=IGET.totals(sel); if(!tmin.meetsMin){IGET.toast('Minimum order is '+IGET.money(tmin.minOrder),'bad');return;}
      FIELDS.map(function(f){return f.k;}).concat('state').forEach(function(k){
        var input=form.querySelector('[name="'+k+'"]'); var err=document.getElementById('e-'+k); var fld=form.querySelector('[data-field="'+k+'"]');
        var v=(input.value||'').trim(); data[k]=v; var msg='';
        if(!v)msg='Required';
        else if(k==='email'&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v))msg='Enter a valid email';
        else if(k==='phone'&&!/^[0-9+\s()-]{8,}$/.test(v))msg='Enter a valid phone';
        else if(k==='postcode'&&!/^\d{4}$/.test(v))msg='4-digit postcode';
        fld.classList.toggle('err',!!msg); err.textContent=msg; if(msg){valid=false;if(!first)first=input;}
      });
      if(!valid){if(first)first.focus();IGET.toast('Please fix the highlighted fields','bad');return;}
      // require a receipt for direct bank / PayID (shown inside the active tab)
      if(needsReceipt() && !receiptData){var box=root.querySelector('.pay-opt.active .receipt-inline')||root.querySelector('.receipt-inline');
        if(box){var e2=box.querySelector('.receipt-err');if(e2)e2.textContent='Please upload your payment receipt';box.classList.add('err');box.scrollIntoView({behavior:'smooth',block:'center'});}
        IGET.toast('Upload your payment receipt to continue','bad');return;}
      var lines=IGET.cartLines(); var tt=IGET.totals(sel); var pm=selPm();
      var order={no:'AU-'+Math.floor(10000+Math.random()*89999),date:new Date().toISOString(),
        customer:{name:data.name,email:data.email,phone:data.phone,address:data.address,suburb:data.suburb,state:data.state,postcode:data.postcode},
        items:lines.map(function(l){return {id:l.id,name:l.name,flavour:l.flavour,device:l.device,qty:l.qty,price:l.price,lineTotal:l.lineTotal};}),
        totals:tt,payment:pm.id,paymentLabel:pm.label,coupon:tt.coupon?tt.coupon.code:null,status:'Pending Payment',
        hasReceipt:needsReceipt()&&!!receiptData,emailHtml:null};
      order.emailHtml=IGET.renderEmail(order);
      var orders=IGET.getOrders();orders.unshift(order);IGET.saveOrders(orders);
      localStorage.setItem('iget_last_order',JSON.stringify(order));
      IGET.setCart([]); IGET.clearCoupon(); IGET.setPay('');
      var receipt=needsReceipt()?receiptData:null;
      var btn=document.getElementById('place-btn'); if(btn){btn.disabled=true;btn.textContent='Placing order…';}
      withTimeout(IGET.sendEmail(order, receipt), 15000).then(function(){
        if(pm.type==='oxapay'){
          var key=(pm.fields||{}).merchantKey; IGET.toast('Redirecting to OxaPay…','info','₿');
          fetch('https://api.oxapay.com/v1/payment/invoice',{method:'POST',headers:{'merchant_api_key':key,'Content-Type':'application/json'},
            body:JSON.stringify({amount:Number(tt.total.toFixed(2)),currency:'AUD',order_id:order.no,
              return_url:location.origin+'/order-confirmation.html',callback_url:location.origin+'/order-confirmation.html'})})
            .then(function(r){return r.json();}).then(function(j){var u=j&&j.data&&j.data.payment_url;location.href=u||'/order-confirmation.html';})
            .catch(function(){location.href='/order-confirmation.html';});
        } else { location.href='/order-confirmation.html'; }
      });
    });
  });
})();
