<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nudge Display</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* Custom Styles */
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #667eea, #764ba2);
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #2d3748;
        }

        .container {
            background-color: #ffffff;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
            padding: 40px;
            max-width: 500px;
            width: 90%;
            box-sizing: border-box;
            text-align: center;
            position: relative;
            z-index: 1;
        }

        .container::before {
            content: '';
            position: absolute;
            top: -15px;
            left: -15px;
            right: -15px;
            bottom: -15px;
            z-index: -1;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 16px;
            transition: all 0.3s ease;
            filter: blur(20px);
            opacity: 0.5;
        }

        .container:hover {
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
        }

        h1 {
            font-size: 2.5rem;
            color: #1a202c;
            margin-bottom: 20px;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            font-weight: 700;
        }

        label {
            display: block;
            font-size: 1.1rem;
            font-weight: 600;
            color: #4a5568;
            margin-bottom: 8px;
            text-align: left;
        }

        select {
            margin-bottom: 25px;
            padding: 14px;
            border: 1px solid #cbd5e0;
            border-radius: 8px;
            width: 100%;
            background-color: #edf2f7;
            font-size: 1rem;
            font-family: 'Poppins', sans-serif;
        }

        button {
            background-color: #3182ce;
            color: #fff;
            padding: 16px 28px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1.2rem;
            font-weight: 600;
            transition: background-color 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
            width: 100%;
            margin-bottom: 20px;
        }

        button:disabled {
            background-color: #a0aec0;
            cursor: not-allowed;
        }

        button:hover {
            background-color: #2b6cb0;
            transform: translateY(-2px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
        }

        .modal-content img {
            max-width: 100px;
            max-height: 100px;
            margin: 10px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            cursor: pointer;
        }

        .modal-content img.selected {
            border: 3px solid #3182ce;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }

        .modal .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .modal .close:hover,
        .modal .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        .alert-box {
    background-color: #f8f9fa;
    border: 1px solid #ced4da;
    border-radius: 8px;
    padding: 10px; /* Adjusted padding for better appearance */
    margin-top: 20px;
    height: 50px;
    overflow-y: auto;
    text-align: center; /* Center text horizontally */
    display: flex; /* Use Flexbox for vertical and horizontal centering */
    align-items: center; /* Center text vertically */
    justify-content: center; /* Center text horizontally */
    position: relative;
    z-index: 1;
    display: none; /* Hidden by default */
}

.alert-box p {
    margin: 0;
    padding: 0; /* Adjust padding as needed */
}

    </style>
</head>

<body>
    <div class="container">
        <h1>Nudge Display</h1>
        <form id="uploadForm" action="/convert_and_build" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="epdSize">Select EPD</label>
                <select id="epdSize" name="epdSize" class="form-control" required>
                    <option value="4.2">4.2" (400x300)</option>
                    <option value="7.5">7.5" (800x480)</option>
                    <option value="13.0">13.0" (1600x1200)</option>
                </select>
            </div>
            <button type="button" id="load-images-btn">Browse Images</button>
            <button type="button" id="done-btn" disabled>Submit</button>
        </form>
        <div id="alertBox" class="alert-box">
            <p><strong></strong></p>
        </div>
    </div>

    <!-- Modal -->
    <div id="imageModal" class="modal">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Select an Image</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div id="imageGallery" class="modal-body d-flex flex-wrap"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="done-btn-footer" disabled>Select</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
        let selectedImage = null;
        let canSelectImages = false;


        function printAlertMessage(message, shouldRefresh = false) {
            const alertBox = document.getElementById('alertBox');
            alertBox.innerHTML = '<p><strong></strong></p>'; // Clear previous messages
            const alertMessage = document.createElement('p');
            alertMessage.textContent = message;
            alertBox.appendChild(alertMessage);

            // Show the alert box
            alertBox.style.display = 'block';

            // Hide the alert box after 5 seconds
            setTimeout(() => {
                alertBox.style.display = 'none';
                if (shouldRefresh) {
                    location.reload(); // Refresh the page
                }
            }, 5000);
        }



        document.getElementById('load-images-btn').addEventListener('click', async function () {
            const epdSize = document.getElementById('epdSize').value;
            let directory;

            // Determine the directory based on the selected EPD size
            if (epdSize === '4.2') {
                directory = 'NudgeDisplay/Input/EPD_4_2/';
            } else if (epdSize === '7.5') {
                directory = 'NudgeDisplay/Input/EPD_7_5/';
            } else if (epdSize === '13.0') {
                directory = 'NudgeDisplay/Input/EPD_13/';
            } else {
                printAlertMessage('Invalid EPD size selected.');
                return;
            }

            try {
                document.getElementById('load-images-btn').textContent = 'Loading...';
                const response = await fetch(`/get-folder-contents?dir=${encodeURIComponent(directory)}`);
                const data = await response.json();
                document.getElementById('load-images-btn').textContent = 'Show Images';

                const gallery = document.getElementById('imageGallery');
                gallery.innerHTML = ''; // Clear any existing images

                let hasImages = false; // Flag to check if there are images

                if (Array.isArray(data) && data.length > 0) {
                    data.forEach(file => {
                        const lowerCaseFile = file.toLowerCase();
                        if (lowerCaseFile.endsWith('.jpg') || lowerCaseFile.endsWith('.png')) {
                            hasImages = true;
                            const img = document.createElement('img');
                            img.src = `/image-proxy/${directory}/${file}`;
                            img.dataset.fileName = file;
                            img.classList.add('img-thumbnail');
                            img.addEventListener('click', () => {
                                if (canSelectImages) {
                                    if (selectedImage) {
                                        selectedImage.classList.remove('selected');
                                    }
                                    img.classList.add('selected');
                                    selectedImage = img;
                                    document.getElementById('load-images-btn').textContent = `Selected: ${file}`;
                                    document.getElementById('done-btn-footer').disabled = false;
                                }
                            });
                            gallery.appendChild(img);
                        }
                    });

                    if (!hasImages) {
                        gallery.innerHTML = '<p>No images found.</p>';
                    }

                    // Open the modal
                    $('#imageModal').modal('show');
                    canSelectImages = true; // Enable image selection
                } else {
                    printAlertMessage('No images found in the selected directory.');

                }
            } catch (error) {
                console.error('Error fetching images:', error);
                printAlertMessage('Failed to load images. Please try again.');
            }
        });

        document.getElementById('done-btn-footer').addEventListener('click', function () {
            if (selectedImage) {
                const fileName = selectedImage.dataset.fileName;
                document.getElementById('load-images-btn').textContent = `Selected: ${fileName}`;
                $('#imageModal').modal('hide');
                document.getElementById('done-btn').disabled = false; // Enable the button when an image is selected
            }
        });
        document.getElementById('done-btn').addEventListener('click', async function () {
            document.getElementById('done-btn').disabled = true;
            const epdSize = document.getElementById('epdSize').value;
            let directory;

            // Determine the directory based on the selected EPD size
            if (epdSize === '4.2') {
                directory = 'NudgeDisplay/Input/EPD_4_2/';
            } else if (epdSize === '7.5') {
                directory = 'NudgeDisplay/Input/EPD_7_5/';
            } else if (epdSize === '13.0') {
                directory = 'NudgeDisplay/Input/EPD_13/';
            } else {
                printAlertMessage('Invalid EPD size selected.');
                return;
            }

            if (selectedImage) {
                try {
                    const response = await fetch('/process-selection', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ selectedImage: selectedImage.dataset.fileName, directory })
                    });

                    if (response.ok) {
                        // Show success message with page refresh
                        printAlertMessage('Files copied successfully!', true);
                        document.getElementById('done-btn').disabled = true; // Disable button after successful processing
                    } else {
                        console.error('Failed to process selection:', await response.text());
                    }
                } catch (error) {
                    console.error('Error processing selection:', error);
                }
            } else {
                printAlertMessage('Please select an image first.');
            }
        });

    </script>


</body>

</html>
