let progressTimer = null;
let currentPasswordStrength = 0;

function startProgress() {
    let bar = document.querySelector('#page-progress');

    if (!bar) {
        bar = document.createElement('div');
        bar.id = 'page-progress';
        bar.style.position = 'fixed';
        bar.style.top = '0';
        bar.style.left = '0';
        bar.style.height = '3px';
        bar.style.width = '0%';
        bar.style.zIndex = '9999';
        bar.style.background = 'linear-gradient(90deg, #6d9bff, #63e8f1)';
        bar.style.transition = 'width 0.25s ease, opacity 0.3s ease';
        document.body.appendChild(bar);
    }

    bar.style.opacity = '1';
    bar.style.width = '12%';

    progressTimer = setInterval(() => {
        const currentWidth = parseFloat(bar.style.width);

        if (currentWidth < 85) {
            bar.style.width = currentWidth + 8 + '%';
        }
    }, 120);
}

function finishProgress() {
    const bar = document.querySelector('#page-progress');

    if (!bar) return;

    clearInterval(progressTimer);

    bar.style.width = '100%';

    setTimeout(() => {
        bar.style.opacity = '0';

        setTimeout(() => {
            bar.style.width = '0%';
        }, 300);
    }, 200);
}

function isHomePage(url) {
    const path = new URL(url, window.location.origin).pathname;

    return path === '/driftly/public/' || path === '/driftly/public';
}

function isAuthPage(url) {
    const path = new URL(url, window.location.origin).pathname;

    return (
        path.endsWith('/login') ||
        path.endsWith('/register') ||
        path.endsWith('/logout')
    );
}

async function loadPage(url, push = true) {
    if (isAuthPage(url)) {
        window.location.href = url;
        return;
    }

    startProgress();

    const app = document.querySelector('#app');

    if (!app) {
        window.location.href = url;
        return;
    }

    if (!isHomePage(url)) {
        app.innerHTML = `
            <div class="animate-pulse space-y-4">
                <div class="h-6 bg-gray-300 rounded w-1/3"></div>
                <div class="h-6 bg-gray-300 rounded w-1/2"></div>
                <div class="h-40 bg-gray-300 rounded"></div>
            </div>
        `;
    }

    try {
        const response = await fetch(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        if (!response.ok) {
            alert('Something went wrong');
            window.location.href = url;
            return;
        }

        const html = await response.text();

        app.innerHTML = html;

        if (push) {
            history.pushState({}, '', url);
        }

        initPage();

        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });

    } catch (error) {
        window.location.href = url;
    } finally {
        finishProgress();
    }
}

document.addEventListener('click', function (e) {
    const link = e.target.closest('[data-link]');

    if (!link) return;

    if (link.target === '_blank') return;

    if (link.origin !== window.location.origin) return;

    if (isAuthPage(link.href)) {
        return;
    }

    e.preventDefault();

    loadPage(link.href, true);
});

window.addEventListener('popstate', function () {
    if (isAuthPage(window.location.href)) {
        window.location.href = window.location.href;
        return;
    }

    loadPage(window.location.href, false);
});

function setActiveLinks() {
    document.querySelectorAll('[data-link]').forEach(link => {
        if (link.href === location.href) {
            link.classList.add('font-bold');
        } else {
            link.classList.remove('font-bold');
        }
    });
}

function initPage() {
    setActiveLinks();
    initFadeAnimations();
    initRideCards();
    initPopularRides();
    initIcons();
    initTestimonials();
    initRegisterSteps();
    initPasswordToggle();
    initPasswordStrength();
}

function initFadeAnimations() {
    const elements = document.querySelectorAll('.fade-up');

    elements.forEach((el, index) => {
        el.classList.remove('show');

        setTimeout(() => {
            el.classList.add('show');
        }, index * 120);
    });
}

function initRideCards() {
    const cards = document.querySelectorAll('.ride-card');

    if (!cards.length) return;

    const observer = new IntersectionObserver((entries, obs) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const el = entry.target;
                const index = [...cards].indexOf(el);

                setTimeout(() => {
                    el.classList.add('show');
                }, index * 100);

                obs.unobserve(el);
            }
        });
    }, {
        threshold: 0.15
    });

    cards.forEach(card => {
        observer.observe(card);
    });
}

async function initPopularRides() {
    const container = document.querySelector('#popular-rides');

    if (!container) return;

    try {
        const response = await fetch('/driftly/public/home/popular-rides', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        if (!response.ok) return;

        const html = await response.text();

        setTimeout(() => {
            container.innerHTML = html;
            initRideCards();
        }, 500);

    } catch (error) {
        console.log(error);
    }
}

async function initTestimonials() {
    const container = document.querySelector('#testimonials');

    if (!container) return;

    try {
        const response = await fetch('/driftly/public/home/testimonials', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        if (!response.ok) return;

        const html = await response.text();

        setTimeout(() => {
            container.innerHTML = html;
            initIcons();
            initTestimonialCards();
        }, 500);

    } catch (error) {
        console.log(error);
    }
}

function initTestimonialCards() {
    const cards = document.querySelectorAll('.testimonial-card');

    if (!cards.length) return;

    const observer = new IntersectionObserver((entries, obs) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const index = [...cards].indexOf(entry.target);

                setTimeout(() => {
                    entry.target.classList.add('show');
                }, index * 100);

                obs.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.15
    });

    cards.forEach(card => observer.observe(card));
}

function initRegisterSteps() {
    const form = document.querySelector('#registerForm');

    if (!form) return;

    let currentStep = 1;

    const steps = form.querySelectorAll('.register-step');
    const indicators = document.querySelectorAll('[data-step-indicator]');
    const prevButton = document.querySelector('#prevRegisterStep');
    const nextButton = document.querySelector('#nextRegisterStep');
    const submitButton = document.querySelector('#submitRegister');

    if (!prevButton || !nextButton || !submitButton) return;

    function showStep(step) {
        currentStep = step;

        steps.forEach(item => {
            const isActive = Number(item.dataset.step) === currentStep;

            item.classList.toggle('step-active', isActive);
            item.classList.toggle('step-hidden', !isActive);
        });

        indicators.forEach(item => {
            item.classList.toggle(
                'active',
                Number(item.dataset.stepIndicator) === currentStep
            );
        });

        prevButton.classList.toggle('hidden', currentStep === 1);
        nextButton.classList.toggle('hidden', currentStep === 3);
        submitButton.classList.toggle('hidden', currentStep !== 3);

        initIcons();
    }

    function validateStep(step) {
        const currentStepElement = form.querySelector(`[data-step="${step}"]`);

        if (!currentStepElement) return false;

        const fields = currentStepElement.querySelectorAll('input, select');

        for (const field of fields) {
            if (!field.checkValidity()) {
                field.reportValidity();
                return false;
            }
        }

        return true;
    }

    nextButton.addEventListener('click', function () {
        if (currentStep === 1 && currentPasswordStrength < 3) {
            const text = document.querySelector('#passwordStrengthText');

            if (text) {
                text.textContent = 'Password must be at least marked as good.';
                text.className = 'text-sm text-red-500 mt-2';
            }

            return;
        }

        if (!validateStep(currentStep)) return;

        showStep(currentStep + 1);
    });

    prevButton.addEventListener('click', function () {
        showStep(currentStep - 1);
    });

    showStep(1);
}

function initPasswordToggle() {
    document.querySelectorAll('[data-toggle-password]').forEach(button => {
        if (button.dataset.initialized === 'true') return;

        button.dataset.initialized = 'true';

        button.addEventListener('click', function () {
            const input = document.getElementById(this.dataset.togglePassword);

            if (!input) return;

            const isPassword = input.type === 'password';

            input.type = isPassword ? 'text' : 'password';

            this.innerHTML = isPassword
                ? '<i data-lucide="eye-off" class="w-5 h-5"></i>'
                : '<i data-lucide="eye" class="w-5 h-5"></i>';

            initIcons();
        });
    });
}

function initIcons() {
    if (window.lucide) {
        lucide.createIcons();
    }
}

function initPasswordStrength() {
    const input = document.querySelector('#registerPassword');
    const bar = document.querySelector('#passwordStrengthBar');
    const text = document.querySelector('#passwordStrengthText');

    if (!input || !bar || !text) return;

    currentPasswordStrength = 0;

    input.addEventListener('input', function () {
        const password = input.value;
        let score = 0;

        if (password.length >= 8) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^A-Za-z0-9]/.test(password)) score++;

        currentPasswordStrength = score;

        if (password.length === 0) {
            currentPasswordStrength = 0;
            bar.style.width = '0%';
            bar.className = 'h-full w-0 rounded-full transition-all duration-300';
            text.textContent = 'Password strength';
            text.className = 'text-sm text-slate-400 mt-2';
            return;
        }

        if (score <= 1) {
            bar.style.width = '25%';
            bar.className = 'h-full rounded-full transition-all duration-300 bg-red-400';
            text.textContent = 'Weak password';
            text.className = 'text-sm text-red-500 mt-2';
        } else if (score === 2) {
            bar.style.width = '50%';
            bar.className = 'h-full rounded-full transition-all duration-300 bg-amber-400';
            text.textContent = 'Medium password';
            text.className = 'text-sm text-amber-500 mt-2';
        } else if (score === 3) {
            bar.style.width = '75%';
            bar.className = 'h-full rounded-full transition-all duration-300 bg-blue-400';
            text.textContent = 'Good password';
            text.className = 'text-sm text-blue-500 mt-2';
        } else {
            bar.style.width = '100%';
            bar.className = 'h-full rounded-full transition-all duration-300 bg-emerald-400';
            text.textContent = 'Strong password';
            text.className = 'text-sm text-emerald-500 mt-2';
        }
    });
}

document.addEventListener('DOMContentLoaded', function () {
    initPage();
});