function updateGrid(grid) {
    // Skip hidden grids
    if (grid.offsetParent === null) {
        return;
    }

    const items = [...grid.querySelectorAll('.episode-item')];

    if (!items.length) {
        return;
    }

    // Reset visibility first
    items.forEach(item => {
        item.style.display = '';
    });

    // Determine actual column count
    const firstTop = items[0].offsetTop;

    let columns = 0;

    for (const item of items) {
        if (item.offsetTop !== firstTop) {
            break;
        }

        columns++;
    }

    const rows = parseInt(grid.dataset.rows || '2', 10);

    const visibleItems = columns * rows;

    items.forEach((item, index) => {
        item.style.display = index < visibleItems
            ? ''
            : 'none';
    });
}

function updateAllEpisodeGrids() {
    document.querySelectorAll('.episode-grid').forEach(updateGrid);
}

const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            updateGrid(entry.target);
        }
    });
});

document.querySelectorAll('.episode-grid').forEach(grid => {
    observer.observe(grid);
});

let resizeTimeout;

window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);

    resizeTimeout = setTimeout(() => {
        updateAllEpisodeGrids();
    }, 100);
});

window.addEventListener('load', updateAllEpisodeGrids);
