/**
 * AskAny Dynamic Pricing System
 * 
 * Fetches pricing data from API and shows dynamic pricing modal
 * when topbar_active is true (with countdown timer)
 * 
 * @package Askany
 * @since 1.9.0
 */

(function($) {
	'use strict';
	
	/**
	 * AskanyPricing namespace
	 */
	window.AskanyPricing = window.AskanyPricing || {};
	
	// Configuration
	const config = {
		apiUrl: 'https://wpazleen.com/wp-json/wpx/v1/premium-modal-settings?config_id=askany',
		cacheKey: 'askany_pricing_data',
		cacheExpiry: 43200000 // 12 hours in milliseconds (12 * 60 * 60 * 1000)
	};
	
	// Countdown timer interval
	let countdownInterval = null;
	
	/**
	 * Fetch pricing data from API
	 * 
	 * @returns {Promise<Object>} Pricing data
	 */
	AskanyPricing.fetchPricingData = async function() {
		// Check cache first
		const cached = localStorage.getItem(config.cacheKey);
		if (cached) {
			const cachedData = JSON.parse(cached);
			const now = Date.now();
			
			// Return cached data if not expired
			if (cachedData.timestamp && (now - cachedData.timestamp) < config.cacheExpiry) {
				console.log('Using cached pricing data');
				return cachedData.data;
			}
		}
		
		try {
			console.log('Fetching pricing data from API...');
			const response = await fetch(config.apiUrl);
			const result = await response.json();
			
			if (result.success && result.data) {
				// Cache the result
				const cacheData = {
					data: result.data,
					timestamp: Date.now()
				};
				localStorage.setItem(config.cacheKey, JSON.stringify(cacheData));
				
				console.log('Pricing data fetched:', result.data);
				return result.data;
			}
			
			// Fallback if no data
			return AskanyPricing.getFallbackData();
		} catch (error) {
			console.warn('Failed to fetch pricing data:', error);
			return AskanyPricing.getFallbackData();
		}
	};
	
	/**
	 * Get fallback pricing data
	 * 
	 * @returns {Object} Fallback data
	 */
	AskanyPricing.getFallbackData = function() {
		return {
			topbar_active: false,
			discount_end_time: null,
			premium_modal_offer_amount: 'Special Offer',
			premium_modal_header_title: 'Unlock Premium Power!',
			premium_modal_content: 'Upgrade now to unlock AskAny powerful features and take your site to the next level!',
			premium_modal_button_text: 'Upgrade to Premium Now',
			premium_modal_button_url: '#upgrade'
		};
	};
	
	/**
	 * Format time with leading zero
	 * 
	 * @param {number} time Time value
	 * @returns {string} Formatted time
	 */
	AskanyPricing.formatTime = function(time) {
		return time.toString().padStart(2, '0');
	};
	
	/**
	 * Update countdown timer
	 * 
	 * @param {string} endTime End time timestamp
	 */
	AskanyPricing.updateCountdown = function(endTime) {
		const targetDate = new Date(endTime);
		const now = new Date().getTime();
		const distance = targetDate.getTime() - now;
		
		if (distance > 0) {
			const days = Math.floor(distance / (1000 * 60 * 60 * 24));
			const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
			const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((distance % (1000 * 60)) / 1000);
			
			$('#askany-countdown-days').text(AskanyPricing.formatTime(days));
			$('#askany-countdown-hours').text(AskanyPricing.formatTime(hours));
			$('#askany-countdown-minutes').text(AskanyPricing.formatTime(minutes));
			$('#askany-countdown-seconds').text(AskanyPricing.formatTime(seconds));
		} else {
			// Countdown ended
			$('.askany-pricing-countdown').html('<p class="countdown-ended">😬 Oops! Offer may slipped away. Check back soon.</p>');
			if (countdownInterval) {
				clearInterval(countdownInterval);
			}
		}
	};
	
	/**
	 * Create dynamic pricing modal HTML
	 * 
	 * @param {Object} data Pricing data from API
	 * @returns {string} Modal HTML
	 */
	AskanyPricing.createPricingModal = function(data) {
		let modalHtml = `
			<div id="askany-pricing-modal" class="askany-pricing-modal" style="display: none;">
				<div class="askany-pricing-modal-overlay"></div>
				<div class="askany-pricing-modal-content">
					<button class="askany-pricing-modal-close" aria-label="Close">
						<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
							<line x1="18" y1="6" x2="6" y2="18"></line>
							<line x1="6" y1="6" x2="18" y2="18"></line>
						</svg>
					</button>
					
					<div class="askany-pricing-header">
						<div class="premium-crown">
							<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
							</svg>
						</div>
						<h2>${data.premium_modal_header_title} 🚀</h2>
						<p>${data.premium_modal_content}</p>
					</div>`;
		
		// Show countdown if topbar is active
		if (data.topbar_active) {
			modalHtml += `
					<div class="askany-pricing-offer">
						<div class="premium-offer-badge">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<circle cx="12" cy="12" r="10"></circle>
								<polyline points="12 6 12 12 16 14"></polyline>
							</svg>
							<span>Limited Time Offer</span>
						</div>
						<div class="askany-pricing-countdown">
							<div class="countdown-item">
								<span class="countdown-number" id="askany-countdown-days">00</span>
								<span class="countdown-label">Days</span>
							</div>
							<div class="countdown-separator">:</div>
							<div class="countdown-item">
								<span class="countdown-number" id="askany-countdown-hours">00</span>
								<span class="countdown-label">Hours</span>
							</div>
							<div class="countdown-separator">:</div>
							<div class="countdown-item">
								<span class="countdown-number" id="askany-countdown-minutes">00</span>
								<span class="countdown-label">Minutes</span>
							</div>
							<div class="countdown-separator">:</div>
							<div class="countdown-item">
								<span class="countdown-number" id="askany-countdown-seconds">00</span>
								<span class="countdown-label">Seconds</span>
							</div>
						</div>
						<p class="premium-offer-text">
							🔥 <strong>${data.premium_modal_offer_amount}</strong> - Save hundreds of dollars!
						</p>
					</div>`;
		} else {
			// Show basic features when topbar is inactive
			modalHtml += `
					<div class="askany-pricing-basic-offer">
						<div class="askany-value-props">
							<div class="value-prop">
								<svg class="value-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
									<path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path>
									<line x1="3" y1="6" x2="21" y2="6"></line>
									<path d="M16 10a4 4 0 0 1-8 0"></path>
								</svg>
								<div class="value-content">
									<h4>Supercharge Your Website</h4>
									<p>Get access to unlimited premium features that will transform your site</p>
								</div>
							</div>
							<div class="value-prop">
								<svg class="value-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
									<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
									<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
								</svg>
								<div class="value-content">
									<h4>All Upcoming Feature</h4>
									<p>Protect your site with enterprise-level security features</p>
								</div>
							</div>
							<div class="value-prop">
								<svg class="value-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
									<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
								</svg>
								<div class="value-content">
									<h4>Priority Support</h4>
									<p>Get help when you need it with our dedicated support team</p>
								</div>
							</div>
						</div>`;
			
			if (data.premium_modal_offer_amount) {
				modalHtml += `
						<div class="premium-offer-highlight">
							<span class="offer-badge">Special Offer</span>
							<span class="offer-text">${data.premium_modal_offer_amount}</span>
						</div>`;
			}
			
			modalHtml += `
					</div>`;
		}
		
		// CTA Button
		modalHtml += `
					<button class="askany-pricing-cta" onclick="window.open('${data.premium_modal_button_url}', '_blank')">
						<span>${data.premium_modal_button_text}</span>
						<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
							<line x1="5" y1="12" x2="19" y2="12"></line>
							<polyline points="12 5 19 12 12 19"></polyline>
						</svg>
					</button>`;
		
		// Features highlight (only when topbar is active)
		if (data.topbar_active) {
			modalHtml += `
					<div class="askany-pricing-highlights">
						<div class="highlight-item">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path>
								<line x1="3" y1="6" x2="21" y2="6"></line>
								<path d="M16 10a4 4 0 0 1-8 0"></path>
							</svg>
							<span>Unlimited Premium Features</span>
						</div>
						<div class="highlight-item">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
								<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
							</svg>
							<span>All Upcoming Feature</span>
						</div>
						<div class="highlight-item">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
							</svg>
							<span>Priority Support</span>
						</div>
					</div>`;
		}
		
		// Footer with money-back guarantee
		modalHtml += `
					<div class="askany-pricing-footer">
						<div class="guarantee-badge">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
								<path d="M9 12l2 2 4-4"></path>
							</svg>
							<span>14-Day Money-Back Guarantee</span>
						</div>
						<p class="guarantee-text">No questions asked • Cancel anytime • Secure payment</p>
					</div>
				</div>
			</div>`;
		
		return modalHtml;
	};
	
	/**
	 * Show pricing modal
	 * 
	 * @param {Object} options Modal options
	 */
	AskanyPricing.showModal = async function(options = {}) {
		try {
			// Fetch pricing data
			const data = await AskanyPricing.fetchPricingData();
			
			// If topbar is NOT active, use default Pro modal
			if (!data.topbar_active) {
				console.log('Topbar inactive - using default Pro modal');
				if (typeof AskanyPro !== 'undefined' && typeof AskanyPro.openModal === 'function') {
					AskanyPro.openModal(options);
				}
				return;
			}
			
			// Topbar is active - show dynamic pricing modal
			console.log('Topbar active - showing dynamic pricing modal');
			
			// Remove existing modal
			$('#askany-pricing-modal').remove();
			
			// Create and show modal
			const modalHtml = AskanyPricing.createPricingModal(data);
			$('body').append(modalHtml);
			
			// Show modal with animation
			$('#askany-pricing-modal').fadeIn(300);
			$('body').css('overflow', 'hidden');
			
			// Start countdown if discount end time exists
			if (data.discount_end_time) {
				// Initial update
				AskanyPricing.updateCountdown(data.discount_end_time);
				
				// Update every second
				countdownInterval = setInterval(function() {
					AskanyPricing.updateCountdown(data.discount_end_time);
				}, 1000);
			}
			
		} catch (error) {
			console.error('Failed to show pricing modal:', error);
			// Fallback to default Pro modal
			if (typeof AskanyPro !== 'undefined' && typeof AskanyPro.openModal === 'function') {
				AskanyPro.openModal(options);
			}
		}
	};
	
	/**
	 * Close pricing modal
	 */
	AskanyPricing.closeModal = function() {
		$('#askany-pricing-modal').fadeOut(300, function() {
			$(this).remove();
		});
		$('body').css('overflow', '');
		
		// Clear countdown interval
		if (countdownInterval) {
			clearInterval(countdownInterval);
			countdownInterval = null;
		}
	};
	
	/**
	 * Clear cached pricing data
	 */
	AskanyPricing.clearCache = function() {
		localStorage.removeItem(config.cacheKey);
		console.log('Pricing data cache cleared');
	};
	
	/**
	 * Update API configuration
	 * 
	 * @param {Object} newConfig Configuration object
	 */
	AskanyPricing.configure = function(newConfig) {
		if (newConfig.apiUrl) {
			config.apiUrl = newConfig.apiUrl;
		}
		if (newConfig.cacheExpiry) {
			config.cacheExpiry = newConfig.cacheExpiry;
		}
		console.log('Dynamic pricing configured:', config);
	};
	
	/**
	 * Initialize pricing modal event handlers
	 */
	AskanyPricing.init = function() {
		// Close modal on close button or overlay click
		$(document).on('click', '.askany-pricing-modal-close, .askany-pricing-modal-overlay', function() {
			AskanyPricing.closeModal();
		});
		
		// Close modal on escape key
		$(document).on('keydown', function(e) {
			if (e.key === 'Escape' && $('#askany-pricing-modal').is(':visible')) {
				AskanyPricing.closeModal();
			}
		});
	};
	
	// Auto-initialize when DOM is ready
	$(document).ready(function() {
		AskanyPricing.init();
	});
	
})(jQuery);
