<!DOCTYPE >
<html>
    <head>
        <title>Image Uploader</title>
        <style>
            body {
                margin-top: 50px;
                margin-bottom: 50px;
                text-align: center;
            }

            form {
                display: flex;
                gap: 20px;
                flex-direction: column;
                align-items: center;
            }

            #image-container {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
            }

            img {
                width: 200px;
                height: 200px;
                object-fit: cover;
                margin: 10px;
            }
        </style>
    </head>
    <body>
        <h1>Image Uploader</h1>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <img id="filePreview" src="https://via.placeholder.com/200" />
            <input id="fileInput" type="file" name="image" accept="image/*" />
            <input type="submit" value="Upload" />
        </form>
        <div id="image-container">
            <!-- Images will be displayed here -->
        </div>
    </body>
    <script>
        // Preview Image Logic
        const imageInput = document.getElementById("fileInput");
        const imagePreview = document.getElementById("filePreview");

        imageInput.addEventListener("change", function () {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function () {
                    imagePreview.src = reader.result;
                };
                reader.readAsDataURL(file);
            }
        });
    </script>
    <script>
        // Fetch Uploaded Images Logic
        fetch("/images")
            .then((response) => response.json())
            .then(({ images }) => {
                console.log(images);
                const imageContainer =
                    document.getElementById("image-container");

                images.forEach((image) => {
                    let extension = image.type.split("/")[1];
                    const img = document.createElement("img");
                    img.src = `/image/${image.id}.${extension}`;
                    imageContainer.appendChild(img);
                });
            });
    </script>
</html>