document.documentElement.classList.add('js-ready');

const appBase = (window.MOZCURSOS_BASE || '').replace(/\/$/, '');
const appUrl = (path) => `${appBase}${path.startsWith('/') ? path : `/${path}`}`;

const adminToggle = document.querySelector('[data-admin-menu-toggle]');
if (adminToggle) {
    if (window.matchMedia('(max-width: 720px)').matches) {
        document.body.classList.add('admin-sidebar-collapsed');
        adminToggle.setAttribute('aria-expanded', 'false');
    }

    adminToggle.addEventListener('click', () => {
        const collapsed = document.body.classList.toggle('admin-sidebar-collapsed');
        adminToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
    });
}

document.querySelectorAll('[data-learning-video]').forEach((video) => {
    const startSecond = parseInt(video.dataset.startSecond || '0', 10);
    let restored = false;
    let lastSent = 0;

    const saveProgress = () => {
        const current = Math.floor(video.currentTime || 0);
        if (!current || Math.abs(current - lastSent) < 8) {
            return;
        }

        lastSent = current;
        const body = new URLSearchParams();
        body.set('_csrf_token', video.dataset.csrf || '');
        body.set('enrollment_id', video.dataset.enrollmentId || '');
        body.set('lesson_id', video.dataset.lessonId || '');
        body.set('second', String(current));

        fetch(appUrl('/learn/progress'), {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body,
            keepalive: true,
        }).catch(() => {});
    };

    video.addEventListener('loadedmetadata', () => {
        if (!restored && startSecond > 15 && startSecond < Math.max(0, video.duration - 8)) {
            video.currentTime = startSecond;
            restored = true;
        }
    });

    video.addEventListener('timeupdate', saveProgress);
    video.addEventListener('pause', saveProgress);
    video.addEventListener('ended', saveProgress);
    window.addEventListener('beforeunload', saveProgress);
});

document.querySelectorAll('[data-rail]').forEach((rail) => {
    const section = rail.closest('.home-section') || rail.parentElement;
    let wrap = rail.closest('.rail-wrap');
    if (!wrap) {
        wrap = document.createElement('div');
        wrap.className = 'rail-wrap';
        rail.parentNode.insertBefore(wrap, rail);
        wrap.appendChild(rail);
    }

    let controls = section ? section.querySelector('.catalog-head .rail-controls') : null;
    if (!controls) {
        controls = wrap.querySelector('.rail-controls');
    }
    if (!controls) {
        controls = document.createElement('div');
        controls.className = 'rail-controls';
        controls.innerHTML = '<button type="button" aria-label="Anterior">&lt;</button><button type="button" aria-label="Seguinte">&gt;</button>';
        wrap.appendChild(controls);
    }

    const prev = controls.querySelector('[data-rail-prev]') || controls.querySelector('button:first-child');
    const next = controls.querySelector('[data-rail-next]') || controls.querySelector('button:last-child');
    const amount = () => Math.min(rail.clientWidth * 0.86, 760);
    if (prev) {
        prev.addEventListener('click', () => rail.scrollBy({ left: -amount(), behavior: 'smooth' }));
    }
    if (next) {
        next.addEventListener('click', () => rail.scrollBy({ left: amount(), behavior: 'smooth' }));
    }
});

const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting) {
            entry.target.classList.add('is-visible');
            revealObserver.unobserve(entry.target);
        }
    });
}, { threshold: 0.12 });

document.querySelectorAll('.home-section, .home-strip, .live-bar, .creator-cta, .course-card').forEach((item) => {
    item.classList.add('reveal');
    revealObserver.observe(item);
});

const progress = document.createElement('div');
progress.className = 'scroll-progress';
document.body.appendChild(progress);

window.addEventListener('scroll', () => {
    const max = document.documentElement.scrollHeight - window.innerHeight;
    const value = max > 0 ? (window.scrollY / max) * 100 : 0;
    progress.style.width = value + '%';
}, { passive: true });
