(function ($) {
	"use strict";

	const SifencyAgeGate = function ($scope) {
		const $overlay = $scope.find('.sifency-age-gate-overlay');
		const $error = $scope.find('.sifency-ag-error-msg');

		if (!$overlay.length) return;

		// Default configuration
		let settings = {
			method: 'buttons',
			age: 18,
			days: 30,
			redirect: 'no',
			redirect_url: ''
		};

		// Parse Widget Settings
		try {
			const dataSettings = $overlay.data('ag-settings');
			if (dataSettings) {
				settings = $.extend({}, settings, dataSettings);
			}
		} catch (e) {
			console.error('Sifency Age Gate: Failed to parse settings.', e);
		}

		const COOKIE_KEY = 'sifency_age_verified';
		const isEditMode = typeof elementorFrontend !== 'undefined' ? elementorFrontend.isEditMode() : false;

		// --- Utilities ---
		const getCookie = (name) => {
			const value = `; ${document.cookie}`;
			const parts = value.split(`; ${name}=`);
			if (parts.length === 2) return parts.pop().split(';').shift();
			return null;
		};

		const setCookie = (name, value, days) => {
			let expires = '';
			if (days) {
				const date = new Date();
				date.setTime(date.getTime() + (days * 86400000));
				expires = '; expires=' + date.toUTCString();
			}
			document.cookie = `${name}=${value}${expires}; path=/`;
		};

		// --- Visibility Logic ---
		if (getCookie(COOKIE_KEY) !== 'true' || isEditMode) {
			$overlay.css('display', 'flex');
			// Lock scroll if we are on the live site
			if (!isEditMode) $('body').css('overflow', 'hidden');
		} else {
			$overlay.remove();
			return; // Stop execution if verified
		}

		// --- Actions ---
		const approve = () => {
			if (!isEditMode) {
				setCookie(COOKIE_KEY, 'true', settings.days);
				$('body').css('overflow', '');
			}
			$overlay.fadeOut(400, function () {
				if (!isEditMode) $(this).remove();
			});
		};

		const deny = () => {
			if (settings.redirect === 'yes' && settings.redirect_url) {
				window.location.href = settings.redirect_url;
			} else {
				$scope.find('.sifency-ag-actions').slideUp(300, () => {
					$error.fadeIn(300);
				});
			}
		};

		// --- Event Listeners ---
		$scope.find('.sifency-ag-yes').on('click', (e) => {
			e.preventDefault();
			approve();
		});

		$scope.find('.sifency-ag-no').on('click', (e) => {
			e.preventDefault();
			deny();
		});

		$scope.find('.sifency-ag-submit').on('click', (e) => {
			e.preventDefault();

			const d = parseInt($scope.find('.ag-day').val(), 10);
			const m = parseInt($scope.find('.ag-month').val(), 10);
			const y = parseInt($scope.find('.ag-year').val(), 10);

			if (!d || !m || !y || m < 1 || m > 12 || d < 1 || d > 31) {
				$error.text('Please enter a valid date.').fadeIn();
				return;
			}

			// Accurate Age Calculation
			const birthDate = new Date(y, m - 1, d);
			const today = new Date();
			let age = today.getFullYear() - birthDate.getFullYear();
			const mDiff = today.getMonth() - birthDate.getMonth();

			// If birth month hasn't occurred yet, or it's birth month but day hasn't occurred
			if (mDiff < 0 || (mDiff === 0 && today.getDate() < birthDate.getDate())) {
				age--;
			}

			if (age >= settings.age) {
				approve();
			} else {
				deny();
			}
		});
	};

	$(window).on('elementor/frontend/init', function () {
		elementorFrontend.hooks.addAction('frontend/element_ready/sifency-content-restriction.default', SifencyAgeGate);
	});

})(jQuery);