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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Identification Lab</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f7f6;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 800px;
            margin: auto;
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        }

        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }

        .upload-section {
            border: 2px dashed #3498db;
            padding: 40px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.3s;
            margin-bottom: 20px;
        }

        .upload-section:hover {
            background: #ebf5fb;
        }

        #preview {
            max-width: 100%;
            max-height: 400px;
            display: none;
            margin: 20px auto;
            border-radius: 8px;
        }

        .btn {
            display: block;
            width: 100%;
            padding: 12px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            font-weight: bold;
        }

        .btn:hover {
            background: #2980b9;
        }

        #results {
            margin-top: 30px;
            border-top: 2px solid #eee;
            padding-top: 20px;
        }

        .result-item {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            border-left: 5px solid #2ecc71;
        }

        .match-score {
            float: right;
            font-weight: bold;
            color: #27ae60;
        }

        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 2s linear infinite;
            display: none;
            margin: 20px auto;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>🔍 Image Identification Lab</h1>

        <div class="upload-section" onclick="document.getElementById('fileInput').click()">
            <p>Click to Upload or Drag & Drop Product Image</p>
            <input type="file" id="fileInput" hidden accept="image/*" onchange="previewImage(event)">
        </div>

        <img id="preview" alt="Preview">

        <button class="btn" onclick="uploadAndMatch()">IDENTIFY PRODUCT</button>

        <div id="loader" class="loader"></div>

        <div id="results">
            <!-- Results will appear here -->
        </div>
    </div>

    <script>
        function previewImage(event) {
            const preview = document.getElementById('preview');
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function () {
                preview.src = reader.result;
                preview.style.display = 'block';
            }
            if (file) reader.readAsDataURL(file);
        }

        async function uploadAndMatch() {
            const fileInput = document.getElementById('fileInput');
            if (fileInput.files.length === 0) {
                alert("Please select an image first!");
                return;
            }

            const resultsDiv = document.getElementById('results');
            const loader = document.getElementById('loader');

            resultsDiv.innerHTML = '';
            loader.style.display = 'block';

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('/match', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                loader.style.display = 'none';

                if (data.status === 'success') {
                    resultsDiv.innerHTML = `<h3>Process Time: ${data.process_time}</h3>`;

                    data.detections.forEach((detection, detIndex) => {
                        const detHtml = `
                            <div style="margin-top:20px; padding:15px; background:#f0f3f5; border-radius:8px;">
                                <h4 style="margin-top:0;">Detection #${detIndex + 1}: ${detection.message}</h4>
                                <div style="color: #2980b9; font-weight:bold; margin-bottom:10px;">Confidence: ${detection.confidence.toUpperCase()}</div>
                                <div id="items-${detIndex}"></div>
                            </div>
                        `;
                        resultsDiv.insertAdjacentHTML('beforeend', detHtml);

                        const itemsDiv = document.getElementById(`items-${detIndex}`);
                        detection.items.forEach(res => {
                            // Convert distance to a mock similarity % for display
                            const sim = Math.max(0, (1 - res.distance) * 100).toFixed(1);
                            itemsDiv.innerHTML += `
                                <div class="result-item">
                                    <span class="match-score">${sim}% Match</span>
                                    <div><strong>SKU:</strong> ${res.sku}</div>
                                </div>
                            `;
                        });
                    });
                } else {
                    resultsDiv.innerHTML = `<p style="color:red">Error: ${data.message}</p>`;
                }
            } catch (error) {
                loader.style.display = 'none';
                alert("Upload failed: " + error);
            }
        }
    </script>
</body>

</html>