(function () {
	'use strict';

	document.addEventListener('DOMContentLoaded', function () {
		var button = document.getElementById('orsc-rebuild-index');
		var status = document.getElementById('orsc-rebuild-status');
		var count = document.getElementById('orsc-index-count');
		var built = document.getElementById('orsc-index-built');

		if (!button || !window.ORSC_ADMIN) {
			return;
		}

		button.addEventListener('click', function () {
			var payload = new FormData();
			payload.append('action', 'orsc_rebuild_index');
			payload.append('nonce', window.ORSC_ADMIN.nonce);

			button.disabled = true;
			status.textContent = window.ORSC_ADMIN.i18n.rebuilding;

			fetch(window.ORSC_ADMIN.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				body: payload
			})
				.then(function (response) {
					return response.json();
				})
				.then(function (json) {
					if (!json || !json.success) {
						throw new Error(window.ORSC_ADMIN.i18n.error);
					}
					count.textContent = json.data.count;
					built.textContent = json.data.builtAt;
					status.textContent = json.data.message || window.ORSC_ADMIN.i18n.done;
				})
				.catch(function (error) {
					status.textContent = error.message || window.ORSC_ADMIN.i18n.error;
				})
				.finally(function () {
					button.disabled = false;
				});
		});
	});
}());

