(function ($) {
  'use strict';

  function cfg() {
    return (typeof window.WPSN_NETWORK_PROFILES !== 'undefined') ? window.WPSN_NETWORK_PROFILES : {};
  }

  function show($el) { try { $el.show(); } catch (e) { } }
  function hide($el) { try { $el.hide(); } catch (e) { } }

  function ajaxPost(action, data) {
    var c = cfg();
    data = data || {};
    data.action = action;
    data.nonce = c.nonce || '';
    return $.post(c.ajaxUrl || ajaxurl, data);
  }

  function parseIds(str) {
    str = String(str || '').trim();
    if (!str) return [];
    var parts = str.split(',');
    var out = [];
    for (var i = 0; i < parts.length; i++) {
      var p = String(parts[i] || '').trim();
      if (!p) continue;
      var n = Number(p);
      if (!isFinite(n)) continue;
      n = Math.floor(n);
      if (n > 0) out.push(n);
    }
    // uniq + sort
    out.sort(function (a, b) { return a - b; });
    var uniq = [];
    for (var j = 0; j < out.length; j++) {
      if (j === 0 || out[j] !== out[j - 1]) uniq.push(out[j]);
    }
    return uniq;
  }

  // ----------------------------
  // Site picker (checkbox table)
  // ----------------------------
  var selectedSites = {}; // id -> true
  var syncingSiteInput = false;

  function selectedIds() {
    var ids = [];
    for (var k in selectedSites) {
      if (Object.prototype.hasOwnProperty.call(selectedSites, k)) {
        var n = Number(k);
        if (isFinite(n) && n > 0) ids.push(Math.floor(n));
      }
    }
    ids.sort(function (a, b) { return a - b; });
    return ids;
  }

  function setSelectedCount() {
    var count = selectedIds().length;
    $('#wpsn-sites-selected-count').text(String(count));
  }

  function syncSiteIdsInputFromSelected() {
    syncingSiteInput = true;
    try {
      var ids = selectedIds();
      $('#wpsn-site-ids').val(ids.join(','));
      setSelectedCount();
    } finally {
      syncingSiteInput = false;
    }
  }

  function setSelectionFromSiteIdsInput() {
    if (syncingSiteInput) return;
    var ids = parseIds($('#wpsn-site-ids').val() || '');
    selectedSites = {};
    for (var i = 0; i < ids.length; i++) {
      selectedSites[String(ids[i])] = true;
    }
    setSelectedCount();
  }

  var sitesState = {
    page: 1,
    pages: 1,
    perPage: 20,
    search: ''
  };

  function renderSites(items) {
    var $body = $('#wpsn-sites-body');
    $body.empty();

    items = items || [];
    if (!items.length) {
      $body.append($('<tr></tr>').append($('<td colspan="4"></td>').text('No sites found.')));
      $('#wpsn-sites-select-page').prop('checked', false);
      return;
    }

    for (var i = 0; i < items.length; i++) {
      var it = items[i] || {};
      var id = it.id ? Number(it.id) : 0;
      if (!id) continue;

      var name = it.name ? String(it.name) : '';
      var domain = it.domain ? String(it.domain) : '';
      var path = it.path ? String(it.path) : '';
      var url = it.url ? String(it.url) : '';

      var label = name ? (name + ' — ' + domain + path) : (domain + path);

      var $tr = $('<tr></tr>');
      var $cb = $('<input type="checkbox" class="wpsn-site-check" />')
        .attr('data-id', String(id))
        .prop('checked', !!selectedSites[String(id)]);
      $tr.append($('<td></td>').append($cb));
      $tr.append($('<td></td>').text(String(id)));
      $tr.append($('<td></td>').text(label));
      $tr.append($('<td></td>').text(url));

      $body.append($tr);
    }

    // Update "select page" header checkbox state.
    var allChecked = true;
    $body.find('input.wpsn-site-check').each(function () {
      if (!$(this).is(':checked')) {
        allChecked = false;
      }
    });
    $('#wpsn-sites-select-page').prop('checked', allChecked);
  }

  function loadSites(page) {
    page = Number(page || 1);
    if (!isFinite(page) || page < 1) page = 1;

    sitesState.page = page;
    $('#wpsn-sites-page').text(String(sitesState.page));
    $('#wpsn-sites-pages').text(String(sitesState.pages));

    var $body = $('#wpsn-sites-body');
    $body.empty();
    $body.append($('<tr></tr>').append($('<td colspan="4"></td>').text('Loading…')));

    ajaxPost('wpsn_network_profile_sites_list', {
      page: sitesState.page,
      per_page: sitesState.perPage,
      search: sitesState.search
    })
      .done(function (res) {
        if (!res || !res.success) {
          var msg = (res && res.data && res.data.message) ? res.data.message : 'Failed to load sites.';
          $body.empty().append($('<tr></tr>').append($('<td colspan="4"></td>').text(msg)));
          return;
        }
        var d = res.data || {};
        sitesState.page = Number(d.page || 1);
        sitesState.pages = Number(d.pages || 1);
        if (!isFinite(sitesState.page) || sitesState.page < 1) sitesState.page = 1;
        if (!isFinite(sitesState.pages) || sitesState.pages < 1) sitesState.pages = 1;

        $('#wpsn-sites-page').text(String(sitesState.page));
        $('#wpsn-sites-pages').text(String(sitesState.pages));

        renderSites(d.items || []);
      })
      .fail(function () {
        $body.empty().append($('<tr></tr>').append($('<td colspan="4"></td>').text('Failed to load sites.')));
      });
  }

  function syncSitePickerDisabled() {
    var all = $('#wpsn-all-sites').is(':checked');
    $('#wpsn-site-ids').prop('disabled', all);

    var $picker = $('#wpsn-sites-selector');
    if ($picker.length) {
      $picker.find('input,button').prop('disabled', all);
      if (all) {
        $picker.css('opacity', '0.5');
      } else {
        $picker.css('opacity', '1');
      }
    }
  }

  // ----------------------------
  // Rollout + Dry run runner
  // ----------------------------
  function readForm() {
    var profileId = String($('#wpsn-profile-id').val() || '');
    var mode = String($('input[name="wpsn-profile-mode"]:checked').val() || 'settings');
    var allSites = $('#wpsn-all-sites').is(':checked') ? 1 : 0;

    var siteIds = String($('#wpsn-site-ids').val() || '').trim();
    if (!allSites && !siteIds) {
      var ids = selectedIds();
      if (ids.length) {
        siteIds = ids.join(',');
        // Keep input in sync for transparency.
        syncSiteIdsInputFromSelected();
      }
    }

    var applyRedirects = $('#wpsn-apply-redirects').is(':checked') ? 1 : 0;
    var applyIndexNow = $('#wpsn-apply-indexnow').is(':checked') ? 1 : 0;

    return {
      profile_id: profileId,
      mode: mode,
      all_sites: allSites,
      site_ids: siteIds,
      apply_redirects: applyRedirects,
      apply_indexnow: applyIndexNow
    };
  }

  function setRolloutProgress(done, total, ok, failed) {
    done = Number(done || 0);
    total = Number(total || 0);
    ok = Number(ok || 0);
    failed = Number(failed || 0);

    $('#wpsn-rollout-text').text(done + '/' + total);
    $('#wpsn-rollout-ok').text(ok);
    $('#wpsn-rollout-failed').text(failed);

    var pct = (total > 0) ? Math.round((done / total) * 100) : 0;
    if (pct < 0) pct = 0;
    if (pct > 100) pct = 100;
    $('#wpsn-rollout-bar').css('width', pct + '%');
  }

  function setDryProgress(done, total) {
    done = Number(done || 0);
    total = Number(total || 0);
    $('#wpsn-dry-text').text(done + '/' + total);

    var pct = (total > 0) ? Math.round((done / total) * 100) : 0;
    if (pct < 0) pct = 0;
    if (pct > 100) pct = 100;
    $('#wpsn-dry-bar').css('width', pct + '%');
  }

  function setDryStats(d) {
    d = d || {};
    $('#wpsn-dry-settings-changed').text(String(Number(d.settings_changed || 0)));
    $('#wpsn-dry-settings-unchanged').text(String(Number(d.settings_unchanged || 0)));
    $('#wpsn-dry-indexnow-changed').text(String(Number(d.indexnow_changed || 0)));
    $('#wpsn-dry-indexnow-unchanged').text(String(Number(d.indexnow_unchanged || 0)));
    $('#wpsn-dry-rewrite-flush').text(String(Number(d.rewrite_flush_needed || 0)));
    $('#wpsn-dry-redirect-rules').text(String(Number(d.redirect_rules || 0)));
    $('#wpsn-dry-redirect-upsert-sites').text(String(Number(d.redirect_upsert_sites || 0)));
  }

  function renderFailures(list, wrapSel, bodySel) {
    var $wrap = $(wrapSel);
    var $body = $(bodySel);
    $body.empty();

    if (!list || !list.length) {
      hide($wrap);
      return;
    }

    for (var i = 0; i < list.length; i++) {
      var row = list[i] || {};
      var sid = row.site_id ? Number(row.site_id) : 0;
      var err = row.error ? String(row.error) : '';
      var tr = $('<tr></tr>');
      tr.append($('<td></td>').text(sid ? String(sid) : ''));
      tr.append($('<td></td>').text(err));
      $body.append(tr);
    }

    show($wrap);
  }

  var running = false;
  var runningType = ''; // 'rollout' | 'dry'
  var cancelled = false;

  function disableButtons(disabled) {
    $('#wpsn-rollout-start').prop('disabled', !!disabled);
    $('#wpsn-rollout-dry').prop('disabled', !!disabled);
  }

  function finish() {
    running = false;
    runningType = '';
    cancelled = false;
    hide($('#wpsn-rollout-cancel'));
    disableButtons(false);
  }

  function startRollout() {
    if (running) return;
    cancelled = false;

    var data = readForm();
    if (!data.profile_id) {
      window.alert('Please select a profile.');
      return;
    }
    if (!data.all_sites && !data.site_ids) {
      window.alert('Please select “All sites” or choose sites / enter site IDs.');
      return;
    }

    running = true;
    runningType = 'rollout';
    disableButtons(true);

    show($('#wpsn-rollout-status'));
    hide($('#wpsn-dry-status'));
    show($('#wpsn-rollout-cancel'));

    setRolloutProgress(0, 0, 0, 0);
    renderFailures([], '#wpsn-rollout-failures', '#wpsn-rollout-failures-body');

    ajaxPost('wpsn_network_profile_rollout_start', data)
      .done(function (res) {
        if (!res || !res.success) {
          var msg = (res && res.data && res.data.message) ? res.data.message : 'Failed to start.';
          window.alert(msg);
          finish();
          return;
        }
        var d = res.data || {};
        setRolloutProgress(d.done || 0, d.total || 0, d.ok || 0, d.failed || 0);
        tick();
      })
      .fail(function (xhr) {
        var msg = 'Failed to start.';
        try {
          if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            msg = xhr.responseJSON.data.message;
          }
        } catch (e) { }
        window.alert(msg);
        finish();
      });
  }

  function startDry() {
    if (running) return;
    cancelled = false;

    var data = readForm();
    if (!data.profile_id) {
      window.alert('Please select a profile.');
      return;
    }
    if (!data.all_sites && !data.site_ids) {
      window.alert('Please select “All sites” or choose sites / enter site IDs.');
      return;
    }

    running = true;
    runningType = 'dry';
    disableButtons(true);

    show($('#wpsn-dry-status'));
    hide($('#wpsn-rollout-status'));
    show($('#wpsn-rollout-cancel'));

    setDryProgress(0, 0);
    setDryStats({
      settings_changed: 0,
      settings_unchanged: 0,
      indexnow_changed: 0,
      indexnow_unchanged: 0,
      rewrite_flush_needed: 0,
      redirect_rules: 0,
      redirect_upsert_sites: 0
    });
    renderFailures([], '#wpsn-dry-failures', '#wpsn-dry-failures-body');

    ajaxPost('wpsn_network_profile_rollout_dry_start', data)
      .done(function (res) {
        if (!res || !res.success) {
          var msg = (res && res.data && res.data.message) ? res.data.message : 'Dry run failed to start.';
          window.alert(msg);
          finish();
          return;
        }
        var d = res.data || {};
        setDryProgress(d.done || 0, d.total || 0);
        setDryStats(d);
        tick();
      })
      .fail(function (xhr) {
        var msg = 'Dry run failed to start.';
        try {
          if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            msg = xhr.responseJSON.data.message;
          }
        } catch (e) { }
        window.alert(msg);
        finish();
      });
  }

  function tick() {
    if (!running) return;

    if (cancelled) {
      var cancelAction = (runningType === 'dry')
        ? 'wpsn_network_profile_rollout_dry_cancel'
        : 'wpsn_network_profile_rollout_cancel';

      ajaxPost(cancelAction, {})
        .always(function () {
          finish();
        });
      return;
    }

    if (runningType === 'rollout') {
      ajaxPost('wpsn_network_profile_rollout_tick', {})
        .done(function (res) {
          if (!res || !res.success) {
            var msg = (res && res.data && res.data.message) ? res.data.message : 'Failed.';
            window.alert(msg);
            finish();
            return;
          }

          var d = res.data || {};
          setRolloutProgress(d.done || 0, d.total || 0, d.ok || 0, d.failed || 0);
          renderFailures(d.failures || [], '#wpsn-rollout-failures', '#wpsn-rollout-failures-body');

          if (d.finished) {
            finish();
            return;
          }

          setTimeout(tick, 400);
        })
        .fail(function (xhr) {
          var msg = 'Failed.';
          try {
            if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
              msg = xhr.responseJSON.data.message;
            }
          } catch (e) { }
          window.alert(msg);
          finish();
        });

      return;
    }

    // Dry run tick.
    ajaxPost('wpsn_network_profile_rollout_dry_tick', {})
      .done(function (res) {
        if (!res || !res.success) {
          var msg = (res && res.data && res.data.message) ? res.data.message : 'Dry run failed.';
          window.alert(msg);
          finish();
          return;
        }

        var d = res.data || {};
        setDryProgress(d.done || 0, d.total || 0);
        setDryStats(d);
        renderFailures(d.failures || [], '#wpsn-dry-failures', '#wpsn-dry-failures-body');

        if (d.finished) {
          finish();
          return;
        }

        setTimeout(tick, 400);
      })
      .fail(function (xhr) {
        var msg = 'Dry run failed.';
        try {
          if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            msg = xhr.responseJSON.data.message;
          }
        } catch (e) { }
        window.alert(msg);
        finish();
      });
  }

  // ----------------------------
  // DOM events
  // ----------------------------
  $(function () {
    // Toggle extra settings panel based on mode.
    function syncMode() {
      var mode = String($('input[name="wpsn-profile-mode"]:checked').val() || 'settings');
      if (mode === 'all') {
        $('#wpsn-profile-extra').show();
      } else {
        $('#wpsn-profile-extra').hide();
      }
    }
    $('input[name="wpsn-profile-mode"]').on('change', syncMode);
    syncMode();

    // Site picker table initial load.
    loadSites(1);

    // When manually typing IDs, update the internal selection map.
    $('#wpsn-site-ids').on('input', function () {
      setSelectionFromSiteIdsInput();
    });

    // Disable site IDs and picker when all-sites is checked.
    $('#wpsn-all-sites').on('change', syncSitePickerDisabled);
    syncSitePickerDisabled();

    // Search sites.
    $('#wpsn-sites-search-btn').on('click', function (e) {
      e.preventDefault();
      sitesState.search = String($('#wpsn-sites-search').val() || '').trim();
      loadSites(1);
    });

    $('#wpsn-sites-search').on('keypress', function (e) {
      if (e.which === 13) {
        e.preventDefault();
        sitesState.search = String($('#wpsn-sites-search').val() || '').trim();
        loadSites(1);
      }
    });

    // Pagination.
    $('#wpsn-sites-prev').on('click', function (e) {
      e.preventDefault();
      if (sitesState.page > 1) {
        loadSites(sitesState.page - 1);
      }
    });
    $('#wpsn-sites-next').on('click', function (e) {
      e.preventDefault();
      if (sitesState.page < sitesState.pages) {
        loadSites(sitesState.page + 1);
      }
    });

    // Clear selection.
    $('#wpsn-sites-clear-btn').on('click', function (e) {
      e.preventDefault();
      selectedSites = {};
      syncSiteIdsInputFromSelected();
      // Update visible checkboxes.
      $('#wpsn-sites-body').find('input.wpsn-site-check').prop('checked', false);
      $('#wpsn-sites-select-page').prop('checked', false);
    });

    // Select/unselect all on page.
    $('#wpsn-sites-select-page').on('change', function () {
      var checked = $(this).is(':checked');
      $('#wpsn-sites-body').find('input.wpsn-site-check').each(function () {
        var $cb = $(this);
        var id = $cb.attr('data-id');
        $cb.prop('checked', checked);
        if (checked) {
          selectedSites[String(id)] = true;
        } else {
          delete selectedSites[String(id)];
        }
      });
      syncSiteIdsInputFromSelected();
    });

    // Per-row checkbox change (delegated).
    $('#wpsn-sites-body').on('change', 'input.wpsn-site-check', function () {
      var $cb = $(this);
      var id = $cb.attr('data-id');
      if (!id) return;
      if ($cb.is(':checked')) {
        selectedSites[String(id)] = true;
      } else {
        delete selectedSites[String(id)];
      }
      syncSiteIdsInputFromSelected();

      // Update header checkbox state.
      var allChecked = true;
      $('#wpsn-sites-body').find('input.wpsn-site-check').each(function () {
        if (!$(this).is(':checked')) allChecked = false;
      });
      $('#wpsn-sites-select-page').prop('checked', allChecked);
    });

    // Buttons.
    $('#wpsn-rollout-start').on('click', function (e) {
      e.preventDefault();
      startRollout();
    });

    $('#wpsn-rollout-dry').on('click', function (e) {
      e.preventDefault();
      startDry();
    });

    $('#wpsn-rollout-cancel').on('click', function (e) {
      e.preventDefault();
      cancelled = true;
    });
  });
})(jQuery);
