<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Face Detection Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            text-align: center;
        }
        #videoContainer {
            position: relative;
            margin: 20px auto;
            width: 400px;
            height: 300px;
            border: 2px solid #ccc;
        }
        #video {
            width: 100%;
            height: 100%;
            background-color: #000;
        }
        #overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
        }
        .controls {
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            font-size: 16px;
        }
        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .warning {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Face Detection Test Page</h1>
        <p>This page tests if face detection is working properly on your system.</p>
        
        <div class="status warning" id="statusMessage">
            Initializing face detection...
        </div>
        
        <div id="videoContainer">
            <video id="video" autoplay playsinline></video>
            <canvas id="overlay"></canvas>
        </div>
        
        <div class="controls">
            <button id="startButton">Start Camera</button>
            <button id="detectButton" disabled>Detect Face</button>
            <button id="stopButton" disabled>Stop Camera</button>
        </div>
        
        <div id="results"></div>
    </div>

    <!-- Load face-api.js from CDN -->
    <script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script>
    <script>
        let videoStream = null;
        const video = document.getElementById('video');
        const overlay = document.getElementById('overlay');
        const startButton = document.getElementById('startButton');
        const detectButton = document.getElementById('detectButton');
        const stopButton = document.getElementById('stopButton');
        const statusMessage = document.getElementById('statusMessage');
        const resultsDiv = document.getElementById('results');

        // Check if face-api.js is loaded
        if (window.faceapi) {
            statusMessage.innerHTML = 'Face-API.js loaded successfully. Ready to test.';
            statusMessage.className = 'status success';
        } else {
            statusMessage.innerHTML = 'Error: Face-API.js failed to load. This is why face detection is not working.';
            statusMessage.className = 'status error';
        }

        startButton.addEventListener('click', async () => {
            try {
                statusMessage.innerHTML = 'Accessing camera...';
                statusMessage.className = 'status warning';
                
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: 'user' }
                });
                
                videoStream = stream;
                video.srcObject = stream;
                
                startButton.disabled = true;
                detectButton.disabled = false;
                stopButton.disabled = false;
                
                statusMessage.innerHTML = 'Camera started. Position your face in front of the camera.';
                statusMessage.className = 'status success';
            } catch (err) {
                console.error('Error accessing camera:', err);
                statusMessage.innerHTML = 'Error accessing camera: ' + err.message;
                statusMessage.className = 'status error';
            }
        });

        stopButton.addEventListener('click', () => {
            if (videoStream) {
                const tracks = videoStream.getTracks();
                tracks.forEach(track => track.stop());
                videoStream = null;
                video.srcObject = null;
                
                startButton.disabled = false;
                detectButton.disabled = true;
                stopButton.disabled = true;
                
                statusMessage.innerHTML = 'Camera stopped.';
                statusMessage.className = 'status warning';
            }
        });

        detectButton.addEventListener('click', async () => {
            if (!window.faceapi) {
                resultsDiv.innerHTML = '<div class="status error">Face-API.js is not loaded. Face detection will not work.</div>';
                return;
            }
            
            statusMessage.innerHTML = 'Loading face detection model...';
            statusMessage.className = 'status warning';
            
            try {
                // Try loading the model from CDN
                await faceapi.nets.tinyFaceDetector.loadFromUri('https://justadudewhohacks.github.io/face-api.js/weights/tiny_face_detector');
                
                statusMessage.innerHTML = 'Model loaded. Detecting face...';
                
                // Detect faces
                const detections = await faceapi.detectAllFaces(
                    video,
                    new faceapi.TinyFaceDetectorOptions()
                );
                
                // Draw detections on overlay
                const canvas = document.getElementById('overlay');
                faceapi.matchDimensions(canvas, { width: video.videoWidth, height: video.videoHeight });
                
                const resizedDetections = faceapi.resizeResults(detections, { width: video.videoWidth, height: video.videoHeight });
                
                // Clear previous drawings
                const ctx = canvas.getContext('2d');
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // Draw rectangles around detected faces
                faceapi.draw.drawDetections(canvas, resizedDetections);
                
                if (detections.length > 0) {
                    resultsDiv.innerHTML = `<div class="status success">${detections.length} face(s) detected successfully!</div>`;
                    statusMessage.innerHTML = 'Face detection working properly.';
                    statusMessage.className = 'status success';
                } else {
                    resultsDiv.innerHTML = '<div class="status error">No faces detected. Make sure your face is visible in the camera frame.</div>';
                    statusMessage.innerHTML = 'No face detected.';
                    statusMessage.className = 'status error';
                }
            } catch (err) {
                console.error('Face detection error:', err);
                resultsDiv.innerHTML = `<div class="status error">Face detection error: ${err.message}</div>`;
                statusMessage.innerHTML = 'Face detection failed.';
                statusMessage.className = 'status error';
            }
        });
    </script>
</body>
</html>