<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Media Gallery</title>
    <style>
        body {
            display: flex;
            justify-content: center;
        }
        .container {
            max-width: 1600px;
            width: 100%;
            padding: 20px;
        }
        .media-container {
            column-count: 4;
            column-gap: 10px;
        }
        .media-item {
            break-inside: avoid;
            margin-bottom: 10px;
        }
        img, video {
            width: 100%;
            height: auto;
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Media Gallery</h1>
        <div class="media-container" id="media-container"></div>
    </div>

    <script>
        let page = 0;

        async function loadMore() {
            const response = await fetch(`/load-more?page=${page}`);
            const mediaFiles = await response.json();
            const container = document.getElementById('media-container');

            mediaFiles.forEach(file => {
                const mediaItem = document.createElement('div');
                mediaItem.className = 'media-item';

                if (file.endsWith('.png') || file.endsWith('.jpg') || file.endsWith('.jpeg') || file.endsWith('.gif')) {
                    const img = document.createElement('img');
                    img.src = `/media/${file}`;
                    img.alt = file;
                    mediaItem.appendChild(img);
                } else if (file.endsWith('.mp4') || file.endsWith('.mkv') || file.endsWith('.mov')) {
                    const video = document.createElement('video');
                    video.controls = false;
                    video.autoplay = true;
                    video.muted = true;
                    video.loop = true;
                    const source = document.createElement('source');
                    source.src = `/media/${file}`;
                    source.type = 'video/mp4';
                    video.appendChild(source);
                    mediaItem.appendChild(video);
                }

                container.appendChild(mediaItem);
            });

            page += 1;
        }

        window.addEventListener('scroll', () => {
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
                loadMore();
            }
        });

        // Initial load
        loadMore();
    </script>
</body>
</html>
