<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Love Alarm - Connect with people around you" />
    <title>Love Alarm</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        html, body, #root {
            width: 100%;
            height: 100%;
        }

        /* Home Page Styles */
        .home-container {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .gradient-bg {
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #86F1F9 0%, #FDD0ED 100%);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 20px;
            padding: 20px;
            max-width: 500px;
            width: 100%;
        }

        .title {
            font-size: 48px;
            font-weight: bold;
            color: white;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }

        .animation-container {
            width: 250px;
            height: 250px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
        }

        .heart-emoji {
            font-size: 100px;
            animation: heartbeat 1.5s infinite;
        }

        @keyframes heartbeat {
            0%, 100% { transform: scale(1); }
            25% { transform: scale(1.1); }
            50% { transform: scale(1.2); }
            75% { transform: scale(1.1); }
        }

        .input-field {
            width: 80%;
            height: 45px;
            padding: 0 15px;
            border: 2px solid white;
            border-radius: 8px;
            background-color: rgba(255, 255, 255, 0.3);
            color: white;
            font-size: 16px;
            font-family: 'Gill Sans', sans-serif;
            transition: all 0.3s ease;
        }

        .input-field::placeholder {
            color: rgba(255, 255, 255, 0.7);
        }

        .input-field:focus {
            outline: none;
            background-color: rgba(255, 255, 255, 0.5);
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
        }

        textarea.input-field {
            height: auto;
            min-height: 80px;
            resize: vertical;
        }

        .button {
            background-color: #F87B92;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            font-family: 'Gill Sans', sans-serif;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
        }

        .button:hover {
            background-color: #F05778;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(248, 123, 146, 0.4);
        }

        .button:active {
            transform: translateY(0);
        }

        .error-message {
            color: #ff6b6b;
            background-color: rgba(255, 107, 107, 0.2);
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 14px;
            margin-top: 10px;
            border: 1px solid rgba(255, 107, 107, 0.5);
            width: 80%;
            text-align: center;
            display: none;
        }

        .location-info {
            color: rgba(255, 255, 255, 0.8);
            margin-top: 15px;
            font-size: 12px;
        }

        /* Matching Page Styles */
        .matching-container {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            position: relative;
        }

        .circle-animation {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.3);
            }
            50% {
                transform: scale(1.05);
                box-shadow: 0 0 0 10px rgba(255, 255, 255, 0);
            }
        }

        .hearts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
            gap: 20px;
            width: 100%;
            height: 100%;
            align-content: center;
            justify-content: center;
            padding: 40px;
        }

        .heart-item {
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .heart-item .heart-emoji {
            font-size: 50px;
            animation: float 3s ease-in-out infinite;
            transition: all 0.3s ease;
        }

        .heart-item:hover .heart-emoji {
            font-size: 60px;
            animation: heartbeatClick 0.6s ease-in-out;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }

        @keyframes heartbeatClick {
            0% { transform: scale(1); }
            25% { transform: scale(1.2); }
            50% { transform: scale(1); }
            75% { transform: scale(1.15); }
            100% { transform: scale(1); }
        }

        .text-container {
            position: absolute;
            top: 65%;
            left: 50%;
            transform: translateX(-50%);
            text-align: center;
            z-index: 10;
        }

        .text {
            font-size: 16px;
            font-weight: bold;
            color: white;
            margin: 5px 0;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
        }

        .number-container {
            position: absolute;
            bottom: 40px;
            left: 50%;
            transform: translateX(-50%);
            text-align: center;
        }

        .number {
            font-size: 60px;
            font-weight: bold;
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
        }

        .back-button {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background-color: rgba(255, 255, 255, 0.3);
            color: white;
            border: 2px solid white;
            padding: 10px 20px;
            border-radius: 5px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            font-family: 'Gill Sans', sans-serif;
        }

        .back-button:hover {
            background-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-2px);
        }

        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal-content {
            background-color: #FFB6D9;
            border-radius: 200px;
            padding: 60px 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        .modal-title {
            color: white;
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 30px;
            font-family: 'Gill Sans', sans-serif;
        }

        .modal-info {
            width: 100%;
            margin-bottom: 20px;
            text-align: center;
        }

        .modal-text {
            color: white;
            font-size: 16px;
            margin-bottom: 15px;
            font-family: 'Gill Sans', sans-serif;
        }

        .ring-button {
            background-color: #F87B92;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
            margin-bottom: 15px;
            font-family: 'Gill Sans', sans-serif;
        }

        .ring-button:hover {
            background-color: #F05778;
            transform: scale(1.05);
        }

        .close-button {
            background-color: transparent;
            color: white;
            border: none;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            font-family: 'Gill Sans', sans-serif;
            margin-top: 10px;
        }

        .close-button:hover {
            opacity: 0.8;
        }

        .success-message {
            text-align: center;
        }

        .success-message h2 {
            color: white;
            font-size: 28px;
            margin-bottom: 10px;
            font-family: 'Gill Sans', sans-serif;
        }

        .success-message p {
            color: white;
            font-size: 16px;
            font-family: 'Gill Sans', sans-serif;
        }

        @media (max-width: 600px) {
            .title {
                font-size: 36px;
            }

            .animation-container {
                width: 200px;
                height: 200px;
            }

            .heart-emoji {
                font-size: 80px;
            }

            .input-field {
                width: 90%;
            }

            .back-button {
                font-size: 12px;
                padding: 8px 15px;
            }
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <script>
        const API_URL = window.location.origin; // Auto-detect API URL

        // Application State
        let currentUser = null;
        let currentPage = 'home';
        let nearbyUsers = [];
        let locationUpdateInterval = null;
        let nearbyUsersInterval = null;

        // Initialize app
        document.addEventListener('DOMContentLoaded', initializeApp);

        function initializeApp() {
            showHomePage();
        }

        function showHomePage() {
            currentPage = 'home';
            const root = document.getElementById('root');
            
            root.innerHTML = `
                <div class="home-container">
                    <div class="gradient-bg">
                        <div class="content">
                            <h1 class="title">Love Alarm</h1>
                            
                            <div class="animation-container">
                                <div class="heart-emoji">💕</div>
                            </div>

                            <input type="text" class="input-field" id="nameInput" placeholder="Your Name" />
                            <textarea class="input-field" id="descInput" placeholder="Short Description" rows="3"></textarea>
                            <div id="errorMsg" class="error-message"></div>
                            <button class="button" onclick="handleStartMatching()">Start Matching</button>
                            <div class="location-info" id="locationInfo"></div>
                        </div>
                    </div>
                </div>
            `;

            requestLocation();
        }

        function requestLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        currentUser = {
                            latitude: position.coords.latitude,
                            longitude: position.coords.longitude
                        };
                        updateLocationDisplay();
                    },
                    (error) => {
                        showError('Unable to access location. Please enable location services.');
                    }
                );
            } else {
                showError('Geolocation is not supported by your browser.');
            }
        }

        function updateLocationDisplay() {
            if (currentUser && currentUser.latitude) {
                const info = document.getElementById('locationInfo');
                if (info) {
                    info.innerHTML = `Location: ${currentUser.latitude.toFixed(4)}, ${currentUser.longitude.toFixed(4)}`;
                }
            }
        }

        function handleStartMatching() {
            const name = document.getElementById('nameInput').value.trim();
            const description = document.getElementById('descInput').value.trim();

            if (!name || !description) {
                showError('Please enter your name and description');
                return;
            }

            if (!currentUser || !currentUser.latitude) {
                showError('Location data not available. Please enable location services.');
                return;
            }

            saveUserProfile(name, description);
        }

        async function saveUserProfile(name, description) {
            try {
                const response = await fetch(`${API_URL}/index.php/api/record`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name,
                        description,
                        latitude: currentUser.latitude,
                        longitude: currentUser.longitude
                    })
                });

                if (response.ok) {
                    currentUser.name = name;
                    currentUser.description = description;
                    showMatchingPage();
                } else {
                    showError('Failed to save user data');
                }
            } catch (error) {
                showError('Error: ' + error.message);
            }
        }

        function showMatchingPage() {
            currentPage = 'matching';
            const root = document.getElementById('root');
            
            root.innerHTML = `
                <div class="matching-container">
                    <div class="gradient-bg">
                        <div class="content">
                            <h1 class="title">Love Alarm</h1>

                            <div class="animation-container" style="width: 400px; height: 400px; margin-top: 50px; margin-bottom: 50px;">
                                <div class="circle-animation">
                                    <div class="hearts-grid" id="heartsGrid"></div>
                                </div>
                            </div>

                            <div class="text-container">
                                <p class="text">Someone within a 1km radius</p>
                                <p class="text">rang your alarm 🔔</p>
                            </div>

                            <div class="number-container">
                                <div class="number" id="likesCount">0</div>
                            </div>

                            <button class="back-button" onclick="goHome()">← Back to Home</button>
                        </div>
                    </div>
                </div>
            `;

            pollNearbyUsers();
        }

        function pollNearbyUsers() {
            getNearbyUsers();
            nearbyUsersInterval = setInterval(getNearbyUsers, 2000);
            locationUpdateInterval = setInterval(updateUserLocation, 2000);
        }

        async function getNearbyUsers() {
            if (!currentUser || !currentUser.name) return;

            try {
                const response = await fetch(`${API_URL}/index.php/api/nearbyUsers`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: currentUser.name,
                        latitude: currentUser.latitude,
                        longitude: currentUser.longitude
                    })
                });

                if (response.ok) {
                    const data = await response.json();
                    nearbyUsers = data.nearbyUsers || [];
                    displayNearbyUsers();
                    updateLikesCount(data.likesCount);
                }
            } catch (error) {
                console.error('Error fetching nearby users:', error);
            }
        }

        function displayNearbyUsers() {
            const grid = document.getElementById('heartsGrid');
            if (!grid) return;

            const filteredUsers = nearbyUsers.filter(u => u.name !== currentUser.name);
            
            grid.innerHTML = filteredUsers.map((user, index) => `
                <div class="heart-item" onclick="showUserModal(${index})">
                    <span class="heart-emoji">❤️</span>
                </div>
            `).join('');
        }

        function updateLikesCount(count) {
            const likesEl = document.getElementById('likesCount');
            if (likesEl) {
                likesEl.textContent = count;
            }
        }

        async function updateUserLocation() {
            if (navigator.geolocation && currentUser && currentUser.name) {
                navigator.geolocation.getCurrentPosition((position) => {
                    currentUser.latitude = position.coords.latitude;
                    currentUser.longitude = position.coords.longitude;
                });
            }
        }

        function showUserModal(userIndex) {
            const user = nearbyUsers[userIndex];
            if (!user) return;

            const modal = document.createElement('div');
            modal.className = 'modal-overlay';
            modal.innerHTML = `
                <div class="modal-content" onclick="event.stopPropagation()">
                    <h2 class="modal-title">I am...</h2>
                    <div class="modal-info">
                        <p class="modal-text"><strong>Name:</strong> ${user.name}</p>
                        <p class="modal-text"><strong>Description:</strong> ${user.description}</p>
                    </div>
                    <button class="ring-button" onclick="likeUser('${user.name.replace(/'/g, "\\'")}')">RING 🔔</button>
                    <button class="close-button" onclick="this.closest('.modal-overlay').remove()">Close</button>
                </div>
            `;

            modal.onclick = () => modal.remove();
            document.body.appendChild(modal);
        }

        async function likeUser(likeName) {
            if (!currentUser || !currentUser.name) return;

            try {
                const response = await fetch(`${API_URL}/index.php/api/likeUsers`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        userName: currentUser.name,
                        likeName: likeName
                    })
                });

                if (response.ok) {
                    const modals = document.querySelectorAll('.modal-overlay');
                    if (modals.length > 0) {
                        const lastModal = modals[modals.length - 1];
                        lastModal.innerHTML = `
                            <div class="modal-content" onclick="event.stopPropagation()">
                                <div class="success-message">
                                    <h2>SUCCESS! 🎉</h2>
                                    <p>You've liked ${likeName}</p>
                                </div>
                                <button class="close-button" onclick="this.closest('.modal-overlay').remove()">Close</button>
                            </div>
                        `;
                    }
                }
            } catch (error) {
                showError('Error liking user: ' + error.message);
            }
        }

        function goHome() {
            if (locationUpdateInterval) clearInterval(locationUpdateInterval);
            if (nearbyUsersInterval) clearInterval(nearbyUsersInterval);
            currentUser = null;
            nearbyUsers = [];
            showHomePage();
        }

        function showError(message) {
            const errorEl = document.getElementById('errorMsg');
            if (errorEl) {
                errorEl.textContent = message;
                errorEl.style.display = 'block';
                setTimeout(() => {
                    errorEl.style.display = 'none';
                }, 5000);
            }
        }
    </script>
</body>
</html>