<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mobile Camera - Local Lendables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .camera-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            overflow: hidden;
            margin: 20px;
        }

        .camera-header {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .camera-body {
            padding: 20px;
        }

        #video {
            width: 100%;
            max-width: 400px;
            border-radius: 10px;
            background: #f8f9fa;
        }

        #canvas {
            display: none;
        }

        .capture-btn {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            border: 4px solid #28a745;
            background: white;
            color: #28a745;
            font-size: 1.5rem;
            margin: 20px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .capture-btn:hover {
            background: #28a745;
            color: white;
            transform: scale(1.1);
        }

        .preview-image {
            max-width: 100%;
            border-radius: 10px;
            margin: 10px 0;
        }

        .status-message {
            text-align: center;
            padding: 15px;
            margin: 10px 0;
            border-radius: 8px;
            font-weight: 500;
        }

        .status-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .file-upload-area {
            border: 2px dashed #28a745;
            border-radius: 10px;
            padding: 40px 20px;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .file-upload-area:hover {
            background: #e9ecef;
            border-color: #20c997;
        }

        .file-upload-area.dragover {
            background: #d4edda;
            border-color: #28a745;
        }

        .btn-custom {
            border-radius: 25px;
            padding: 12px 25px;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="camera-container">
            <div class="camera-header">
                <h2><i class="fas fa-camera me-2"></i>Item Photo Capture</h2>
                {% if sessionId and sessionValid %}
                    <p class="mb-0" id="capturePrompt">Take your first photo (up to 3 photos allowed)</p>
                    <div class="progress mt-2" style="height: 6px;">
                        <div class="progress-bar bg-success" id="photoProgress" role="progressbar" style="width: 0%"></div>
                    </div>
                {% elseif sessionId and not sessionValid %}
                    <div class="alert alert-warning mb-0">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        QR code has expired (5-minute limit). Please scan a new QR code.
                    </div>
                {% else %}
                    <div class="alert alert-success mb-0">
                        <i class="fas fa-info-circle me-2"></i>
                        Demo mode: You can use the camera without a QR code for testing.
                    </div>
                    <p class="mb-0 mt-2" id="capturePrompt">Take your first photo (up to 3 photos allowed)</p>
                    <div class="progress mt-2" style="height: 6px;">
                        <div class="progress-bar bg-success" id="photoProgress" role="progressbar" style="width: 0%"></div>
                    </div>
                {% endif %}
            </div>
            
            <div class="camera-body">
                <!-- Camera Interface - Always show for demo mode -->
                <div id="cameraInterface" class="text-center">
                    <!-- Camera Selection -->
                    <div class="camera-controls mb-3">
                        <div class="btn-group" role="group" aria-label="Camera selection">
                            <button type="button" class="btn btn-outline-primary" id="frontCameraBtn" onclick="switchCamera('user')">
                                <i class="fas fa-user me-1"></i>Front
                            </button>
                            <button type="button" class="btn btn-primary" id="backCameraBtn" onclick="switchCamera('environment')">
                                <i class="fas fa-camera me-1"></i>Back
                            </button>
                        </div>
                    </div>
                    
                    <video id="video" autoplay playsinline></video>
                    <div class="capture-btn" onclick="capturePhoto()">
                        <i class="fas fa-camera"></i>
                    </div>
                    <canvas id="canvas"></canvas>
                </div>

                <!-- File Upload Alternative -->
                <div id="uploadInterface" style="display: none;">
                    <div class="file-upload-area" onclick="document.getElementById('fileInput').click()">
                        <i class="fas fa-cloud-upload-alt mb-3" style="font-size: 3rem; color: #28a745;"></i>
                        <h5>Choose Photo from Gallery</h5>
                        <p class="text-muted">Tap here to select an existing photo</p>
                    </div>
                    <input type="file" id="fileInput" accept="image/*" style="display: none;" onchange="handleFileSelect(this)">
                </div>

                <!-- Photo Preview -->
                <div id="photoPreview" style="display: none;" class="text-center">
                    <img id="previewImage" class="preview-image" alt="Captured photo">
                    <div class="mt-3">
                        <button class="btn btn-success btn-custom me-2" onclick="acceptPhoto()">
                            <i class="fas fa-check me-2"></i><span id="acceptButtonText">Use This Photo</span>
                        </button>
                        <button class="btn btn-outline-secondary btn-custom" onclick="retakePhoto()">
                            <i class="fas fa-redo me-2"></i>Retake
                        </button>
                    </div>
                </div>

                <!-- Captured Photos Gallery -->
                <div id="capturedGallery" style="display: none;" class="mt-4">
                    <h5>Captured Photos</h5>
                    <div id="photoThumbnails" class="d-flex flex-wrap gap-2 mb-3"></div>
                    <div class="text-center">
                        <button class="btn btn-primary btn-custom me-2" onclick="submitPhotos()">
                            <i class="fas fa-check me-2"></i>Submit Photo(s)
                        </button>
                        <button class="btn btn-outline-primary btn-custom" onclick="takeAnotherPhoto()" id="anotherPhotoBtn">
                            <i class="fas fa-camera me-2"></i>Take Another
                        </button>
                    </div>
                </div>

                <!-- Status Messages -->
                <div id="statusMessage"></div>

                <!-- Action Buttons -->
                <div class="text-center mt-4">
                    <button id="switchModeBtn" class="btn btn-outline-primary btn-custom me-2" onclick="switchMode()">
                        <i class="fas fa-exchange-alt me-2"></i>Switch to Upload
                    </button>
                    <button class="btn btn-outline-secondary btn-custom" onclick="window.close()">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let stream = null;
        let currentMode = 'camera'; // 'camera' or 'upload'
        let capturedImageBlob = null;
        let currentFacingMode = 'environment'; // 'environment' (back) or 'user' (front)
        let capturedPhotos = []; // Array to store captured photo blobs
        let maxPhotos = 3;
        
        // Get session ID from URL parameters
        const urlParams = new URLSearchParams(window.location.search);
        const sessionId = urlParams.get('session');

        // Initialize camera on page load (works in demo mode without session)
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Mobile camera loaded, session:', sessionId || 'demo mode');
            initializeCamera();
        });

        async function initializeCamera(facingMode = 'environment') {
            try {
                // Stop existing stream if any
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }

                const constraints = {
                    video: {
                        facingMode: facingMode,
                        width: { ideal: 640 },
                        height: { ideal: 480 }
                    }
                };

                stream = await navigator.mediaDevices.getUserMedia(constraints);
                const video = document.getElementById('video');
                video.srcObject = stream;
                
                // Update button states
                updateCameraButtons(facingMode);
                currentFacingMode = facingMode;
                
                showStatus('Camera ready! Tap the camera button to capture.', 'info');
            } catch (error) {
                console.error('Camera access error:', error);
                showStatus('Camera access denied. Please use file upload instead.', 'error');
                switchMode();
            }
        }

        async function switchCamera(facingMode) {
            if (currentMode !== 'camera') return;
            
            try {
                showStatus('Switching camera...', 'info');
                await initializeCamera(facingMode);
            } catch (error) {
                console.error('Error switching camera:', error);
                showStatus('Could not switch camera. Some devices only have one camera.', 'error');
            }
        }

        function updateCameraButtons(activeFacingMode) {
            const frontBtn = document.getElementById('frontCameraBtn');
            const backBtn = document.getElementById('backCameraBtn');
            
            // Reset button states
            frontBtn.className = 'btn btn-outline-primary';
            backBtn.className = 'btn btn-outline-primary';
            
            // Set active button
            if (activeFacingMode === 'user') {
                frontBtn.className = 'btn btn-primary';
            } else {
                backBtn.className = 'btn btn-primary';
            }
        }

        function capturePhoto() {
            const video = document.getElementById('video');
            const canvas = document.getElementById('canvas');
            const context = canvas.getContext('2d');

            // Set canvas size to match video
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;

            // Draw video frame to canvas
            context.drawImage(video, 0, 0);

            // Convert to blob
            canvas.toBlob(function(blob) {
                capturedImageBlob = blob;
                showPhotoPreview(canvas.toDataURL());
            }, 'image/jpeg', 0.8);
        }

        function handleFileSelect(input) {
            const file = input.files[0];
            if (file) {
                capturedImageBlob = file;
                const reader = new FileReader();
                reader.onload = function(e) {
                    showPhotoPreview(e.target.result);
                };
                reader.readAsDataURL(file);
            }
        }

        function showPhotoPreview(imageSrc) {
            document.getElementById('cameraInterface').style.display = 'none';
            document.getElementById('uploadInterface').style.display = 'none';
            document.getElementById('photoPreview').style.display = 'block';
            document.getElementById('previewImage').src = imageSrc;
        }

        function retakePhoto() {
            document.getElementById('photoPreview').style.display = 'none';
            capturedImageBlob = null;
            
            if (currentMode === 'camera') {
                document.getElementById('cameraInterface').style.display = 'block';
            } else {
                document.getElementById('uploadInterface').style.display = 'block';
            }
        }

        async function uploadPhoto() {
            if (!capturedImageBlob) {
                showStatus('No photo captured', 'error');
                return;
            }

            try {
                showStatus('Uploading photo...', 'info');

                const formData = new FormData();
                formData.append('image', capturedImageBlob, 'mobile-capture.jpg');

                const response = await fetch('/api/mobile-upload', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    showStatus('Photo uploaded successfully! You can now close this window.', 'success');
                    
                    // Auto-close after 3 seconds
                    setTimeout(() => {
                        window.close();
                    }, 3000);
                } else {
                    throw new Error('Upload failed');
                }
            } catch (error) {
                console.error('Upload error:', error);
                showStatus('Upload failed. Please try again.', 'error');
            }
        }

        async function acceptPhoto() {
            if (!capturedImageBlob) {
                showStatus('No photo to accept', 'error');
                return;
            }

            // Upload immediately after accepting the photo
            try {
                showStatus('Uploading photo...', 'info');
                
                const formData = new FormData();
                const filename = `mobile_capture_${Date.now()}_${capturedPhotos.length}.jpg`;
                formData.append('image', capturedImageBlob, filename);
                
                // Include session ID if available
                if (sessionId) {
                    formData.append('sessionId', sessionId);
                }

                const response = await fetch('/api/mobile-upload-sequential', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const result = await response.json();
                    capturedPhotos.push(capturedImageBlob);
                    showStatus(`Photo ${result.count} uploaded successfully!`, 'success');
                    
                    updateProgress();
                    showCapturedGallery();
                    
                    document.getElementById('photoPreview').style.display = 'none';
                    
                    if (capturedPhotos.length < maxPhotos && result.canAddMore) {
                        document.getElementById('cameraInterface').style.display = 'block';
                        updatePromptText();
                    } else {
                        // Auto-submit if maximum photos reached
                        setTimeout(() => {
                            submitPhotos();
                        }, 1000);
                    }
                } else {
                    const error = await response.json();
                    showStatus(`Upload failed: ${error.error}`, 'error');
                }
                
            } catch (error) {
                console.error('Upload error:', error);
                showStatus('Upload failed. Please try again.', 'error');
            }
            
            capturedImageBlob = null;
        }

        function updateProgress() {
            const progress = (capturedPhotos.length / maxPhotos) * 100;
            document.getElementById('photoProgress').style.width = progress + '%';
        }

        function updatePromptText() {
            const promptElement = document.getElementById('capturePrompt');
            const acceptButtonText = document.getElementById('acceptButtonText');
            
            if (capturedPhotos.length === 0) {
                promptElement.textContent = 'Take your first photo (up to 3 photos allowed)';
                acceptButtonText.textContent = 'Use This Photo';
            } else if (capturedPhotos.length === 1) {
                promptElement.textContent = 'Take another photo? (optional)';
                acceptButtonText.textContent = 'Add This Photo';
            } else if (capturedPhotos.length === 2) {
                promptElement.textContent = 'One more photo? (last one)';
                acceptButtonText.textContent = 'Add Final Photo';
            }
        }

        function showCapturedGallery() {
            const galleryDiv = document.getElementById('capturedGallery');
            const thumbnailsDiv = document.getElementById('photoThumbnails');
            const anotherPhotoBtn = document.getElementById('anotherPhotoBtn');
            
            thumbnailsDiv.innerHTML = '';
            
            capturedPhotos.forEach((blob, index) => {
                const img = document.createElement('img');
                img.src = URL.createObjectURL(blob);
                img.style.width = '80px';
                img.style.height = '80px';
                img.style.objectFit = 'cover';
                img.style.borderRadius = '8px';
                img.style.border = '2px solid #28a745';
                thumbnailsDiv.appendChild(img);
            });
            
            if (capturedPhotos.length >= maxPhotos) {
                anotherPhotoBtn.style.display = 'none';
            } else {
                anotherPhotoBtn.style.display = 'inline-block';
                anotherPhotoBtn.textContent = capturedPhotos.length === 2 ? 'Take Final Photo' : 'Take Another';
            }
            
            galleryDiv.style.display = 'block';
        }

        function takeAnotherPhoto() {
            document.getElementById('capturedGallery').style.display = 'none';
            document.getElementById('cameraInterface').style.display = 'block';
            updatePromptText();
        }

        function continueToItemForm() {
            if (capturedPhotos.length === 0) {
                showStatus('Please capture at least one photo', 'error');
                return;
            }

            showStatus('Redirecting to create item form...', 'success');
            setTimeout(() => {
                window.location.href = '/create-item';
            }, 1000);
        }

        function switchMode() {
            if (currentMode === 'camera') {
                currentMode = 'upload';
                document.getElementById('cameraInterface').style.display = 'none';
                document.getElementById('uploadInterface').style.display = 'block';
                document.getElementById('switchModeBtn').innerHTML = '<i class="fas fa-camera me-2"></i>Switch to Camera';
                
                // Stop camera stream
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }
            } else {
                currentMode = 'camera';
                document.getElementById('uploadInterface').style.display = 'none';
                document.getElementById('cameraInterface').style.display = 'block';
                document.getElementById('switchModeBtn').innerHTML = '<i class="fas fa-upload me-2"></i>Switch to Upload';
                
                // Restart camera with previously selected facing mode
                initializeCamera(currentFacingMode);
            }
        }

        function showStatus(message, type) {
            const statusDiv = document.getElementById('statusMessage');
            statusDiv.innerHTML = `<div class="status-message status-${type}">${message}</div>`;
            
            // Auto-hide after 5 seconds for non-success messages
            if (type !== 'success') {
                setTimeout(() => {
                    statusDiv.innerHTML = '';
                }, 5000);
            }
        }

        // Cleanup when page is closed
        window.addEventListener('beforeunload', function() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
        });

        // Handle drag and drop for file upload
        const uploadArea = document.querySelector('.file-upload-area');
        
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0 && files[0].type.startsWith('image/')) {
                capturedImageBlob = files[0];
                const reader = new FileReader();
                reader.onload = function(e) {
                    showPhotoPreview(e.target.result);
                };
                reader.readAsDataURL(files[0]);
            }
        });

        function submitPhotos() {
            showStatus('Thanks for submitting!', 'success');
            
            // Close window after brief success message
            setTimeout(() => {
                try {
                    window.close();
                } catch (error) {
                    // If window.close() fails, show instructions
                    showStatus('Please return to the main tab to continue.', 'info');
                }
            }, 2000);
        }
        
        // Legacy function name for compatibility
        function continueToItemForm() {
            submitPhotos();
        }
    </script>
</body>
</html>