jQuery(function($){
  function showModal(title, message, type){
    var tClass = type ? (' '+type) : '';
    var icon = type === 'success' ? '✅' : (type === 'error' ? '⚠️' : 'ℹ️');
    var $m = $(
      '<div class="kdsamref-modal-overlay">\
         <div class="kdsamref-modal'+tClass+'">\
           <div class="kdsamref-modal-header">'+icon+' '+$('<div>').text(title).html()+'</div>\
           <div class="kdsamref-modal-body">'+message+'</div>\
           <div class="kdsamref-modal-footer">\
             <button class="button button-primary kdsamref-modal-ok">'+kdsamrefProLicense.i18n.ok+'</button>\
           </div>\
         </div>\
       </div>'
    );
    $('body').append($m);
    $m.on('click', '.kdsamref-modal-ok, .kdsamref-modal-overlay', function(e){
      if ($(e.target).hasClass('kdsamref-modal-overlay') || $(e.target).hasClass('kdsamref-modal-ok')) {
        $m.remove();
      }
    });
  }

  $('#kdsamref_pro_validate_btn').on('click', function(){
    var key = $('#kdsamref_pro_license_key').val().trim();
    if(!key){
      showModal(kdsamrefProLicense.i18n.error, '<p>'+kdsamrefProLicense.i18n.error+': License key required</p>');
      return;
    }
    $(this).prop('disabled', true).text(kdsamrefProLicense.i18n.validating);
    $.post(kdsamrefProLicense.ajaxUrl, {
      action: 'kdsamref_pro_ajax_validate',
      nonce: kdsamrefProLicense.nonce,
      license_key: key
    }).done(function(resp){
      if(resp && resp.success){
        var active = resp.data && resp.data.active;
        var status = (resp.data && resp.data.status) || {};
        var statusText = (status.status || status.message || '').toString();
        if(active){
          var extra = '';
          if(status.expiry_date){
            // Attempt to show a friendly remaining days if server shared it
            extra = '<p style="margin-top:8px;color:#6b7280;">Expiry: '+status.expiry_date+'</p>';
          }
          showModal('License Active', '<p>'+kdsamrefProLicense.i18n.validated+'</p>'+extra, 'success');
          setTimeout(function(){ location.reload(); }, 900);
        } else {
          var host = window.location.host;
          var reason = statusText || 'License not active';
          var help = ''+
            '<div style="margin-top:8px;color:#374151;">'+
              '<p>Please check the following:</p>'+
              '<ul style="margin:6px 0 0 18px;list-style:disc;">'+
                '<li>License status in your account (Suspended/Expired)</li>'+
                '<li>Domain must match this site: <strong>'+host+'</strong></li>'+
              '</ul>'+
              '<p style="margin-top:8px;">If the issue persists, contact <a href="mailto:info@codeon.ch">info@codeon.ch</a>.</p>'+
            '</div>';
          var message = '<p><strong>'+reason+'</strong></p>'+help;
          showModal('License Issue', message, 'error');
        }
      } else {
        var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Unknown error';
        var support = '<p style="margin-top:8px;">Please contact <a href="mailto:info@codeon.ch">info@codeon.ch</a>.</p>';
        showModal(kdsamrefProLicense.i18n.error, '<p>'+msg+'</p>'+support, 'error');
      }
    }).fail(function(){
      var support = '<p style="margin-top:8px;">Please contact <a href="mailto:info@codeon.ch">info@codeon.ch</a>.</p>';
      showModal(kdsamrefProLicense.i18n.error, '<p>Network error</p>'+support, 'error');
    }).always(() => {
      $('#kdsamref_pro_validate_btn').prop('disabled', false).text('Save & Validate');
    });
  });

  $('#kdsamref_pro_deactivate_btn').on('click', function(){
    var $btn = $(this).prop('disabled', true).text('Deactivating...');
    $.post(kdsamrefProLicense.ajaxUrl, {
      action: 'kdsamref_pro_ajax_deactivate',
      nonce: kdsamrefProLicense.nonce
    }).done(function(resp){
      if(resp && resp.success){
        showModal('License Updated', '<p>'+kdsamrefProLicense.i18n.deactivated+'</p>', 'success');
        setTimeout(function(){ location.reload(); }, 800);
      } else {
        var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Unknown error';
        var support = '<p style="margin-top:8px;">Please contact <a href="mailto:info@codeon.ch">info@codeon.ch</a>.</p>';
        showModal(kdsamrefProLicense.i18n.error, '<p>'+msg+'</p>'+support, 'error');
      }
    }).fail(function(){
      var support = '<p style="margin-top:8px;">Please contact <a href="mailto:info@codeon.ch">info@codeon.ch</a>.</p>';
      showModal(kdsamrefProLicense.i18n.error, '<p>Network error</p>'+support, 'error');
    }).always(function(){
      $btn.prop('disabled', false).text('Deactivate');
    });
  });
});

