/* PEWIT Labs — Pewit AI Schema Builder admin */
(function ($) {
  'use strict';

  var cfg = window.AISB || {};

  function notice(msg, type) {
    var $n = $('#aisb-notice, .aisb-metabox-status').first();
    if (!$n.length) return;
    $n.removeClass('aisb-notice-ok aisb-notice-error aisb-notice-warn')
      .addClass('aisb-notice-' + (type || 'ok'))
      .text(msg);
  }

  function ajax(action, data) {
    data = data || {};
    data.action = action;
    data.nonce = cfg.nonce;
    return $.post(cfg.ajax, data);
  }

  function renderValidation($panel, html) {
    if ($panel.length && html) {
      $panel.html(html);
    }
  }

  function validationHtmlFromResult(v) {
    if (!v) return '';
    var cls = v.valid ? 'aisb-validation-ok' : 'aisb-validation-error';
    var html = '<div class="aisb-validation-result ' + cls + '">';
    if (v.score && v.score.score !== undefined) {
      html += '<p><strong>Rich Results Score: ' + v.score.score + '/100</strong> — ' + $('<div>').text(v.score.label || '').html() + '</p>';
    }
    if (v.valid) {
      html += '<p><strong>' + (cfg.i18n.valid || 'Validation passed') + '</strong></p>';
    } else {
      html += '<p><strong>' + (cfg.i18n.invalid || 'Validation issues') + '</strong></p><ul>';
      (v.errors || []).forEach(function (e) {
        html += '<li>' + $('<div>').text(e).html() + '</li>';
      });
      html += '</ul>';
    }
    if (v.warnings && v.warnings.length) {
      html += '<p class="description">' + (cfg.i18n.warnings || 'Warnings:') + '</p><ul class="aisb-validation-warnings">';
      v.warnings.forEach(function (w) {
        html += '<li>' + $('<div>').text(w).html() + '</li>';
      });
      html += '</ul>';
    }
    html += '</div>';
    return html;
  }

  /* Settings */
  $(document).on('click', '#aisb-api-key-change', function () {
    $('#aisb-api-key-saved').hide();
    $('#aisb-api-key-edit').show();
    $('#aisb_api_key').val('').focus();
  });

  $(document).on('click', '#aisb-api-key-cancel', function () {
    $('#aisb-api-key-edit').hide();
    $('#aisb-api-key-saved').show();
  });

  $(document).on('click', '#aisb-test-api', function () {
    var $btn = $(this).prop('disabled', true);
    ajax('aisb_test_api', {
      provider: $('#aisb_provider').val(),
      api_key: $('#aisb_api_key').val(),
      model: $('#aisb_model').val(),
      global_context: $('#aisb_global_context').val()
    }).done(function (res) {
      if (res.success) {
        notice(res.data.message, 'ok');
        $('#aisb-api-status').removeClass('error').addClass('ok').text(res.data.message);
        if (res.data.mask) {
          $('#aisb_api_key_mask').text(res.data.mask);
          $('#aisb-api-key-saved').show();
          $('#aisb-api-key-edit').hide();
        }
        cfg.apiReady = 1;
      } else {
        notice(res.data && res.data.message ? res.data.message : cfg.i18n.error, 'error');
        $('#aisb-api-status').removeClass('ok').addClass('error').text(res.data.message);
      }
    }).fail(function () {
      notice(cfg.i18n.error || 'Request failed', 'error');
    }).always(function () {
      $btn.prop('disabled', false);
    });
  });

  $(document).on('click', '#aisb-save-settings', function () {
    var $btn = $(this).prop('disabled', true);
    var enabled = [];
    $('.aisb-cpt-enabled:checked').each(function () {
      enabled.push($(this).val());
    });
    var cptMap = {};
    $('.aisb-cpt-map').each(function () {
      var name = $(this).attr('name');
      var match = name && name.match(/aisb_cpt_map\[([^\]]+)\]/);
      if (match) {
        cptMap[match[1]] = $(this).val();
      }
    });
    var fieldMap = {};
    $('.aisb-field-map-row').each(function () {
      var pt = $(this).data('post-type');
      var field = $(this).data('source-field');
      var target = $(this).find('.aisb-field-target').val();
      if (pt && field && target) {
        if (!fieldMap[pt]) fieldMap[pt] = {};
        fieldMap[pt][field] = target;
      }
    });
    ajax('aisb_save_settings', {
      provider: $('#aisb_provider').val(),
      api_key: $('#aisb_api_key').val(),
      model: $('#aisb_model').val(),
      global_context: $('#aisb_global_context').val(),
      output_mode: $('#aisb_output_mode').val(),
      seo_coexist_mode: $('#aisb_seo_coexist_mode').val(),
      global_schema_enabled: $('#aisb_global_schema_enabled').is(':checked') ? 1 : 0,
      breadcrumb_enabled: $('#aisb_breadcrumb_enabled').is(':checked') ? 1 : 0,
      etch_native_ui: $('#aisb_etch_native_ui').is(':checked') ? 1 : 0,
      enabled_post_types: enabled,
      cpt_schema_map: cptMap,
      schema_field_map: fieldMap,
      auto_generate: $('#aisb_auto_generate').is(':checked') ? 1 : 0,
      batch_size: $('#aisb_batch_size').val(),
      batch_delay: $('#aisb_batch_delay').val(),
      notify_email_enabled: $('#aisb_notify_email_enabled').is(':checked') ? 1 : 0,
      notify_email_failures: $('#aisb_notify_email_failures').is(':checked') ? 1 : 0,
      notify_email_to: $('#aisb_notify_email_to').val(),
      validation_scan_enabled: $('#aisb_validation_scan_enabled').is(':checked') ? 1 : 0
    }).done(function (res) {
      notice(res.success ? res.data.message : (res.data && res.data.message), res.success ? 'ok' : 'error');
    }).always(function () {
      $btn.prop('disabled', false);
    });
  });

  /* Post metabox */
  function postId() {
    var $box = $('.aisb-metabox');
    return $box.data('post-id') || $('#post_ID').val();
  }

  function generateSchema(regenerate) {
    var $box = $('.aisb-metabox');
    if (!$box.length) return;
    var $btn = regenerate ? $('.aisb-regenerate-schema') : $('.aisb-generate-schema');
    $btn.prop('disabled', true);
    notice(cfg.i18n.generating || 'Generating…', 'warn');
    ajax('aisb_generate_schema', {
      post_id: postId(),
      schema_type: $('#aisb_schema_type').val()
    }).done(function (res) {
      if (res.success) {
        $('#aisb_schema_json').val(res.data.json);
        renderValidation($('#aisb-validation-panel'), validationHtmlFromResult(res.data.validation));
        notice(cfg.i18n.generated || 'Schema generated. Review and save to post.', 'ok');
        $('.aisb-regenerate-schema').prop('disabled', false);
      } else {
        notice(res.data && res.data.message ? res.data.message : cfg.i18n.error, 'error');
      }
    }).fail(function () {
      notice(cfg.i18n.error || 'Request failed', 'error');
    }).always(function () {
      $btn.prop('disabled', false);
    });
  }

  $(document).on('click', '.aisb-generate-schema', function () {
    generateSchema(false);
  });

  $(document).on('click', '.aisb-regenerate-schema', function () {
    generateSchema(true);
  });

  $(document).on('click', '.aisb-save-schema', function () {
    var $btn = $(this).prop('disabled', true);
    ajax('aisb_save_schema', {
      post_id: postId(),
      schema_type: $('#aisb_schema_type').val(),
      schema_json: $('#aisb_schema_json').val()
    }).done(function (res) {
      if (res.success) {
        notice(res.data.message, 'ok');
        renderValidation($('#aisb-validation-panel'), validationHtmlFromResult(res.data.validation));
      } else {
        notice(res.data && res.data.message ? res.data.message : cfg.i18n.error, 'error');
      }
    }).always(function () {
      $btn.prop('disabled', false);
    });
  });

  $(document).on('click', '.aisb-validate-schema', function () {
    ajax('aisb_validate_schema', {
      schema_type: $('#aisb_schema_type').val(),
      schema_json: $('#aisb_schema_json').val()
    }).done(function (res) {
      if (res.success) {
        renderValidation($('#aisb-validation-panel'), res.data.html || validationHtmlFromResult(res.data.validation));
      } else {
        notice(res.data && res.data.message ? res.data.message : cfg.i18n.error, 'error');
      }
    });
  });

  $(document).on('click', '.aisb-faq-schema', function () {
    var $btn = $(this).prop('disabled', true);
    notice(cfg.i18n.generating || 'Generating…', 'warn');
    ajax('aisb_generate_faq_schema', { post_id: postId() }).done(function (res) {
      if (res.success) {
        $('#aisb_schema_type').val('FAQPage');
        $('#aisb_schema_json').val(res.data.json);
        renderValidation($('#aisb-validation-panel'), validationHtmlFromResult(res.data.validation));
        notice(cfg.i18n.generated || 'Schema generated.', 'ok');
      } else {
        notice(res.data && res.data.message ? res.data.message : cfg.i18n.error, 'error');
      }
    }).always(function () {
      $btn.prop('disabled', false);
    });
  });

  /* Onboarding */
  function dismissOnboarding() {
    ajax('aisb_complete_onboarding').always(function () {
      $('#aisb-onboarding').remove();
    });
  }

  $(function () {
    if (!cfg.onboarding_done && $('#aisb-onboarding').length) {
      $('#aisb-onboarding').addClass('is-open');
      $('#aisb-onboarding-dismiss').on('click', function (e) {
        e.preventDefault();
        dismissOnboarding();
      });
    }
  });

  /* Jobs */
  var jobPoll;

  function refreshJobPanel() {
    ajax('aisb_job_status').done(function (res) {
      if (res.success && res.data.html) {
        $('#aisb-job-panel').html(res.data.html);
        var status = res.data.job && res.data.job.status;
        if (status === 'running') {
          if (!jobPoll) {
            jobPoll = setInterval(refreshJobPanel, 4000);
          }
        } else if (jobPoll) {
          clearInterval(jobPoll);
          jobPoll = null;
        }
      }
    });
  }

  $(document).on('click', '#aisb-start-bulk', function () {
    var $btn = $(this).prop('disabled', true);
    ajax('aisb_start_bulk').done(function (res) {
      if (res.success) {
        notice(res.data.message, 'ok');
        if (res.data.html) $('#aisb-job-panel').html(res.data.html);
        refreshJobPanel();
      } else {
        notice(res.data && res.data.message ? res.data.message : cfg.i18n.error, 'error');
        $btn.prop('disabled', false);
      }
    });
  });

  $(document).on('click', '#aisb-job-pause, #aisb-job-stop', function () {
    var action = $(this).data('action');
    ajax('aisb_job_control', { job_action: action }).done(function (res) {
      if (res.success && res.data.html) {
        $('#aisb-job-panel').html(res.data.html);
        refreshJobPanel();
      }
    });
  });

  $(function () {
    if ($('#aisb-job-panel').length && cfg.canAutomate) {
      var $panel = $('#aisb-job-panel');
      if ($panel.find('.aisb-progress-bar').length) {
        refreshJobPanel();
      }
    }

    $(document).on('click', '#aisb-boost-scores', function () {
      var $btn = $(this).prop('disabled', true);
      ajax('aisb_boost_scores').done(function (res) {
        if (res.success) {
          notice(res.data.message || 'Job started.', 'ok');
          if (res.data.html) {
            $('#aisb-job-panel').replaceWith(res.data.html);
          }
          refreshJobPanel();
        } else {
          notice((res.data && res.data.message) || 'Failed.', 'err');
        }
      }).always(function () { $btn.prop('disabled', false); });
    });

    $(document).on('click', '#aisb-export-score-csv', function () {
      var $btn = $(this).prop('disabled', true);
      ajax('aisb_export_score_csv').done(function (res) {
        if (res.success && res.data && res.data.csv) {
          var blob = new Blob([res.data.csv], { type: 'text/csv;charset=utf-8;' });
          var a = document.createElement('a');
          a.href = URL.createObjectURL(blob);
          a.download = 'schema-scores.csv';
          a.click();
          notice('CSV exported.', 'ok');
        }
      }).always(function () { $btn.prop('disabled', false); });
    });
  });
})(jQuery);
