<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Location - CGW Product Finder</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: 14px;
        }

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

        .user-info p {
            color: #333;
            margin-bottom: 5px;
        }

        .user-info strong {
            color: #667eea;
        }

        .location-list {
            margin-bottom: 25px;
        }

        .location-item {
            background: #f7fafc;
            padding: 15px 20px;
            border-radius: 5px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
            display: flex;
            align-items: center;
        }

        .location-item:hover {
            background: #e6f2ff;
            border-color: #667eea;
            transform: translateX(5px);
        }

        .location-item input[type="radio"] {
            margin-right: 15px;
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .location-item label {
            cursor: pointer;
            flex: 1;
            font-size: 16px;
            color: #333;
            font-weight: 500;
        }

        .location-badge {
            background: #667eea;
            color: white;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .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;
        }

        .btn-logout {
            background: #f56565;
            margin-top: 15px;
        }

        .btn-logout:hover {
            background: #e53e3e;
            box-shadow: 0 5px 15px rgba(245, 101, 101, 0.4);
        }

        .btn-admin {
            background: #48bb78;
            margin-top: 15px;
        }

        .btn-admin:hover {
            background: #38a169;
            box-shadow: 0 5px 15px rgba(72, 187, 120, 0.4);
        }

        .btn-admin.hidden {
            display: 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;
        }
    </style>
</head>
<body>
    <div class="location-container">
        <div class="location-header">
            <h1>📍 Select Your Location</h1>
            <p>Choose a location to access the Product Finder</p>
        </div>

        <div class="user-info" id="userInfo">
            <p><strong>Welcome:</strong> <span id="userName"></span></p>
            <p><strong>Default Location:</strong> <span id="defaultLocation"></span></p>
        </div>

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

        <form id="locationForm">
            <div class="location-list" id="locationList">
                <!-- Locations will be populated here -->
            </div>

            <button type="submit" class="btn" id="continueBtn">
                Continue to Product Finder
            </button>
        </form>

        <button class="btn btn-admin hidden" id="userManagementBtn" onclick="goToUserManagement()">
            ⚙️ User Management
        </button>

        <button class="btn btn-logout" onclick="logout()">
            Sign Out
        </button>
    </div>

    <script>
        // Base URL for API calls (supports subdirectory deployments)
        const BASE_URL = '{{ base_url }}';
        
        const LOCATION_NAMES = {
            'LINDS': 'Lindsborg',
            'IOLA': 'Iola',
            'KC': 'KC',
            'BMD': 'BMD'
        };

        let sessionData = null;

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

                if (data.status === 'success') {
                    sessionData = data;
                    
                    // Populate user info
                    document.getElementById('userName').textContent = data.username;
                    document.getElementById('defaultLocation').textContent = 
                        LOCATION_NAMES[data.defaultLocation] || data.defaultLocation;

                    // Populate location list
                    const locationList = document.getElementById('locationList');
                    const locations = data.accessibleLocations || [];

                    if (locations.length === 0) {
                        showAlert('No accessible locations found. Please contact an administrator.');
                        document.getElementById('continueBtn').disabled = true;
                        return;
                    }

                    locationList.innerHTML = locations.map((code, index) => {
                        const isDefault = code === data.defaultLocation;
                        const checked = isDefault ? 'checked' : '';
                        
                        return `
                            <div class="location-item" onclick="selectLocation('${code}')">
                                <input type="radio" name="location" value="${code}" 
                                       id="loc_${code}" ${checked}>
                                <label for="loc_${code}">
                                    ${LOCATION_NAMES[code] || code}
                                </label>
                                ${isDefault ? '<span class="location-badge">Default</span>' : ''}
                            </div>
                        `;
                    }).join('');
                } else {
                    // Not logged in or session expired
                    window.location.href = BASE_URL + '/login?message=' + encodeURIComponent('Please log in first');
                }

                // Check if user has manage_users permission
                await checkUserManagementPermission();
            } catch (error) {
                showAlert('Error loading location data. Please try again.');
            }
        }

        async function checkUserManagementPermission() {
            try {
                const response = await fetch(BASE_URL + '/api/check-permission', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ permission: 'manage_users' })
                });

                const data = await response.json();

                if (data.status === 'success' && data.hasPermission) {
                    document.getElementById('userManagementBtn').classList.remove('hidden');
                }
            } catch (error) {
                // Permission check failed, keep button hidden
                console.error('Error checking permission:', error);
            }
        }

        function goToUserManagement() {
            window.location.href = BASE_URL + '/users';
        }

        function selectLocation(code) {
            document.getElementById(`loc_${code}`).checked = true;
        }

        document.getElementById('locationForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const selectedLocation = document.querySelector('input[name="location"]:checked')?.value;
            
            if (!selectedLocation) {
                showAlert('Please select a location');
                return;
            }

            try {
                const response = await fetch(BASE_URL + '/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 main app
                    window.location.href = BASE_URL + '/';
                } else {
                    showAlert(data.message || 'Error selecting location');
                }
            } catch (error) {
                showAlert('Error connecting to server. Please try again.');
            }
        });

        async function logout() {
            try {
                await fetch(BASE_URL + '/api/logout', { method: 'POST' });
                window.location.href = BASE_URL + '/login?message=' + encodeURIComponent('Successfully logged out');
            } catch (error) {
                window.location.href = BASE_URL + '/login';
            }
        }

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

            setTimeout(() => {
                alert.classList.remove('show');
            }, 5000);
        }

        // Load location data on page load
        loadLocationData();
    </script>
</body>
</html>
