/**
 * Vanilla JS Helper Functions
 * Replacement for jQuery on main website (modern browsers)
 * Mall still uses jQuery for IE11 compatibility
 */

// DOM Ready
function ready(fn) {
    if (document.readyState !== 'loading') {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

// Selector helpers
function $(selector) {
    return document.querySelector(selector);
}

function $$(selector) {
    return document.querySelectorAll(selector);
}

// Fade In animation
function fadeIn(element, duration = 400) {
    if (typeof element === 'string') {
        element = $(element);
    }
    if (!element) return;

    element.style.opacity = 0;
    element.style.display = '';

    let start = null;
    function animate(timestamp) {
        if (!start) start = timestamp;
        const progress = timestamp - start;
        element.style.opacity = Math.min(progress / duration, 1);
        if (progress < duration) {
            requestAnimationFrame(animate);
        }
    }
    requestAnimationFrame(animate);
}

// Fade Out animation
function fadeOut(element, duration = 400) {
    if (typeof element === 'string') {
        element = $(element);
    }
    if (!element) return;

    let start = null;
    function animate(timestamp) {
        if (!start) start = timestamp;
        const progress = timestamp - start;
        element.style.opacity = 1 - Math.min(progress / duration, 1);
        if (progress < duration) {
            requestAnimationFrame(animate);
        } else {
            element.style.display = 'none';
        }
    }
    requestAnimationFrame(animate);
}

// Slide Toggle (simplified - uses max-height trick)
function slideToggle(element) {
    if (typeof element === 'string') {
        element = $(element);
    }
    if (!element) return;

    if (element.style.display === 'none' || !element.style.display) {
        element.style.display = 'block';
        const height = element.scrollHeight;
        element.style.height = '0px';
        element.style.overflow = 'hidden';
        element.style.transition = 'height 0.3s ease';

        // Force reflow
        element.offsetHeight;
        element.style.height = height + 'px';

        setTimeout(() => {
            element.style.height = '';
            element.style.overflow = '';
            element.style.transition = '';
        }, 300);
    } else {
        const height = element.scrollHeight;
        element.style.height = height + 'px';
        element.style.overflow = 'hidden';
        element.style.transition = 'height 0.3s ease';

        // Force reflow
        element.offsetHeight;
        element.style.height = '0px';

        setTimeout(() => {
            element.style.display = 'none';
            element.style.height = '';
            element.style.overflow = '';
            element.style.transition = '';
        }, 300);
    }
}

// AJAX helper (using fetch)
function ajax(options) {
    const defaults = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    };

    const config = Object.assign({}, defaults, options);
    const url = config.url;
    delete config.url;

    fetch(url, config)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            if (config.dataType === 'json' || options.dataType === 'json') {
                return response.json();
            }
            return response.text();
        })
        .then(data => {
            if (options.success) {
                options.success(data);
            }
        })
        .catch(error => {
            if (options.error) {
                options.error(error);
            }
        });
}

// Validation Engine replacement
const validationEngine = {
    buildPrompt: function(selector, message, type) {
        const element = typeof selector === 'string' ? $(selector) : selector;
        if (!element) return;

        // Remove existing prompts
        const existing = element.parentElement.querySelector('.formError');
        if (existing) {
            existing.remove();
        }

        // Create new prompt
        const prompt = document.createElement('div');
        prompt.className = 'formError formError' + type.charAt(0).toUpperCase() + type.slice(1);
        prompt.innerHTML = `
            <div class="formErrorContent">${message}</div>
            <div class="formErrorArrow">
                <div class="line1"></div>
                <div class="line2"></div>
                <div class="line3"></div>
                <div class="line4"></div>
                <div class="line5"></div>
                <div class="line6"></div>
                <div class="line7"></div>
                <div class="line8"></div>
                <div class="line9"></div>
                <div class="line10"></div>
            </div>
        `;

        element.parentElement.style.position = 'relative';
        element.parentElement.appendChild(prompt);

        // Auto-remove after 5 seconds
        setTimeout(() => {
            prompt.remove();
        }, 5000);
    }
};

// Add/Remove/Toggle Class helpers
function addClass(element, className) {
    if (typeof element === 'string') {
        element = $(element);
    }
    if (element) {
        element.classList.add(className);
    }
}

function removeClass(element, className) {
    if (typeof element === 'string') {
        element = $(element);
    }
    if (element) {
        element.classList.remove(className);
    }
}

function toggleClass(element, className) {
    if (typeof element === 'string') {
        element = $(element);
    }
    if (element) {
        element.classList.toggle(className);
    }
}

// Export to global scope
window.ready = ready;
window.$ = $;
window.$$ = $$;
window.fadeIn = fadeIn;
window.fadeOut = fadeOut;
window.slideToggle = slideToggle;
window.ajax = ajax;
window.validationEngine = validationEngine;
window.addClass = addClass;
window.removeClass = removeClass;
window.toggleClass = toggleClass;
