export function debounce(func, timeout = 300) {
	let timer;
	return (...args) => {
		clearTimeout(timer);
		timer = setTimeout(() => { func.apply(this, args); }, timeout);
	};
}

export function calcIncreasePercent(originalVal, newVal) {
	originalVal = originalVal.match('/\d+/g').join("");
	newVal = newVal.match('/\d+/g').join("");
	return ((newVal - originalVal) / originalVal) * 100
}

export function isFormChanged(form) {
	for (const el of form.elements) {
		if (!el.name || el.disabled) continue;
		if (el.type === 'checkbox' || el.type === 'radio') {
			if (el.checked !== el.defaultChecked) return true;
		} else if (el.tagName === 'SELECT') {
			const selectedIndex = el.selectedIndex;
			const defaultOption = Array.from(el.options).find(o => o.defaultSelected);
			const defaultIndex = defaultOption ? defaultOption.index : 0;
			if (selectedIndex !== defaultIndex) return true;
		} else if (el.value !== el.defaultValue) {
			return true;
		}
	}
	return false;
}


export function parsePrice(str) {
  return parseFloat(str.replace(/[^0-9.]/g, ''));
}

export function formatPrice(value) {
    if (value === '' || value === '-' || value === null || value === undefined) {
        return value;
    }

    const isNegative = value.toString().startsWith('-');
    const cleanValue = value.toString().replace(/,/g, '').trim();

    if (!/^-?\d*\.?\d*$/.test(cleanValue) || cleanValue === '.') {
        return cleanValue === '.' ? '.' : value;
    }

    const numericStr = isNegative ? cleanValue.substring(1) : cleanValue;
    const parts = numericStr.split('.');
    const integerPart = parts[0];
    const decimalPart = parts.length > 1 ? '.' + parts[1] : '';

    let formattedInteger = integerPart ? integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '';
    let formattedValue = formattedInteger + decimalPart;

    if (formattedValue === '') {
        formattedValue = '.';
    }

    if (isNegative && numericStr !== '' && parseFloat(numericStr) !== 0) {
        formattedValue = '-' + formattedValue;
    }

    return formattedValue;
}

export function formatPriceElement($element) {
    const inputValue = $element.is('input') ? $element.val() : $element.text();
    const formatted = formatPrice(inputValue);
    
    if (formatted !== inputValue) {
        $element.is('input') ? $element.val(formatted) : $element.text(formatted);
    }
}

export function numberWithCommas(x) {
    return formatPrice(x);
}

export function setCookie(name, value, days) {
	var expires = "";
	name = 'anbaarak_' + name;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toUTCString();
	}
	document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

export function getCookie(name) {
	name = 'anbaarak_' + name;
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

export function eraseCookie(name) {
	name = 'anbaarak_' + name;
	document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

tippy('[data-tippy-content]', {
	delay: [200, 200],
});

export function tippyUpdateTemplate() {
	tippy('.tippy-template', {
		content(reference) {
			const id = reference.getAttribute('data-template');
			const template = document.getElementById(id);
			return template.innerHTML;
		},
		allowHTML: true,
	});
};