<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Location</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .location-container {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            width: 100%;
            max-width: 500px;
        }

        .location-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .location-header h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }

        .location-header p {
            color: #666;
            font-size: 15px;
        }

        .user-info {
            background: #f7fafc;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 30px;
            border-left: 4px solid #667eea;
        }

        .user-info strong {
            color: #333;
            display: block;
            margin-bottom: 5px;
        }

        .user-info span {
            color: #666;
            font-size: 14px;
        }

        .location-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .location-card {
            background: #f7fafc;
            border: 3px solid #e0e0e0;
            border-radius: 8px;
            padding: 30px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            position: relative;
        }

        .location-card:hover {
            border-color: #667eea;
            background: #edf2f7;
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .location-card.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .location-card .icon {
            font-size: 40px;
            margin-bottom: 10px;
        }

        .location-card .name {
            font-size: 18px;
            font-weight: 600;
        }

        .location-card .description {
            font-size: 13px;
            margin-top: 5px;
            opacity: 0.8;
        }

        .btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            background: #667eea;
            color: white;
        }

        .btn:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn:disabled {
            background: #cbd5e0;
            cursor: not-allowed;
            transform: none;
        }

        .alert {
            padding: 12px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: none;
        }

        .alert.show {
            display: block;
        }

        .alert-error {
            background: #fed7d7;
            color: #742a2a;
            border-left: 4px solid #f56565;
        }

        .footer {
            text-align: center;
            margin-top: 20px;
        }

        .footer a {
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
        }

        .footer a:hover {
            text-decoration: underline;
        }

        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-left: 10px;
            vertical-align: middle;
            display: none;
        }

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

        @media (max-width: 600px) {
            .location-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="location-container">
        <div class="location-header">
            <h1>📍 Select Your Location</h1>
            <p>Choose which location you'll be working from today</p>
        </div>

        <div class="user-info">
            <strong>Welcome, <span id="username">User</span>!</strong>
            <span>Default Location: <span id="defaultLocation">-</span></span>
        </div>

        <div class="alert alert-error" id="errorAlert"></div>

        <div class="location-grid" id="locationGrid">
            <!-- Locations will be populated here -->
        </div>

        <button class="btn" id="confirmBtn" disabled>
            Confirm Location
            <span class="loading-spinner" id="loadingSpinner"></span>
        </button>

        <div class="footer">
            <a href="{{ url_for('users.user_manager') }}" id="manageUsersLink" style="display: none; margin-right: 15px;">Manage Users</a>
            <a href="{{ url_for('auth.logout') }}">Logout</a>
        </div>
    </div>

    <script>
        let selectedLocation = null;
        let sessionData = null;

        // Location details
        const locationDetails = {
            'LINDS': {
                icon: '🏭',
                name: 'LINDS',
                description: 'Lindsborg Location'
            },
            'IOLA': {
                icon: '🏢',
                name: 'IOLA',
                description: 'Iola Location'
            },
            'KC': {
                icon: '🌆',
                name: 'KC',
                description: 'Kansas City Location'
            },
            'BMD': {
                icon: '🏛️',
                name: 'BMD',
                description: 'BMD Location'
            }
        };

        // Load session data on page load
        loadSessionData();

        async function loadSessionData() {
            try {
                const response = await fetch('/api/session');
                const data = await response.json();

                if (data.status === 'success') {
                    sessionData = data;
                    document.getElementById('username').textContent = data.username;
                    document.getElementById('defaultLocation').textContent = data.defaultLocation || 'Not set';

                    // Show manage users link if user has permission
                    if (data.permissions && data.permissions.manage_users === true) {
                        document.getElementById('manageUsersLink').style.display = 'inline';
                    }

                    // Render accessible locations
                    renderLocations(data.accessibleLocations || []);

                    // Auto-select default location if available
                    if (data.defaultLocation && data.accessibleLocations.includes(data.defaultLocation)) {
                        selectLocation(data.defaultLocation);
                    }
                } else {
                    showError('Error loading session. Please login again.');
                    setTimeout(() => {
                        window.location.href = '{{ url_for("auth.login_page") }}';
                    }, 2000);
                }
            } catch (error) {
                showError('Error connecting to server.');
            }
        }

        function renderLocations(accessibleLocations) {
            const grid = document.getElementById('locationGrid');

            if (accessibleLocations.length === 0) {
                grid.innerHTML = '<p style="color: #666; text-align: center; grid-column: 1 / -1;">No accessible locations found.</p>';
                return;
            }

            grid.innerHTML = accessibleLocations.map(locCode => {
                const loc = locationDetails[locCode] || {
                    icon: '📍',
                    name: locCode,
                    description: locCode
                };

                return `
                    <div class="location-card" onclick="selectLocation('${locCode}')" data-location="${locCode}">
                        <div class="icon">${loc.icon}</div>
                        <div class="name">${loc.name}</div>
                        <div class="description">${loc.description}</div>
                    </div>
                `;
            }).join('');
        }

        function selectLocation(locCode) {
            selectedLocation = locCode;

            // Remove selected class from all cards
            document.querySelectorAll('.location-card').forEach(card => {
                card.classList.remove('selected');
            });

            // Add selected class to clicked card
            const card = document.querySelector(`[data-location="${locCode}"]`);
            if (card) {
                card.classList.add('selected');
            }

            // Enable confirm button
            document.getElementById('confirmBtn').disabled = false;
        }

        document.getElementById('confirmBtn').addEventListener('click', async () => {
            if (!selectedLocation) return;

            const confirmBtn = document.getElementById('confirmBtn');
            const spinner = document.getElementById('loadingSpinner');

            confirmBtn.disabled = true;
            spinner.style.display = 'inline-block';

            try {
                const response = await fetch('/api/select-location', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ location: selectedLocation })
                });

                const data = await response.json();

                if (data.status === 'success') {
                    // Redirect to quiz page
                    window.location.href = '{{ url_for("products.product_finder") }}';
                } else {
                    showError(data.message || 'Error selecting location');
                    confirmBtn.disabled = false;
                    spinner.style.display = 'none';
                }
            } catch (error) {
                showError('Error connecting to server');
                confirmBtn.disabled = false;
                spinner.style.display = 'none';
            }
        });

        function showError(message) {
            const alert = document.getElementById('errorAlert');
            alert.textContent = message;
            alert.classList.add('show');

            setTimeout(() => {
                alert.classList.remove('show');
            }, 5000);
        }
    </script>
</body>
</html>
