/**
 * Enqueue Script
 *
 * @package     wpfaqblock
 */

(function () {
	/**
	 * Check if a color string is a valid, usable color
	 * (not transparent, not black, not white, not grey).
	 */
	function isValidAccentColor(color) {
		if (!color || color === 'transparent' || color === 'rgba(0, 0, 0, 0)') return false;

		var match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
		if (!match) return false;

		var r = parseInt(match[1]);
		var g = parseInt(match[2]);
		var b = parseInt(match[3]);

		if (r < 40 && g < 40 && b < 40) return false;
		if (r > 220 && g > 220 && b > 220) return false;

		var max = Math.max(r, g, b);
		var min = Math.min(r, g, b);
		if ((max - min) < 25) return false;

		return true;
	}

	/**
	 * Convert rgb/rgba string to hex.
	 */
	function rgbToHex(rgb) {
		var match = rgb.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
		if (!match) return null;
		var r = parseInt(match[1]).toString(16).padStart(2, '0');
		var g = parseInt(match[2]).toString(16).padStart(2, '0');
		var b = parseInt(match[3]).toString(16).padStart(2, '0');
		return '#' + r + g + b;
	}

	/**
	 * Try to resolve a CSS variable value (possibly nested).
	 */
	function resolveCSSVar(varName, el) {
		var target = el || document.documentElement;
		var rawValue = getComputedStyle(target).getPropertyValue(varName).trim();
		if (!rawValue) return null;
		// If it's itself a var(), resolve it recursively (1 level)
		var nestedMatch = rawValue.match(/^var\((--[^,)]+)/);
		if (nestedMatch) {
			return resolveCSSVar(nestedMatch[1], target);
		}
		return rawValue;
	}

	function detectSitePrimaryColor() {
		var rootStyles = getComputedStyle(document.documentElement);

		// --- 1. Check popular theme CSS variables directly ---
		var themeVars = [
			// Kadence Theme
			'--global-palette1',
			'--global-palette2',
			'--global-palette3',
			// Astra Theme
			'--ast-global-color-0',
			'--ast-global-color-1',
			'--ast-global-color-2',
			// GeneratePress
			'--gp-button-background-color',
			// OceanWP, Blocksy, Hello, Neve, etc.
			'--color-primary',
			'--primary-color',
			'--accent-color',
			'--brand-primary',
			'--site-primary',
			'--wp--preset--color--primary',
			'--wp--preset--color--vivid-cyan-blue',
		];

		for (var v = 0; v < themeVars.length; v++) {
			var val = resolveCSSVar(themeVars[v]);
			if (!val) continue;
			if (/^#[0-9a-f]{3,6}$/i.test(val)) {
				return val;
			}
			if (isValidAccentColor(val)) return val;
		}

		// --- 2. Fallback: scan button/link background colors ---
		var buttonSelectors = [
			'button',
			'.btn',
			'.button',
			'input[type="submit"]',
			'input[type="button"]',
			'[class*="btn-primary"]',
			'[class*="btn-main"]',
			'[class*="cta"]',
			'.wp-block-button__link',
		];

		for (var i = 0; i < buttonSelectors.length; i++) {
			var el = document.querySelector(buttonSelectors[i]);
			if (!el) continue;
			var bg = window.getComputedStyle(el).backgroundColor;
			if (isValidAccentColor(bg)) return bg;
		}

		// --- 3. Fallback: scan link/nav colors ---
		var linkSelectors = ['nav a', 'header a', '.menu-item a', 'a'];
		for (var j = 0; j < linkSelectors.length; j++) {
			var lel = document.querySelector(linkSelectors[j]);
			if (!lel) continue;
			var fg = window.getComputedStyle(lel).color;
			if (isValidAccentColor(fg)) return fg;
		}

		return null;
	}

	var _lastColor = null;

	function applyThemeColors() {
		var wrappers = document.querySelectorAll('.faq-plugin-wrapper');
		if (!wrappers.length) return;

		var detected = detectSitePrimaryColor();
		if (!detected) return;

		var finalColor = detected;
		if (detected.indexOf('rgb') !== -1) {
			var hex = rgbToHex(detected);
			if (hex) finalColor = hex;
		}

		if (finalColor === _lastColor) return;
		_lastColor = finalColor;

		wrappers.forEach(function (wrapper) {
			wrapper.style.setProperty('--faq-primary', finalColor);
		});
	}

	window.addEventListener('DOMContentLoaded', applyThemeColors);
	window.addEventListener('load', applyThemeColors);

	setTimeout(applyThemeColors, 300);
	setTimeout(applyThemeColors, 1000);
	setTimeout(applyThemeColors, 2500);

	if (window.MutationObserver) {
		var observer = new MutationObserver(function (mutations) {
			mutations.forEach(function (mutation) {
				if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
					applyThemeColors();
				}
			});
		});
		observer.observe(document.documentElement, {
			attributes: true,
			attributeFilter: ['style', 'class']
		});
		observer.observe(document.body, {
			attributes: true,
			attributeFilter: ['style', 'class']
		});
	}
	setInterval(applyThemeColors, 1000);
})();


jQuery(document).ready(function ($) {

	/* ── Template 1 accordion ───────────────────────────── */
	$('.wpfaqblock-accordion .accordion-title').click(function () {
		if ($(this).hasClass('accordian-pause')) {
			return;
		}
		var $accordion = $(this).closest('.wpfaqblock-accordion');
		var $content = $(this).next('.accordion-content');
		var isOpen = $(this).hasClass('open');

		$accordion.find('.accordion-title').not($(this)).removeClass('open');
		$accordion.find('.accordion-content').not($content).stop(true, true).slideUp(250);

		if (!isOpen) {
			$(this).addClass('open');
			$content.stop(true, true).slideDown(250);
		} else {
			$(this).removeClass('open');
			$content.stop(true, true).slideUp(250);
		}
	});

	/* ── Template 2 accordion ───────────────────────────── */
	$(document).on('click', '.wpfaqblock-t2-question', function () {
		var $question = $(this);
		var $item = $question.closest('.wpfaqblock-t2-item');
		var $answer = $item.find('.wpfaqblock-t2-answer');
		var $list = $item.closest('.wpfaqblock-t2-list');

		var isOpen = $item.hasClass('wpfaqblock-t2-item-open');

		$list.find('.wpfaqblock-t2-item').not($item).removeClass('wpfaqblock-t2-item-open');
		$list.find('.wpfaqblock-t2-question').not($question).removeClass('wpfaqblock-t2-question-open');
		$list.find('.wpfaqblock-t2-answer').not($answer).stop(true, true).slideUp(250);

		// Toggle
		if (!isOpen) {
			$item.addClass('wpfaqblock-t2-item-open');
			$question.addClass('wpfaqblock-t2-question-open');
			$answer.stop(true, true).slideDown(250);
		} else {
			$item.removeClass('wpfaqblock-t2-item-open');
			$question.removeClass('wpfaqblock-t2-question-open');
			$answer.stop(true, true).slideUp(250);
		}
	});

	/* ── Template 3 accordion ───────────────────────────── */
	$(document).on('click', '.wpfaqblock-t3-question', function () {
		var $question = $(this);
		var $item = $question.closest('.wpfaqblock-t3-item');
		var $answer = $item.find('.wpfaqblock-t3-answer');
		var $list = $item.closest('.wpfaqblock-t3-list');

		var isOpen = $item.hasClass('wpfaqblock-t3-item-open');

		$list.find('.wpfaqblock-t3-item').not($item).removeClass('wpfaqblock-t3-item-open');
		$list.find('.wpfaqblock-t3-question').not($question).removeClass('wpfaqblock-t3-question-open');
		$list.find('.wpfaqblock-t3-answer').not($answer).stop(true, true).slideUp(250);

		// Toggle
		if (!isOpen) {
			$item.addClass('wpfaqblock-t3-item-open');
			$question.addClass('wpfaqblock-t3-question-open');
			$answer.stop(true, true).slideDown(250);
		} else {
			$item.removeClass('wpfaqblock-t3-item-open');
			$question.removeClass('wpfaqblock-t3-question-open');
			$answer.stop(true, true).slideUp(250);
		}
	});

	/* -- Template 4 accordion ----------------------------- */
	$(document).on('click', '.wpfaqblock-t4-question', function () {
		var $question = $(this);
		var $item = $question.closest('.wpfaqblock-t4-item');
		var $answer = $item.find('.wpfaqblock-t4-answer');
		var $list = $item.closest('.wpfaqblock-t4-list');

		var isOpen = $item.hasClass('wpfaqblock-t4-item-open');

		$list.find('.wpfaqblock-t4-item').not($item).removeClass('wpfaqblock-t4-item-open');
		$list.find('.wpfaqblock-t4-question').not($question).removeClass('wpfaqblock-t4-question-open');
		$list.find('.wpfaqblock-t4-answer').not($answer).stop(true, true).slideUp(250);

		// Toggle
		if (!isOpen) {
			$item.addClass('wpfaqblock-t4-item-open');
			$question.addClass('wpfaqblock-t4-question-open');
			$answer.stop(true, true).slideDown(250);
		} else {
			$item.removeClass('wpfaqblock-t4-item-open');
			$question.removeClass('wpfaqblock-t4-question-open');
			$answer.stop(true, true).slideUp(250);
		}
	});

	/* -- Template 5 accordion ----------------------------- */
	$(document).on('click', '.wpfaqblock-t5-question', function () {
		var $question = $(this);
		var $item = $question.closest('.wpfaqblock-t5-item');
		var $answer = $item.find('.wpfaqblock-t5-answer');
		var $list = $item.closest('.wpfaqblock-t5-list');

		var isOpen = $item.hasClass('wpfaqblock-t5-item-open');

		$list.find('.wpfaqblock-t5-item').not($item).removeClass('wpfaqblock-t5-item-open');
		$list.find('.wpfaqblock-t5-question').not($question).removeClass('wpfaqblock-t5-question-open');
		$list.find('.wpfaqblock-t5-answer').not($answer).stop(true, true).slideUp(250);

		// Toggle
		if (!isOpen) {
			$item.addClass('wpfaqblock-t5-item-open');
			$question.addClass('wpfaqblock-t5-question-open');
			$answer.stop(true, true).slideDown(250);
		} else {
			$item.removeClass('wpfaqblock-t5-item-open');
			$question.removeClass('wpfaqblock-t5-question-open');
			$answer.stop(true, true).slideUp(250);
		}
	});

	/* -- Template 6 accordion ----------------------------- */
	$(document).on('click', '.wpfaqblock-t6-question, .wpfaqblock-t6-item', function (e) {
		if ($(e.target).closest('.wpfaqblock-t6-answer').length) return;

		var $item = $(this).closest('.wpfaqblock-t6-item');
		var $question = $item.find('.wpfaqblock-t6-question');
		var $answer = $item.find('.wpfaqblock-t6-answer');
		var $list = $item.closest('.wpfaqblock-t6-list');

		var isOpen = $item.hasClass('wpfaqblock-t6-item-open');

		$list.find('.wpfaqblock-t6-item').not($item).removeClass('wpfaqblock-t6-item-open');
		$list.find('.wpfaqblock-t6-answer').not($answer).stop(true, true).slideUp(250);

		// Toggle
		if (!isOpen) {
			$item.addClass('wpfaqblock-t6-item-open');
			$answer.stop(true, true).slideDown(250);
			$item.find('.wpfaqblock-t6-btn').attr('aria-expanded', 'true');
		} else {
			$item.removeClass('wpfaqblock-t6-item-open');
			$answer.stop(true, true).slideUp(250);
			$item.find('.wpfaqblock-t6-btn').attr('aria-expanded', 'false');
		}

		e.preventDefault();
		e.stopPropagation();
	});

	/* -- Template 7 accordion ----------------------------- */
	$(document).on('click', '.wpfaqblock-t7-question, .wpfaqblock-t7-item', function (e) {
		if ($(e.target).closest('.wpfaqblock-t7-answer').length) return;

		var $item = $(this).closest('.wpfaqblock-t7-item');
		var $answer = $item.find('.wpfaqblock-t7-answer');
		var $list = $item.closest('.wpfaqblock-t7-list');

		var isOpen = $item.hasClass('wpfaqblock-t7-item-open');

		$list.find('.wpfaqblock-t7-item').not($item).removeClass('wpfaqblock-t7-item-open');
		$list.find('.wpfaqblock-t7-answer').not($answer).stop(true, true).slideUp(250);

		// Toggle
		if (!isOpen) {
			$item.addClass('wpfaqblock-t7-item-open');
			$answer.stop(true, true).slideDown(250);
			$item.find('.wpfaqblock-t7-btn').attr('aria-expanded', 'true');
		} else {
			$item.removeClass('wpfaqblock-t7-item-open');
			$answer.stop(true, true).slideUp(250);
			$item.find('.wpfaqblock-t7-btn').attr('aria-expanded', 'false');
		}

		e.preventDefault();
		e.stopPropagation();
	});
});
