// source --> http://www.bluesanne.at/wordpress/wp-content/plugins/easy-quotes/public/js/easy-quotes.js?ver=1.3.7 
/**
 * Easy Quotes Frontend JavaScript
 * 
 * Handles font loading, quote rotation, client-side quote selection, and animation observers.
 * 
 * @package EasyQuotes
 * @since 1.0.2
 */

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    createIntersectionObserver();
    initializeClientSideQuoteSelection();
});

// ===== CLIENT-SIDE QUOTE SELECTION =====

/**
 * Initialize client-side quote selection for random/daily modes
 */
function initializeClientSideQuoteSelection() {
    const containers = document.querySelectorAll('.easy-quotes-client-selection');
    
    containers.forEach(container => {
        const mode = container.dataset.mode;
        const quotes = container.querySelectorAll('.easy-quotes-quote');
        
        if (quotes.length === 0) return;
        
        let selectedIndex = 0;
        
        if (mode === 'random') {
            selectedIndex = Math.floor(Math.random() * quotes.length);
        } else if (mode === 'daily') {
            selectedIndex = getDailyQuoteIndex(container); // Pass container to scope the search
        }
        
        // Show selected quote, hide others
        quotes.forEach((quote, index) => {
            if (index === selectedIndex) {
                quote.classList.remove('easy-quotes-hidden');
                quote.classList.add('easy-quotes-visible');
            } else {
                quote.classList.add('easy-quotes-hidden');
                quote.classList.remove('easy-quotes-visible');
            }
        });
    });
}

/**
 * Get daily quote index based on current date
 * 
 * Logic:
 * 1. Find quote for today's MMDD date
 * 2. If none found, use index 0 (first quote = most recent = SQL fallback)
 */
function getDailyQuoteIndex(container) {
    const today = new Date();
    const todayMonth = String(today.getMonth() + 1).padStart(2, '0');
    const todayDay = String(today.getDate()).padStart(2, '0');
    const todayPattern = todayMonth + todayDay; // MMDD format (no dash)
    
    const quotes = container.querySelectorAll('.easy-quotes-quote[data-published-date]');
    
    for (let quote of quotes) {
        const publishedDate = quote.dataset.publishedDate; // Already in MMDD format
        const quoteIndex = parseInt(quote.dataset.quoteIndex);
        
        // Check for exact match (same MMDD)
        if (publishedDate === todayPattern) {
            return quoteIndex; // Found today's quote
        }
    }
    
    // No exact match found - return index 0 (SQL provides most recent quote as fallback)
    return 0;
}

// ===== FONT MANAGEMENT =====

/**
 * Creates and injects font styles into document head
 * 
 * Dynamically loads Google Fonts and applies them to quote elements.
 * Handles both regular blocks and legacy widget compatibility.
 * 
 * @param {string} fontURL - Google Fonts URL for the font file
 * @param {string} fontClassName - CSS class name for the font
 * @param {boolean} isCustomizer - Whether running in WordPress Customizer
 * @param {string|null} widgetId - Widget ID for legacy widget support
 */
function createStyleForFont(fontURL, fontClassName, isCustomizer = false, widgetId = null) {
    // Handle regular blocks and non-customizer contexts
    if (widgetId === null || isCustomizer === false) {
        const styleId = 'easy-quotes-' + fontClassName;

        // Check if font style already exists
        let style = document.getElementById(styleId);
        if (style) {
            return;
        }

        // Create new font style
        style = document.createElement('style');
        style.id = styleId;
        const selector = '.' + fontClassName;
        style.innerHTML = `
            @font-face {
                font-family: ${fontClassName};
                src: url("${fontURL}");
            }
            ${selector} {
                font-family: ${fontClassName};
            }
        `;
        document.head.appendChild(style);
    } else {
        // Handle legacy widgets in customizer
        let append = false;
        const styleId = 'easy-quotes-' + widgetId;
        let style = document.getElementById(styleId);
        
        if (!style) {
            style = document.createElement('style');
            style.id = styleId;
            append = true;
        }
        
        const selector = '.' + fontClassName;
        style.innerHTML = `
            @font-face {
                font-family: ${fontClassName};
                src: url("${fontURL}");
            }
            ${selector} {
                font-family: ${fontClassName};
            }
        `;
        
        if (append) {
            document.head.appendChild(style);
        }
    }
}

// ===== ANIMATION MANAGEMENT =====

/**
 * Intersection Observer callback
 * 
 * Starts CSS animations when elements enter the viewport
 * and stops them when elements leave the viewport.
 * 
 * @param {IntersectionObserverEntry[]} entries - Array of observed elements
 * @param {IntersectionObserver} observer - The observer instance
 */
const animationCallback = (entries, observer) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting) {
            // Element is visible - start animation
            const animationName = entry.target.dataset.animation;
            entry.target.style.setProperty('animation-name', animationName);
        } else {
            // Element is not visible - stop animation
            entry.target.style.setProperty('animation-name', 'none');
        }
    });
};

/**
 * Creates Intersection Observer for quote animations
 * 
 * Observes all quote elements with CSS animations and manages
 * their animation state based on viewport visibility.
 */
function createIntersectionObserver() {
    const observer = new IntersectionObserver(animationCallback, {
        threshold: 0,
    });
    
    // Find all quote containers
    const quotes = document.querySelectorAll('.easy-quotes-quote');
    
    quotes.forEach((target) => {
        // Navigate through theme wrapper divs to find actual content
        while (target.children.length === 1) {
            target = target.children[0];
        }

        // Observe child elements that have CSS animations
        Array.from(target.children).forEach(child => {
            const animation = getComputedStyle(child).getPropertyValue('animation-name');
            if (animation !== 'none') {
                child.setAttribute('data-animation', animation);
                observer.observe(child);
            }
        });
    });
}

// ===== QUOTE ROTATION =====

/**
 * Starts quote rotation for a given container
 * 
 * Initializes the rotation system with the specified speed and viewing order.
 * Manages the display cycle of multiple quotes within a container.
 * 
 * @param {string} id - The HTML ID of the rotation container
 */
function startRotation(id) {
    const element = document.getElementById(id);
    if (!element) {
        console.error('Easy Quotes: Rotation container not found:', id);
        return;
    }
    
    // Get rotation configuration from data attributes
    const rotationSpeed = element.dataset.rotationSpeed * 1000;
    const viewingOrder = (element.dataset.isRandomViewingOrder === '0') ? 'normal' : 'random';
    
    // Find all quote elements within the container
    const quotes = element.querySelectorAll('.easy-quotes-quote');
    
    if (quotes.length === 0) {
        console.warn('Easy Quotes: No quotes found in rotation container:', id);
        return;
    }
    
    // Start immediate rotation and set up interval
    showNext(element, quotes, viewingOrder);
    
    setInterval(() => {
        showNext(element, quotes, viewingOrder);
    }, rotationSpeed);
}

/**
 * Shows the next quote in rotation sequence
 * 
 * Manages the quote rotation logic including:
 * - Hiding currently visible quote
 * - Selecting next quote based on viewing order (normal/random)
 * - Resetting rotation when all quotes have been shown
 * - Avoiding consecutive display of the same quote
 * 
 * @param {Element} element - The rotation container element
 * @param {NodeList} quotes - All quote elements in the container
 * @param {string} viewingOrder - Either 'normal' or 'random'
 */
function showNext(element, quotes, viewingOrder) {
    // Hide currently visible quote
    const visible = element.querySelector('.easy-quotes-quote.la-show');
    if (visible) {
        visible.classList.remove('la-show');
        visible.classList.add('la-hide');
        visible.setAttribute('data-shown', '1');
    }

    // Get quotes that haven't been shown in current cycle
    let availableQuotes = element.querySelectorAll('.easy-quotes-quote:not([data-shown])');
    
    // Reset cycle if all quotes have been shown
    if (availableQuotes.length === 0) {
        quotes.forEach((quoteElement) => {
            quoteElement.removeAttribute('data-shown');
        });
        
        // Refresh available quotes after reset
        availableQuotes = element.querySelectorAll('.easy-quotes-quote:not([data-shown])');
    }

    // Select next quote based on viewing order
    let index = 0;
    if (viewingOrder === 'random') {
        index = Math.floor(Math.random() * availableQuotes.length);
        
        // Avoid showing the same quote twice in a row
        if (availableQuotes[index] === visible) {
            index = (index + 1) % availableQuotes.length;
        }
    }

    // Show the selected quote
    const nextQuote = availableQuotes[index];
    nextQuote.classList.remove('la-hide');
    nextQuote.classList.add('la-show');
};
// source --> http://www.bluesanne.at/wordpress/wp-content/plugins/essential-widgets/public/js/essential-widgets-public.js?ver=3.0.1 
(function( $ ) {
	'use strict';

	/**
	 * All of the code for your public-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */

})( jQuery );