(function($){
  function renderBitQR(){
    var box = document.getElementById('paycal_qr_box');
    if(!box) return;

    var phone = (box.dataset.phone || '').trim();
    if(!phone){
      box.innerHTML = '<span style="color:#64748B">הזן מספר טלפון כדי לראות QR</span>';
      return;
    }

    var payload = 'BIT:' + phone;
    var url = 'https://chart.googleapis.com/chart?chs=220x220&cht=qr&chl=' + encodeURIComponent(payload);
    box.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();
        if(!text) return;

        navigator.clipboard.writeText(text).then(function(){
          var old = btn.textContent;
          btn.textContent = 'הועתק ✓';
          setTimeout(function(){ btn.textContent = old; }, 1200);
        });
      });
    });
  }

  document.addEventListener('DOMContentLoaded', function(){
    renderBitQR();

    var phoneInput = document.getElementById('paycal_bit_phone');
    if(phoneInput){
      phoneInput.addEventListener('input', function(){
        var box = document.getElementById('paycal_qr_box');
        if(box) box.dataset.phone = phoneInput.value.replace(/\D+/g,'');
        renderBitQR();
      });
    }

    setupCopy();
  });
})(jQuery);
