import { formatPriceElement, tippyUpdateTemplate } from './utils.js';

jQuery(function ($) {
	$(document).on('input', '.thousand-separator', function (e) {
		formatPriceElement($(this));
	});

	$('.thousand-separator').each(function () {
		formatPriceElement($(this));
	})

	$(document).on('click', '.toggle-show-password', function (e) {
		e.preventDefault();
		var $button = $(this);
		var $input = $button.parent().find('input');
		var $icon = $button.find('.icon');

		if ($input.attr('type') === 'password') {
			$input.attr('type', 'text');
			$button.attr('aria-label', 'Hide password');
			$icon.removeClass('icon-eye').addClass('icon-eye-off');
		} else {
			$input.attr('type', 'password');
			$button.attr('aria-label', 'Show password');
			$icon.removeClass('icon-eye-off').addClass('icon-eye');
		}

		$input.focus();
	});

	// perms select/deselect
	$(document).on('click', '.modal-perms .btn-toggle-select-all', function () {
		const $modal = $(this).closest('.modal-perms');
		const $checkboxes = $modal.find('input[type="checkbox"][name^="caps"]');
		const allChecked = $checkboxes.length === $checkboxes.filter(':checked').length;

		if (allChecked) {
			$checkboxes.prop('checked', false);
		} else {
			$checkboxes.prop('checked', true);
		}
	});

});



jQuery(function ($) {

	MicroModal.init({});

	const originalClose = MicroModal.close;

	MicroModal.close = function (id) {
		let onClose = $('#' + id).data('on-close');
		if (onClose) onClose();
		originalClose(id);
	}

	$('.modal__close').off('click');

	// allow multiple instances(nested)
	$(document).on('click', '.modal__close', function (e) {
		if ($(e.target).hasClass('modal__overlay') || $(e.target).hasClass('modal__close')) {
			var id = $(this).closest('.micro-modal').attr('id');
			MicroModal.close(id);
		}
	})

	$(document).on('click', '.modal__overlay', function (e) {
		e.stopPropagation();
		if ($(e.target).hasClass('modal__overlay')) {
			var existingNestedOpenModal = $(this).find('.micro-modal.is-open').last();
			var modalToClose = existingNestedOpenModal.length
				? existingNestedOpenModal
				: $(this).closest('.micro-modal')

			MicroModal.close(modalToClose.attr('id'));
		}
	})

});


jQuery(function ($) {
	$('a.menu__item').click(function () {
		$('.anbarak_page_content').addClass('transition duration-800 scale-97 origin-top')
		$('.loading-screen').addClass('is-active');

		const loadingText = document.querySelector('.loading-screen__secondary-message');

		const quickMessages = [
			"Preparing something great...",
			"Preparing something great...",
			"Time is money. We saved you both.",
			"Good things take time...",
			"Good things take time...",
			"Cooking things up.",
			"Almost ready.",
			"Managing inventory like a pro",
		];


		function getRandom(arr) {
			return arr[Math.floor(Math.random() * arr.length)];
		}

		loadingText.textContent = getRandom(quickMessages);

	})


	$('#toggle-main-menu').click(function () {
		if ($('aside .menu').hasClass('is-open')) {
			$('aside .menu').removeClass('is-open');
		} else {
			$('aside .menu').addClass('is-open');
		}
	})

	// expense
	$(document).on('click', 'button.btn-edit-expense', function () {
		var expenseId = $(this).attr('data-expense-id');
		var $button = $(this);

		$button.addClass('loading');

		$.ajax({
			method: 'GET',
			url: anbarak.ajax_url,
			data: {
				id: expenseId,
					action: 'anbarak_get_expense_json',
				security: anbarak.nonce
			},
		}).done(function (data) {
			var $form = $('form[name="frm-edit-expense"]');
			$form.find('input[name="id"]').val(expenseId);
			$form.find('input[name="price"]').val(data.price);
			$form.find('textarea[name="notes"]').val(data.notes);
			$form.find('select[name="tag"]').val(data.tag_id);
			$form.find('input[name="buy_tax"]').val(data.tax_rate || "");
			$form.find('input[name="buy_discount"]').val(data.buy_discount);
			$form.find('input[name="invoice_number"]').val(data.invoice_number);
			$form.find('select[name="payment_method"]').val(data.payment_method || '');

			window.anbarakSetDatePickerValue($form.find('input[name="date"]'), data.timestamp * 1000);

			formatPriceElement($form.find('input[name="price"]'));
			MicroModal.show('modal-purchase-edit', {
				onShow: () => $('#expense-' + expenseId).addClass('highlight'),
			});
			$('#modal-purchase-edit').data('on-close', () => $('#expense-' + expenseId).removeClass('highlight'))
			$button.removeClass('loading');
		}).fail(function (response) { })
	});

	// expense submit 
	$('form[name="frm-new-expense"]').on('submit', function (e) {
		e.preventDefault();
		var $form = $(this);
		var $button = $form.find('button[type="submit"]');

		$button.addClass('loading');

		$.ajax({
			method: 'POST',
			url: anbarak.ajax_url,
			data: $form.serialize(),
			dataType: 'html'
		}).done(function (html) {
			MicroModal.close('modal-3');
			$('.expenses-list-wrap tbody').prepend(html);
			setTimeout(() => {
				$('.expenses-list-wrap tbody tr:first-of-type').addClass('highlight')
				setTimeout(() => {
					$('.expenses-list-wrap tbody tr:first-of-type').removeClass('highlight')
				}, 600);
			}, 100);

			$form[0].reset();

			$button.removeClass('loading');
		}).fail(function (response) { })
	});

	// expense submit edit
	$('form[name="frm-edit-expense"]').on('submit', function (e) {
		e.preventDefault();
		var $form = $(this);
		var expenseId = $form.find('input[name="id"]').val();
		var $button = $form.find('button[type="submit"]');

		$button.addClass('loading');

		$.ajax({
			method: 'POST',
			url: anbarak.ajax_url,
			data: $form.serialize(),
			dataType: 'html'
		}).done(function (html) {
			MicroModal.close('modal-purchase-edit');
			$('#expense-' + expenseId).html(html);
			setTimeout(() => {
				$('#expense-' + expenseId).addClass('product-row-update-highlight')
				setTimeout(() => {
					$('#expense-' + expenseId).removeClass('product-row-update-highlight')
				}, 1000);
			}, 200);
			$button.removeClass('loading');
		}).fail(function (response) { })
	});


	$(document).on('click', '.btn-delete-expense', function (e) {
		e.preventDefault();
		var $form = $(this).parents('form');
		var expense_id = $form.find('input[name="eid"]').val();

		$('#expense-' + expense_id).addClass('highlight');

		setTimeout(() => {

			anbarakConfirmAsync({
				message: anbarak.i18n.delete_confirm,
				type: 'ok-cancel',
			}).then(function (confirmed) {
				if (!confirmed) {
					$('#expense-' + expense_id).removeClass('highlight')
					return false;
				}

				var $button = $form.find('button[type="submit"]');
				$button.addClass('loading');

				$.ajax({
					method: 'POST',
					url: anbarak.ajax_url,
					data: $form.serialize(),
					dataType: 'json'
				}).done(function (data) {
					$('#expense-' + expense_id).addClass('highlight--red')
					$('#expense-' + expense_id).hide(500);
				}).fail(function (response) { })
			});

		}, 100);
	})

	// Function to activate a tab
	function activateTab(tabId) {
		$('.tabs .tab-item').removeClass('active');
		$('.tabs .tabs__content > div').removeClass('active');

		// Activate the tab link
		$('.tabs .tab-item a[href="#' + tabId + '"]').parent().addClass('active');
		// Activate the tab content
		$('.tabs #tab-' + tabId).addClass('active');

		// Save to localStorage
		localStorage.setItem('activeTab', tabId);

		// Update URL hash (optional)
		window.location.hash = tabId;
	}

	// Tab click handler
	$('.tabs .tab-item > a').click(function (e) {
		e.preventDefault();
		const tabId = $(this).attr('href').split('#')[1];
		activateTab(tabId);
	});

	// On page load
	$(document).ready(function () {

		if (!$('.tabs').length) return;

		const hashTab = window.location.hash.replace('#', '');

		if (hashTab && $('.tabs #tab-' + hashTab).length) {
			activateTab(hashTab);
		}
		else {
			const savedTab = localStorage.getItem('activeTab');
			if (savedTab && $('.tabs #tab-' + savedTab).length) {
				activateTab(savedTab);
			}
			// Otherwise use default active tab
			else {
				if ($('.tabs .tab-item.active a').attr('href')) {
					const defaultActiveTab = $('.tabs .tab-item.active a').attr('href').split('#')[1];
					if (defaultActiveTab) {
						activateTab(defaultActiveTab);
					}
				}
			}
		}
	});

	// Optional: Handle browser back/forward buttons
	$(window).on('hashchange', function () {
		const hashTab = window.location.hash.replace('#', '');
		if (hashTab && $('.tabs #tab-' + hashTab).length) {
			activateTab(hashTab);
		}
	});


	$('#notification-btn').on('click', function (e) {
		e.stopPropagation();
		$('#notification-popup').toggleClass('hidden');
	});

	$(document).on('click', '.mark-notification-read', function () {
		var $item = $(this).closest('.notification-item');
		$.post(anbarak.ajax_url, {
			action: 'anbarak_mark_notification_read',
			product_id: $item.data('product-id'),
			security: anbarak.nonce
		}).done(function () {
			$item.remove();
			var $badge = $('#notification-btn > span');
			if ($badge.length) {
				var count = parseInt($badge.text(), 10) - 1;
				count > 0 ? $badge.text(count) : $badge.remove();
			}
			if (!$('#notification-popup .notification-item').length) {
				$('#notification-popup ul').replaceWith('<div class="no-notifications p-10 text-center text-gray-400"><span class="icon icon-bell text-3xl"></span><p class="mt-3">' + (anbarak.i18n.no_notifications || 'No Notifications') + '</p></div>');
			}
		});
	});

	// Fullscreen toggle
	$(document).on('click', '#btn-enter-fullscreen', function () {
		$.post(anbarak.ajax_url, {
			action: 'anbarak_toggle_fullscreen',
			fullscreen: '1',
			security: anbarak.nonce
		}).always(function () {
			window.location.reload();
		});
	});

	$(document).on('click', '#btn-exit-fullscreen', function () {
		$.post(anbarak.ajax_url, {
			action: 'anbarak_toggle_fullscreen',
			fullscreen: '0',
			security: anbarak.nonce
		}).always(function () {
			window.location.reload();
		});
	});

	$(document).on('click', '#btn-dismiss-fullscreen-hint', function () {
		$('#fullscreen-hint').slideUp(200);
		$.post(anbarak.ajax_url, {
			action: 'anbarak_dismiss_fullscreen_hint',
			security: anbarak.nonce
		});
	});

	// Close on click outside
	$(document).on('click', function (e) {
		if (!$(e.target).closest('#notification-center').length) {
			$('#notification-popup').addClass('hidden');
		}
	});

	$('#btn-export-excel').on('click', function (e) {
		e.preventDefault();

		const $form = $('form.product-search');

		let params = $form.serialize();

		// replace action
		params = params.replace(
			'action=anbarak_product_search',
			'action=anbarak_export_product_search'
		);

		const url = anbarak.ajax_url + '?' + params;
		window.location.href = url;
	});


});


// auto-detect system preference
(function () {
	var mql = window.matchMedia('(prefers-color-scheme: dark)');

	function applyDarkMode(isDark) {
		document.documentElement.classList.toggle('dark', isDark);
	}

	applyDarkMode(mql.matches);

	mql.addEventListener('change', function (e) {
		applyDarkMode(e.matches);
	});
})();


tippyUpdateTemplate();
