jQuery(document).ready(function ($) {
  function reindexWebsiteFields() {
    var fields = $('#website-fields .website-field');
    fields.each(function (newIndex, field) {
      $(field).find('input, label').each(function () {
        var el = $(this);

        if (el.is('input')) {
          var name = el.attr('name');
          if (name) {
            name = name.replace(/masspost_websites\[\d+\]/, 'masspost_websites[' + newIndex + ']');
            el.attr('name', name);
          }
          var id = el.attr('id');
          if (id) {
            id = id.replace(/_\d+$/, '_' + newIndex);
            el.attr('id', id);
          }
        }
        if (el.is('label')) {
          var forAttr = el.attr('for');
          if (forAttr) {
            forAttr = forAttr.replace(/_\d+$/, '_' + newIndex);
            el.attr('for', forAttr);
          }
        }
      });
    });
  }

  $('#add-new-website').on('click', function () {
    var container = $('#website-fields');
    var index = container.children('.website-field').length;
    var template = masspost_admin_vars.template;
    container.append(template.replace(/__INDEX__/g, index));
  });

  $('#website-fields').on('click', '.remove-website', function (e) {
    e.preventDefault();
    $(this).closest('.website-field').remove();
    reindexWebsiteFields();
  });

  $('#website-fields').sortable({
    items: '.website-field',
    placeholder: 'ui-sortable-placeholder',
    forcePlaceholderSize: true,
    stop: function () {
      reindexWebsiteFields();
    }
  });

  // Export Configuration
  $('#masspost-export-config').on('click', function (e) {
    e.preventDefault();

    // Collect site settings
    var api_token = $('#masspost_api_token').val() || '';
    var api_user = $('#masspost_api_user').val() || '';

    // Collect all website data
    var websites = [];
    $('#website-fields .website-field').each(function () {
      var $field = $(this);
      var name = $field.find('input[name*="[name]"]').val();
      var api_url = $field.find('input[name*="[api_url]"]').val();
      var api_token = $field.find('input[name*="[api_token]"]').val();

      if (name && api_url && api_token) {
        websites.push({
          name: name,
          api_url: api_url,
          api_token: api_token
        });
      }
    });

    // Check if there's anything to export
    if (websites.length === 0 && !api_token && !api_user) {
      alert('No configuration to export. Please configure at least one setting first.');
      return;
    }

    // Create export data
    var exportData = {
      version: '1.0',
      exported_at: new Date().toISOString(),
      site_url: window.location.hostname,
      api_token: api_token,
      api_user: api_user,
      websites: websites
    };

    // Create downloadable file
    var jsonString = JSON.stringify(exportData, null, 2);
    var blob = new Blob([jsonString], { type: 'application/json' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'masspost-config-' + new Date().toISOString().split('T')[0] + '.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  });

  // Import Configuration
  $('#masspost-import-config').on('click', function (e) {
    e.preventDefault();

    var fileInput = document.getElementById('masspost-import-file');
    var file = fileInput.files[0];

    if (!file) {
      $('#masspost-import-result').html('<div class="notice notice-error inline"><p>Please select a JSON file to import.</p></div>');
      return;
    }

    if (file.type !== 'application/json') {
      $('#masspost-import-result').html('<div class="notice notice-error inline"><p>Invalid file type. Please select a JSON file.</p></div>');
      return;
    }

    var reader = new FileReader();
    reader.onload = function (event) {
      try {
        var jsonData = event.target.result;
        JSON.parse(jsonData); // Validate JSON

        // Send to server
        $.ajax({
          url: masspost_admin_vars.ajax_url,
          type: 'POST',
          data: {
            action: 'masspost_import_config',
            nonce: masspost_admin_vars.import_nonce,
            json_data: jsonData
          },
          beforeSend: function () {
            $('#masspost-import-result').html('<div class="notice notice-info inline"><p>Importing...</p></div>');
          },
          success: function (response) {
            if (response.success) {
              $('#masspost-import-result').html(
                '<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>'
              );
              // Reload page after 2 seconds to show imported data
              setTimeout(function () {
                window.location.reload();
              }, 2000);
            } else {
              $('#masspost-import-result').html(
                '<div class="notice notice-error inline"><p>' + response.data.message + '</p></div>'
              );
            }
          },
          error: function () {
            $('#masspost-import-result').html(
              '<div class="notice notice-error inline"><p>Failed to import configuration. Please try again.</p></div>'
            );
          }
        });

      } catch (error) {
        $('#masspost-import-result').html(
          '<div class="notice notice-error inline"><p>Invalid JSON file. Please check the file format.</p></div>'
        );
      }
    };

    reader.readAsText(file);
  });

  // AJAX Save Settings
  $('#masspost-save-settings').on('click', function (e) {
    e.preventDefault();

    var $btn = $(this);
    var $result = $('#masspost-save-result');
    var originalText = $btn.html();

    // Show loading state
    $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> ' + (masspost_admin_vars.strings?.saving || 'Saving...'));

    // Collect form data
    var api_token = $('#masspost_api_token').val() || '';
    var api_user = $('#masspost_api_user').val() || '';
    var websites = [];

    $('#website-fields .website-field').each(function () {
      var $field = $(this);
      websites.push({
        name: $field.find('input[name*="[name]"]').val() || '',
        api_url: $field.find('input[name*="[api_url]"]').val() || '',
        api_token: $field.find('input[name*="[api_token]"]').val() || ''
      });
    });

    $.ajax({
      url: masspost_admin_vars.ajax_url,
      type: 'POST',
      data: {
        action: 'masspost_save_settings',
        nonce: masspost_admin_vars.save_nonce,
        api_token: api_token,
        api_user: api_user,
        websites: websites
      },
      success: function (response) {
        $btn.prop('disabled', false).html(originalText);
        if (response.success) {
          $result.html('<div class="notice notice-success inline" style="margin-top: 16px;"><p>' + (response.data?.message || masspost_admin_vars.strings?.saved || 'Settings saved.') + '</p></div>');
          setTimeout(function () { $result.find('.notice').fadeOut(); }, 3000);
        } else {
          $result.html('<div class="notice notice-error inline" style="margin-top: 16px;"><p>' + (response.data?.message || masspost_admin_vars.strings?.error || 'Error saving.') + '</p></div>');
        }
      },
      error: function () {
        $btn.prop('disabled', false).html(originalText);
        $result.html('<div class="notice notice-error inline" style="margin-top: 16px;"><p>' + (masspost_admin_vars.strings?.error || 'Error saving settings.') + '</p></div>');
      }
    });
  });
});
