jQuery(document).ready(function($) {
  let rowsPerPage = 20;
  let currentPage = 1;
  const ITEMS_PER_PAGE = 30;
  let selectionCurrentPage = 1;
  let allPosts = [];

  function escapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/[&<>"']/g, function(c) {
      return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      } [c];
    });
  }

  function escapeAttribute(str) {
    return escapeHtml(str).replace(/"/g, '&quot;');
  }

  function updateCounters() {
    $.post(mindwecoPlugin.ajax_url, {
      action: 'mindweco_get_stats',
      nonce: mindwecoPlugin.nonce
    }).done(function(response) {
      if (response.success) {
        const stats = response.data;
        $('#total').text(stats.total);
        $('#to-index-count').text(stats.to_index);
        $('#indexed-count').text(stats.indexed);
        $('#index-progress').text(stats.progress + '%');
      }
    }).fail(function(xhr, status, error) {
      MindwecoToast.error('Failed to update counters.');
    });
  }

  $('.nav-tab').on('click', function(e) {
    e.preventDefault();
    $('.nav-tab').removeClass('nav-tab-active');
    $(this).addClass('nav-tab-active');
    const tab = $(this).data('tab');
    $('.tab-content').hide();
    $('#tab-' + tab).show();
    if (tab === 'manage') {
      loadIndexedTable();
    }
    if (tab === 'selection') {
      mindwecoloadSelection();
    }
    if (tab === 'indexing') {
      updateCounters();
    }
  });

  $(document).on('click', '.mindweco-go-selection', function(e) {
    e.preventDefault();
    $('.nav-tab[data-tab="selection"]').trigger('click');
  });

  function mindwecoloadSelection() {
    $('#mindweco-selection-list').html('<p>Loading...</p>');
    $('#mindweco-selection-count').text('');
    $.post(mindwecoPlugin.ajax_url, {
      action: 'mindweco_get_selection',
      nonce: mindwecoPlugin.nonce,
    }, function(response) {
      if (response.success) {
        allPosts = response.data.posts;
        selectionCurrentPage = 1;
        renderSelectionPage(1);
      } else {
        $('#mindweco-selection-list').html('<p>Failed to load.</p>');
      }
    });
  }

  function renderSelectionList(posts) {
    var $list = $('#mindweco-selection-list');
    $list.empty();

    if (!posts || posts.length === 0) {
      $list.html('<p>No pages or posts found.</p>');
      return;
    }

    var pages = posts.filter(function(p) {
      return p.type === 'page';
    });
    var postsOnly = posts.filter(function(p) {
      return p.type === 'post';
    });

    function renderGroup(label, items) {
      if (!items.length) return;
      $list.append(
        '<p style="font-size:0.8em; text-transform:uppercase; font-weight:700; color:#666; margin:10px 0 4px;">' +
        escapeHtml(label) + '</p>'
      );
      items.forEach(function(post) {
        var checked = post.selected ? 'checked' : '';
        $list.append(
          '<label style="display:block; margin-bottom:8px; cursor:pointer;">' +
          '<input type="checkbox" class="mindweco-select-checkbox" value="' + post.id + '" data-post-id="' + post.id + '" ' + checked + '> ' +
          '<strong>' + escapeHtml(post.title) + '</strong> ' +
          '<span style="color:#999; font-size:0.85em;">— /' + escapeHtml(post.slug) + '</span>' +
          '</label>'
        );
      });
    }

    renderGroup('Pages', pages);
    renderGroup('Posts', postsOnly);
    updateSelectionCount();
  }

  function renderSelectionPage(page) {
      selectionCurrentPage = page;
      const start = (page - 1) * ITEMS_PER_PAGE;
      const end = start + ITEMS_PER_PAGE;
      const paginated = allPosts.slice(start, end);
      renderSelectionList(paginated);
      renderSelectionPagination(Math.ceil(allPosts.length / ITEMS_PER_PAGE), page);
  }

  function renderSelectionPagination(totalPages, page) {
      selectionCurrentPage = page;
      const $pag = $('#mindweco-selection-pagination');
      $pag.empty();
      if (totalPages <= 1) return;

      if (page > 1) {
          $pag.append(`<button class="mindweco-page-previous" data-page="${page - 1}">Previous</button>`);
      }

      let start = 1;
      let end = totalPages;

      if (totalPages > 8) {
          start = Math.max(page - 2, 1);
          end = Math.min(page + 2, totalPages);

          if (start > 1) {
              $pag.append(`<button class="mindweco-page-item" data-page="1">1</button>`);
              if (start > 2) {
                  $pag.append(`<span class="mindweco-page-ellipsis">...</span>`);
              }
          }
      }

      for (let p = start; p <= end; p++) {
          const active = p === page ? 'mindweco-page-active' : '';
          $pag.append(`<button class="mindweco-page-item ${active}" data-page="${p}">${p}</button>`);
      }

      if (totalPages > 8 && end < totalPages) {
          if (end < totalPages - 1) {
              $pag.append(`<span class="mindweco-page-ellipsis">...</span>`);
          }
          $pag.append(`<button class="mindweco-page-item" data-page="${totalPages}">${totalPages}</button>`);
      }

      if (page < totalPages) {
          $pag.append(`<button class="mindweco-page-next" data-page="${page + 1}">Next</button>`);
      }
  }

  $(document).on('click', '#mindweco-selection-pagination button', function () {
      const page = parseInt($(this).data('page'));
      if (page) renderSelectionPage(page);
  });

  function updateSelectionCount() {
    var count = allPosts.filter(function(post) {
      return post.selected;
    }).length;
    var total = allPosts.length;
    $('#mindweco-selection-count').text(count + ' of ' + total + ' selected');
  }

  function saveSelection() {
    clearTimeout(selectionSaveTimer);
    selectionSaveTimer = setTimeout(function() {
      var selectedIds = allPosts
        .filter(function(post) {
          return post.selected;
        })
        .map(function(post) {
          return post.id;
        });

      $('#mindweco-selection-count').text('Saving...');

      $.post(mindwecoPlugin.ajax_url, {
        action: 'mindweco_save_selection',
        nonce: mindwecoPlugin.nonce,
        selected_ids: selectedIds,
      }, function(response) {
        if (response.success) {
          MindwecoToast.success('Selection saved (' + response.data.count + ' items)');
          updateSelectionCount();
          updateCounters();
        } else {
          MindwecoToast.error('Failed to save selection.');
          updateSelectionCount();
        }
      });
    }, 600);
  }

  $('#mindweco-select-all').on('click', function() {
    allPosts.forEach(function(post) {
      post.selected = true;
    });
    renderSelectionPage(selectionCurrentPage);
    updateSelectionCount();
    saveSelection();
  });

  $('#mindweco-deselect-all').on('click', function() {
    allPosts.forEach(function(post) {
      post.selected = false;
    });
    renderSelectionPage(selectionCurrentPage);
    updateSelectionCount();
    saveSelection();
  });

  var selectionSaveTimer = null;

  $(document).on('change', '.mindweco-select-checkbox', function() {
    var postId = parseInt($(this).data('post-id'), 10);
    var selected = $(this).is(':checked');
    allPosts.forEach(function(post) {
      if (parseInt(post.id, 10) === postId) {
        post.selected = selected;
      }
    });
    updateSelectionCount();
    saveSelection();
  });

  function createPagination(pages, page) {
    currentPage = page;
    let str = `<div class="mindweco-pagination-container">`;

    if (page > 1) {
      str += `<button class="mindweco-page-previous" data-page="${page - 1}">Previous</button>`;
    }

    let start = 1;
    let end = pages;

    if (pages > 8) {
      start = Math.max(page - 2, 1);
      end = Math.min(page + 2, pages);
      if (start > 1) {
        str += `<button class="mindweco-page-item" data-page="1">1</button>`;
        if (start > 2) {
          str += `<span class="mindweco-page-ellipsis">...</span>`;
        }
      }
    }

    for (let p = start; p <= end; p++) {
      let active = page === p ? 'mindweco-page-active' : '';
      str += `<button class="mindweco-page-item ${active}" data-page="${p}">${p}</button>`;
    }

    if (pages > 8 && end < pages) {
      if (end < pages - 1) {
        str += `<span class="mindweco-page-ellipsis">...</span>`;
      }
      str += `<button class="mindweco-page-item" data-page="${pages}">${pages}</button>`;
    }

    if (page < pages) {
      str += `<button class="mindweco-page-next" data-page="${page + 1}">Next</button>`;
    }

    str += `</div>`;

    $('#pagination').html(str);
    displayRows();
  }

  $(document).on('click', '#pagination button', function(e) {
    e.preventDefault();
    var page = parseInt($(this).data('page'));
    if (page) {
      var table = document.getElementById('table-indexed');
      if (!table) return;
      var rows = table.getElementsByTagName('tr');
      var numRows = rows.length - 1;
      var numPages = Math.ceil(numRows / rowsPerPage);
      createPagination(numPages, page);
    }
  });

  function loadIndexedTable() {
    var $tbody = $('#table-indexed tbody');
    $tbody.html('<tr><td colspan="9">Loading...</td></tr>');
    $.post(mindwecoPlugin.ajax_url, {
      action: 'mindweco_get_indexed_table',
      nonce: mindwecoPlugin.nonce
    }).done(function(response) {
      if (response.success) {
        if (response.data && response.data.trim().length > 0) {
          $tbody.html(response.data);
          MindwecoToast.success('Indexed items loaded successfully');
          refreshPagination();
        } else {
          $tbody.html('<tr><td colspan="9">No indexed items found.</td></tr>');
          MindwecoToast.warning('No indexed items yet. Start indexing to see items here.');
        }
      } else {
        $tbody.html('<tr><td colspan="9">Failed to load.</td></tr>');
        MindwecoToast.error('Failed to load indexed items');
      }
    }).fail(function() {
      MindwecoToast.error('Failed to load indexed items');
      $tbody.html('<tr><td colspan="9">AJAX error.</td></tr>');
    });
    $('#search-input').val('').trigger('keyup');
  }

  function addRowToTable(item) {
    var $tbody = $('#table-indexed tbody');
    $tbody.find('tr td[colspan="9"]').closest('tr').remove();
    var newRow =
      '<tr style="display:none;" class="newly-indexed">' +
      '<td class="text-danger">—</td>' +
      '<td>' + escapeHtml(String(item.post_id)) + '</td>' +
      '<td>' + escapeHtml(item.item_id || 'N/A') + '</td>' +
      '<td>' + escapeHtml(item.category_id || '—') + '</td>' +
      '<td>' + escapeHtml(item.author || '—') + '</td>' +
      '<td>' + escapeHtml(item.title || 'Untitled') + '</td>' +
      '<td>' + escapeHtml(item.post_name || '—') + '</td>' +
      '<td>' + escapeHtml(item.post_status) + '</td>' +
      '<td>' +
      '<button class="button button-small button-link-delete unindex-item"' +
      ' data-item-id="' + escapeHtml(item.item_id || '') + '"' +
      ' data-category-id="' + escapeHtml(item.category_id || '') + '">' +
      '<span class="dashicons dashicons-trash"></span> UnIndex' +
      '</button>' +
      '</td>' +
      '</tr>';
    $tbody.prepend(newRow);
    $tbody.find('tr.newly-indexed').fadeIn(400, function() {
      $(this).removeClass('newly-indexed');
    });
  }

  $('#search-input').on('keyup', function() {
    var value = $(this).val().toLowerCase().trim();
    var visibleCount = 0;
    $('#table-indexed tbody tr').each(function() {
      var titleText = $(this).find('td:nth-child(6)').text().toLowerCase();
      if (titleText.includes(value)) {
        $(this).show();
        visibleCount++;
      } else {
        $(this).hide();
      }
    });
    if (visibleCount === 0) {
      if ($('#no-search-result').length === 0) {
        $('#table-indexed tbody').append(
          '<tr id="no-search-result"><td colspan="9" class="text-center text-muted">No matching items found.</td></tr>'
        );
      }
    } else {
      $('#no-search-result').remove();
    }
  });

  
  $('#mindweco-search-input-index-selection').on('keyup', function() {
    const value = $(this).val().toLowerCase().trim();

    if (value === '') {
        renderSelectionPage(selectionCurrentPage);
        $('#no-search-result').remove();
        return;
    }

    const filtered = allPosts.filter(p =>
        p.title.toLowerCase().includes(value) || p.slug.toLowerCase().includes(value)
    );

    renderSelectionList(filtered);
    $('#mindweco-selection-pagination').empty();

    if (filtered.length === 0) {
        if ($('#no-search-result').length === 0) {
            $('#mindweco-selection-list').append(
                '<p id="no-search-result" style="color:#999; padding:8px 0;">No matching posts/pages found.</p>'
            );
        }
    } else {
        $('#no-search-result').remove();
    }
  });

  function displayRows() {
    var table = document.getElementById('table-indexed');
    if (!table) return;
    var rows = table.getElementsByTagName('tr');
    var numRows = rows.length - 1;
    for (let i = 1; i <= numRows; i++) {
      rows[i].style.display = 'none';
    }
    var start = (currentPage - 1) * rowsPerPage + 1;
    var end = Math.min(currentPage * rowsPerPage, numRows);
    for (let i = start; i <= end; i++) {
      if (rows[i]) rows[i].style.display = '';
    }
  }

  function refreshPagination() {
    currentPage = 1;
    var table = document.getElementById('table-indexed');
    if (!table) return;
    var rows = table.getElementsByTagName('tr');
    var numRows = rows.length - 1;
    var numPages = Math.ceil(numRows / rowsPerPage);
    if (numPages > 0) {
      createPagination(numPages, 1);
    } else {
      if ($('#pagination').length) $('#pagination').html('');
    }
  }

  $('#mindweco-index-all-items').on('click', function(e) {
    e.preventDefault();
    var $button = $(this);
    var $resultDiv = $('#mindweco-index-all-result');
    var $progressContainer = $('#progress-container');
    var $progressBar = $('#progress-bar');
    var $progressText = $('#progress-text');

    $button.prop('disabled', true).html(
      '<span class="dashicons dashicons-update spin text-white"></span>' +
      ' <span class="spinner-text text-white">Indexing...</span>'
    );

    $progressContainer.show();
    $resultDiv.html('');
    $progressBar.removeClass('mindweco-progress-active').addClass('mindweco-progress-empty');
    $progressBar.css('width', '0%');
    $progressText.text('0%');

    $.post(mindwecoPlugin.ajax_url, {
      action: 'mindweco_index_all_items',
      nonce: mindwecoPlugin.nonce
    }).done(function(response) {
      if (response.success) {
        var results = response.data;
        var total = results.length;
        var success = results.filter(r => r.status === 'success').length;
        var already_indexed = results.filter(r => r.status === 'already_indexed').length;
        var failed = results.filter(r => r.status === 'failed').length;

        $progressBar.removeClass('mindweco-progress-empty').addClass('mindweco-progress-active');
        $progressBar.css('width', '100%');
        $progressText.text('100%');

        var failedItems = results.filter(r => r.status === 'failed');
        if (failedItems.length > 0) {
          MindwecoToast.warning(failedItems.length + ' items failed to index. Check details below.');
        }

        var isManageTabActive = $('.nav-tab[data-tab="manage"]').hasClass('nav-tab-active');
        if (isManageTabActive && success > 0) {
          var category_id = results.find(r => r.category_id)?.category_id || '';
          results.forEach(function(item) {
            if (item.status === 'success' && item.item_id) {
              addRowToTable({
                item_id: item.item_id,
                post_id: item.post_id,
                category_id: category_id,
                author: item.author || 'Unknown',
                title: item.title,
                post_name: item.post_name || 'untitled',
                post_status: item.post_status || 'publish'
              });
            }
          });
          setTimeout(refreshPagination, 500);
        }

        setTimeout(updateCounters, 3000);

        var html = '<div class="mindweco-result-success">';
        html += '<h3 class="indexing-complete-text"><i class="fa fa-check-circle text-success"></i> Indexing Complete!</h3>';
        html += '<p class="mindweco-paragraph-complete"><strong>Total:</strong> ' + total + '</p>';
        html += '<p class="mindweco-paragraph-complete"><strong>Success:</strong> <span style="color:#46b450;">' + success + '</span></p>';
        html += '<p class="mindweco-paragraph-complete"><strong>Already Indexed:</strong> <span style="color:#0073aa;">' + already_indexed + '</span></p>';
        html += '<p class="mindweco-paragraph-complete"><strong>Failed:</strong> <span style="color:#dc3232;">' + failed + '</span></p>';
        html += '</div>';
        html += '<details class="mt-3"><summary class ="fw-bold pe-auto">View Details</summary>';
        html += '<table class="wp-list-table widefat fixed striped mt-2">';
        html += '<thead><tr><th>Post ID</th><th>Title</th><th>Item ID</th><th>Status</th></tr></thead><tbody>';
        results.forEach(function(item) {
          var safeStatus = escapeHtml(item.status);
          var statusColor = safeStatus === 'failed' ? '#dc3232' :
            safeStatus === 'success' ? '#46b450' :
            '#0073aa';
          var statusIcon = safeStatus === 'failed' ? '<i class="fa fa-times-circle text-danger"></i>' :
            safeStatus === 'success' ? '<i class="fa fa-check-circle text-success"></i>' :
            safeStatus === 'already_indexed' ? '<i class="fa fa-circle"></i>' :
            '<i class="fa fa-circle-notch fa-spin"></i>';
          html += '<tr>';
          html += '<td>' + escapeHtml(String(item.post_id)) + '</td>';
          html += '<td>' + escapeHtml(item.title || 'N/A') + '</td>';
          html += '<td>' + escapeHtml(item.item_id || 'N/A') + '</td>';
          html += '<td style="color:' + statusColor + ';font-weight:bold;">' + statusIcon + ' ' + safeStatus + '</td>';
          html += '</tr>';
        });
        html += '</tbody></table></details>';
        $resultDiv.html(html);
      } else {
        var msg = response.data && response.data.message ?
          response.data.message :
          (typeof response.data === 'string' ? response.data : 'Indexing failed.');
        MindwecoToast.error(msg);
      }
    }).fail(function() {
      MindwecoToast.error('AJAX request failed.');
    }).always(function() {
      $button.prop('disabled', false).html(
        '<span class="dashicons dashicons-update text-white"></span> Start Indexing'
      );
    });
  });

  $('#mindweco-refresh-summary').on('click', function(e) {
    e.preventDefault();

    var $button = $(this);
    var originalHtml = '<span class="dashicons dashicons-update text-white"></span> Refresh summary';

    $button.prop('disabled', true).html(
      '<span class="dashicons dashicons-update spin text-white"></span>' +
      ' <span class="spinner-text text-white">Regenerating...</span>'
    );

    $.ajax({
        url: mindwecoPlugin.ajax_url,
        type: 'POST',
        data: {
          action: 'mindweco_regenerate_welcome',
          nonce: mindwecoPlugin.nonce
        },
        dataType: 'json'
      })

      .done(function(response) {

        if (response && response.success) {
          var newText = response.data.welcome_text;
          mindwecoPlugin.summary = newText;
          var formatted = newText.replace(/\n/g, '<br>');
          $('#mindweco-messages .default-welcome-message').html(formatted);

          MindwecoToast.success('Summary regenerated successfully!');

        } else {
          MindwecoToast.error('Server returned error: ' + (response?.data || 'Unknown'));
        }

        $button.prop('disabled', false).html(originalHtml);
      })

      .fail(function(xhr, status, error) {

        MindwecoToast.error('AJAX request failed');

        $button.prop('disabled', false).html(originalHtml);
      });
  });

  $(document).on('click', '.unindex-item', function(e) {
    e.preventDefault();
    e.stopPropagation();
    var button = $(this);
    var item_id = button.data('item-id');
    var category_id = button.data('category-id');
    var $row = button.closest('tr');
    if (!item_id || !category_id) {
      MindwecoToast.error('Missing item_id or category_id');
      return;
    }
    MindwecoModal.confirm('Confirm Unindex', 'Are you sure you want to unindex this item?', function() {
      var originalHtml = button.html();
      button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Unindexing...');
      $.post(mindwecoPlugin.ajax_url, {
        action: 'mindweco_delete_indexed_item',
        nonce: mindwecoPlugin.nonce,
        item_id: item_id,
        category_id: category_id
      }).done(function(response) {
        if (response.success) {
          MindwecoToast.success(response.data.message || 'Item unindexed successfully');
          $row.fadeOut(300, function() {
            $(this).remove();
            refreshPagination();
            updateCounters();
          });
          $('.mindweco-result-success details').hide();
          $('.mindweco-result-success').hide();
        } else {
          MindwecoToast.error('Error unindexing item');
          button.prop('disabled', false).html(originalHtml);
        }
      }).fail(function() {
        MindwecoToast.error('AJAX request failed');
        button.prop('disabled', false).html(originalHtml);
      });
    }, 'Unindex', 'btn-danger');
  });

  $('#mindweco-unindex-all-items').on('click', function() {
    var $progressBar = $('#progress-bar');
    var $progressText = $('#progress-text');
    MindwecoModal.confirm('Confirm Unindex', 'Are you sure you want to unindex all items?', function() {
      const $result = $('#mindweco-unindex-result');
      $result.html('<i class="fas fa-spinner fa-spin" style="margin-right:5px;"></i> Unindexing all items...').show();
      $.post(mindwecoPlugin.ajax_url, {
        action: 'mindweco_unindex_all_items',
        nonce: mindwecoPlugin.nonce
      }).done(function(response) {
        if (response.success) {
          updateCounters();
          $progressBar.removeClass('mindweco-progress-active').addClass('mindweco-progress-empty');
          $progressBar.css('width', '0%');
          $progressText.text('0%');
          setTimeout(function() {
            MindwecoToast.success('All items have been unindexed.');
            $result.text(response.data.message);
            setTimeout(function() {
              $result.fadeOut(1000);
            }, 3000);
          }, 1500);
          $('#table-indexed tbody').html('<tr><td colspan="9">No indexed items found.</td></tr>');
          $('.nav-tab[data-tab="indexing"]').click();
          $('#mindweco-index-all-result').empty().hide();
          $('#progress-container').hide();
        } else {
          MindwecoToast.error('Error unindexing all items.');
          $result.fadeOut(1000);
        }
      }).fail(function() {
        MindwecoToast.error('AJAX request failed.');
        $result.fadeOut(1000);
      });
    }, 'Unindex', 'btn-danger');
  });

  $(document).on('click', '.submitdelete', function() {
    setTimeout(function() {
      updateCounters();
    }, 2000);
  });

  $(document).on('click', '.btn-index-items', function() {
    $('.nav-tab[data-tab="indexing"]').click();
  });

  $('<style>.spin{animation:spin 1s linear infinite;}@keyframes spin{100%{transform:rotate(360deg);}}</style>').appendTo('head');

  if ($('.notice-success').length > 0) {
    $('.nav-tab[data-tab="selection"]').click();
  }

  $('.notice-success').delay(3000).fadeOut(1000);

  if (document.getElementById('table-indexed')) {
    refreshPagination();
  }

  var askRange = document.getElementById('mindweco_ask_setting');
  var askValue = document.getElementById('mindweco_ask_setting_value');
  if (askRange) {
    var updateAskRange = function () {
      var value = parseInt(askRange.value || '0', 10);
      var min = parseInt(askRange.min || '0', 10);
      var max = parseInt(askRange.max || '0', 10);
      if (askValue) {
        askValue.textContent = value;
      }
      if (max > min) {
        askRange.style.setProperty('--mindweco-range-progress', (((value - min) / (max - min)) * 100) + '%');
      }
    };
    askRange.addEventListener('input', updateAskRange);
    updateAskRange();
  }

  var countInput = document.getElementById('mindweco_services_count');
  var repeater = document.getElementById('mindweco-services-repeater');
  if (!countInput || !repeater) {
    return;
  }

  var initialData = [];
  try {
    initialData = JSON.parse(repeater.getAttribute('data-services') || '[]');
  } catch (e) {
    initialData = [];
  }

  var lastServiceRows = Array.isArray(initialData) ? initialData.slice() : [];

  function collectServiceRows() {
    return Array.prototype.slice.call(repeater.querySelectorAll('.mindweco-service-row')).map(function (row) {
      return {
        title: row.querySelector('.mindweco-service-title-input') ? row.querySelector('.mindweco-service-title-input').value : '',
        description: row.querySelector('.mindweco-service-description-input') ? row.querySelector('.mindweco-service-description-input').value : '',
        url: row.querySelector('.mindweco-service-url-input') ? row.querySelector('.mindweco-service-url-input').value : ''
      };
    });
  }

  function renderServiceRows(dataOverride) {
    var count = parseInt(countInput.value || '0', 10);
    if (Number.isNaN(count) || count < 0) {
      count = 0;
    }
    countInput.value = count;

    var currentRows = collectServiceRows();
    var data = Array.isArray(dataOverride) ? dataOverride : (currentRows.length ? currentRows : lastServiceRows);
    if (!Array.isArray(data)) {
      data = [];
    }
    lastServiceRows = data.slice();
    repeater.innerHTML = '';

    for (var i = 0; i < count; i++) {
      var item = data[i] || {};
      var row = document.createElement('div');
      row.className = 'mindweco-service-row';
      row.innerHTML =
        '<div class="mindweco-service-row-head"><strong>Service ' + (i + 1) + '</strong>' +
        '<button type="button" style="align-items:center;" class="button-link-delete mindweco-service-delete-row" aria-label="' + escapeAttribute('Delete service ' + (i + 1)) + '" title="' + escapeAttribute('Delete service ' + (i + 1)) + '">' +
        '<span class="dashicons dashicons-trash" aria-hidden="true"></span><span>Delete</span>' +
        '</button></div>' +
        '<input type="text" name="mindweco_service_title[]" class="settings-field-input mindweco-service-title-input" placeholder="Service title" value="' + escapeAttribute(item.title || '') + '" required>' +
        '<input type="url" name="mindweco_service_url[]" class="settings-field-input mindweco-service-url-input" placeholder="https://example.com/service" value="' + escapeAttribute(item.url || '') + '" required>' +
        '<textarea name="mindweco_service_description[]" class="settings-field-input mindweco-service-description-input" rows="2" placeholder="Service description">' + escapeHtml(item.description || '') + '</textarea>';
      repeater.appendChild(row);
    }
  }

  $(repeater).on('click', '.mindweco-service-delete-row', function (event) {
    event.preventDefault();
    event.stopPropagation();

    var button = $(this);
    var $row = button.closest('.mindweco-service-row');
    var rowIndex = $(repeater).find('.mindweco-service-row').index($row);

    if (rowIndex < 0) {
      return;
    }

    MindwecoModal.confirm(
      'Confirm Delete Service',
      'Are you sure you want to delete this service?',
      function () {
        var rows = collectServiceRows();
        var originalHtml = button.html();

        button.prop('disabled', true).html('<span class="dashicons dashicons-update spin" aria-hidden="true"></span> Deleting...');

        $.post(mindwecoPlugin.ajax_url, {
          action: 'mindweco_delete_service',
          nonce: mindwecoPlugin.nonce,
          row_id: rowIndex
        }).done(function (response) {
          if (response && response.success) {
            rows.splice(rowIndex, 1);
            countInput.value = rows.length;
            renderServiceRows(rows);
            MindwecoToast.success((response.data && response.data.message) ? response.data.message : 'Service deleted successfully');
            return;
          }

          MindwecoToast.error((response && response.data && response.data.message) ? response.data.message : 'Error deleting service');
          button.prop('disabled', false).html(originalHtml);
        }).fail(function () {
          MindwecoToast.error('AJAX request failed');
          button.prop('disabled', false).html(originalHtml);
        });
      },
      'Delete Service',
      'btn-danger'
    );
  });

  function validateServiceRows(event) {
    var count = parseInt(countInput.value || '0', 10);
    if (!count) {
      return true;
    }

    var rows = Array.prototype.slice.call(repeater.querySelectorAll('.mindweco-service-row'));
    for (var i = 0; i < rows.length; i++) {
      var titleInput = rows[i].querySelector('.mindweco-service-title-input');
      var urlInput = rows[i].querySelector('.mindweco-service-url-input');
      var title = titleInput ? titleInput.value.trim() : '';
      var url = urlInput ? urlInput.value.trim() : '';

      if (!title || !url) {
        event.preventDefault();
        alert('Each service must include both a title and a URL.');
        if (!title && titleInput) {
          titleInput.focus();
        } else if (urlInput) {
          urlInput.focus();
        }
        return false;
      }
    }

    return true;
  }

  countInput.addEventListener('input', renderServiceRows);
  repeater.closest('form').addEventListener('submit', validateServiceRows);
  renderServiceRows();

  updateCounters();
});
