(function(){
  function renderQrs(){
    document.querySelectorAll('.paycal-qrwrap').forEach(function(el){
      var payload = (el.getAttribute('data-qr') || '').trim();
      if(!payload){
        el.innerHTML = '<span style="color:#64748B">QR לא זמין</span>';
        return;
      }
      var url = 'https://chart.googleapis.com/chart?chs=220x220&cht=qr&chl=' + encodeURIComponent(payload);
      el.innerHTML = '<img alt="QR" src="'+url+'" style="width:220px;height:220px;border-radius:14px" />';
    });
  }

  function setupCopy(){
    document.querySelectorAll('[data-copy]').forEach(function(btn){
      btn.addEventListener('click', function(){
        var sel = btn.getAttribute('data-copy');
        var el = document.querySelector(sel);
        if(!el) return;
        var text = (el.textContent || '').trim();
        navigator.clipboard.writeText(text).then(function(){
          var old = btn.textContent;
          btn.textContent = 'הועתק ✓';
          setTimeout(function(){ btn.textContent = old; }, 1200);
        });
      });
    });
  }

  function canShowDebug(){
    var params = new URLSearchParams(window.location.search);
    return !!(window.PAYCAL_FRONT && window.PAYCAL_FRONT.canManageOptions) && params.get('paycal_debug') === '1';
  }

  function checkoutRoot(){
    return document.querySelector('[data-paycal-hosted-checkout]') || document.querySelector('.paycal-hosted-checkout') || document.body;
  }

  function returnUrlFrom(options){
    options = options || {};
    if(options.returnUrl) return options.returnUrl;
    var params = new URLSearchParams(window.location.search);
    return params.get('return_url') || '';
  }

  function looksTechnical(text){
    text = (text || '').trim();
    if(!text) return false;
    return text.indexOf('Invalid PayCal API response') !== -1 ||
      text.indexOf('payment_id') !== -1 ||
      text.indexOf('http_code') !== -1 ||
      text.indexOf('apple_pay_token') !== -1 ||
      text.indexOf('payment_token') !== -1 ||
      text.indexOf('merchantSessionIdentifier') !== -1 ||
      text.indexOf('JSON.stringify') !== -1 ||
      text.indexOf('"ok"') !== -1 ||
      text.indexOf('{"') === 0 ||
      text.indexOf('[{') === 0;
  }

  function applyDebugVisibility(root){
    root = root || document;
    root.querySelectorAll('[data-paycal-debug], .paycal-debug, .paycal-api-response').forEach(function(el){
      if(canShowDebug()){
        el.style.display = 'block';
      } else {
        el.style.display = 'none';
      }
    });

    if(canShowDebug()) return;

    root.querySelectorAll('pre, code, .paycal-error, .paycal-message, .paycal-notice').forEach(function(el){
      if(looksTechnical(el.textContent)){
        el.style.display = 'none';
        el.textContent = '';
      }
    });
  }

  function renderHostedCheckoutAccepted(options){
    options = options || {};
    var root = options.root || checkoutRoot();
    var result = root.querySelector('[data-paycal-payment-result]') || root.querySelector('.paycal-payment-result');
    var returnUrl = returnUrlFrom(options);

    applyDebugVisibility(root);

    if(!result){
      result = document.createElement('div');
      result.className = 'paycal-payment-result';
      root.appendChild(result);
    }

    result.innerHTML = '<div>הבקשה התקבלה</div><div>מחזירים אותך לחנות…</div>';
    result.setAttribute('dir', 'rtl');

    if(returnUrl){
      setTimeout(function(){
        window.location.href = returnUrl;
      }, options.redirectDelay || 1200);
    }

    return true;
  }

  function renderHostedCheckoutSuccess(response, options){
    if(!response || !response.ok || !response.success || response.status !== 'approved'){
      return false;
    }

    return renderHostedCheckoutAccepted(options);
  }

  function renderHostedCheckoutFailure(options){
    renderHostedCheckoutAccepted(options || {});
    return true;
  }

  function observeTechnicalOutput(){
    if(canShowDebug() || !window.MutationObserver) return;
    var observer = new MutationObserver(function(mutations){
      mutations.forEach(function(mutation){
        Array.prototype.slice.call(mutation.addedNodes || []).forEach(function(node){
          if(node.nodeType !== 1) return;
          if(looksTechnical(node.textContent)){
            renderHostedCheckoutFailure({root: checkoutRoot()});
          }
          applyDebugVisibility(node);
        });
      });
    });
    observer.observe(document.body, {childList:true, subtree:true});
  }

  document.addEventListener('DOMContentLoaded', function(){
    renderQrs();
    setupCopy();
    applyDebugVisibility(document);
    observeTechnicalOutput();
  });

  window.PayCalHostedCheckout = window.PayCalHostedCheckout || {};
  window.PayCalHostedCheckout.renderAccepted = renderHostedCheckoutAccepted;
  window.PayCalHostedCheckout.renderPaymentSuccess = renderHostedCheckoutSuccess;
  window.PayCalHostedCheckout.renderPaymentFailure = renderHostedCheckoutFailure;
  window.PayCalHostedCheckout.applyDebugVisibility = applyDebugVisibility;
  document.addEventListener('paycal:payment-success', function(event){
    renderHostedCheckoutSuccess(event.detail && event.detail.response, event.detail || {});
  });
  document.addEventListener('paycal:payment-error', function(event){
    renderHostedCheckoutFailure(event.detail || {});
  });
  document.addEventListener('paycal:payment-failure', function(event){
    renderHostedCheckoutFailure(event.detail || {});
  });
  document.addEventListener('paycal:invalid-api-response', function(event){
    renderHostedCheckoutFailure(event.detail || {});
  });
})();
