/**
 * 🌍 City Service — Central city management for the Wassili multi-city platform.
 * 
 * Responsibilities:
 * - Persist the selected city in localStorage
 * - Provide a full-screen city selection UI on first launch
 * - Expose getters/setters used by all pages (order, registration, pricing, etc.)
 * 
 * Usage:
 *   CityService.getCity()         → 'Khartoum' | 'PortSudan'
 *   CityService.hasCity()         → boolean
 *   CityService.setCity('PortSudan')
 *   CityService.showCityPicker()  → Promise (resolves after user picks)
 *   CityService.ensureCity()      → Promise (shows picker only if no city is set)
 */

const CityService = {
    STORAGE_KEY: 'selected_city',
    VALID_CITIES: ['Khartoum', 'PortSudan'],

    /** Arabic labels for UI display */
    CITY_LABELS: {
        Khartoum:  'الخرطوم (أم درمان)',
        PortSudan: 'بورتسودان'
    },

    /** City emoji/icon for visual distinction */
    CITY_ICONS: {
        Khartoum:  '🏙️',
        PortSudan: '🌊'
    },

    /**
     * Get the currently selected city.
     * Falls back to 'Khartoum' if nothing is stored (backward compat).
     * @returns {string} 'Khartoum' | 'PortSudan'
     */
    getCity() {
        const saved = localStorage.getItem(this.STORAGE_KEY);
        return this.VALID_CITIES.includes(saved) ? saved : null;
    },

    /**
     * Check if a city has been explicitly selected.
     * @returns {boolean}
     */
    hasCity() {
        return this.VALID_CITIES.includes(localStorage.getItem(this.STORAGE_KEY));
    },

    /**
     * Persist the selected city.
     * @param {string} city - 'Khartoum' | 'PortSudan'
     */
    setCity(city) {
        if (!this.VALID_CITIES.includes(city)) {
            console.warn('[CityService] Invalid city:', city, '— ignoring.');
            return;
        }
        localStorage.setItem(this.STORAGE_KEY, city);
        // Emit a DOM event so any open page can react (e.g., admin panel city switch)
        window.dispatchEvent(new CustomEvent('city-changed', { detail: { city } }));
        console.log('🌍 City set to:', city);
    },

    /**
     * Get the Arabic display label for a city.
     * @param {string} [city] - defaults to current city
     * @returns {string}
     */
    getCityLabel(city) {
        const c = city || this.getCity() || 'Khartoum';
        return this.CITY_LABELS[c] || c;
    },

    /**
     * Show the full-screen city selection modal.
     * Returns a Promise that resolves with the selected city string.
     * The user CANNOT dismiss this without selecting — it's a hard gate.
     * @returns {Promise<string>}
     */
    showCityPicker() {
        return new Promise((resolve) => {
            // Create a full-screen overlay
            const overlay = document.createElement('div');
            overlay.id = 'city-picker-overlay';
            overlay.innerHTML = `
                <div class="city-picker-container">
                    <div class="city-picker-header">
                        <img src="/icons/icon-192x192.png" alt="Wassili" class="city-picker-logo">
                        <h2>مرحباً بك في وصل-لي!</h2>
                        <p>اختر مدينتك لنعرض لك الخدمات المتاحة</p>
                    </div>
                    <div class="city-picker-cards">
                        <button class="city-card" data-city="Khartoum">
                            <div class="city-card-icon">🏙️</div>
                            <div class="city-card-name">الخرطوم</div>
                            <div class="city-card-sub">أم درمان والخرطوم</div>
                        </button>
                        <button class="city-card" data-city="PortSudan">
                            <div class="city-card-icon">🌊</div>
                            <div class="city-card-name">بورتسودان</div>
                            <div class="city-card-sub">ولاية البحر الأحمر</div>
                        </button>
                    </div>
                    <p class="city-picker-note">⚠️ لا يمكن تغيير المدينة لاحقاً إلا من خلال الإدارة</p>
                </div>
            `;

            // Inject styles (scoped to the overlay)
            const style = document.createElement('style');
            style.textContent = `
                #city-picker-overlay {
                    position: fixed; inset: 0; z-index: 2147483647;
                    background: linear-gradient(135deg, #0a8754 0%, #065a3a 50%, #033a25 100%);
                    display: flex; align-items: center; justify-content: center;
                    font-family: 'Cairo', 'Segoe UI', sans-serif;
                    direction: rtl;
                    animation: cityPickerFadeIn 0.4s ease-out;
                }
                @keyframes cityPickerFadeIn {
                    from { opacity: 0; }
                    to   { opacity: 1; }
                }
                .city-picker-container {
                    text-align: center;
                    padding: 30px 20px;
                    max-width: 420px;
                    width: 100%;
                }
                .city-picker-logo {
                    width: 80px; height: 80px;
                    border-radius: 20px;
                    box-shadow: 0 8px 32px rgba(0,0,0,0.3);
                    margin-bottom: 20px;
                    animation: cityLogoFloat 3s ease-in-out infinite;
                }
                @keyframes cityLogoFloat {
                    0%, 100% { transform: translateY(0); }
                    50%      { transform: translateY(-8px); }
                }
                .city-picker-header h2 {
                    color: #fff;
                    font-size: 1.6rem;
                    font-weight: 700;
                    margin: 0 0 8px;
                }
                .city-picker-header p {
                    color: rgba(255,255,255,0.8);
                    font-size: 0.95rem;
                    margin: 0 0 30px;
                }
                .city-picker-cards {
                    display: flex;
                    gap: 16px;
                    justify-content: center;
                    flex-wrap: wrap;
                }
                .city-card {
                    background: rgba(255,255,255,0.12);
                    backdrop-filter: blur(12px);
                    -webkit-backdrop-filter: blur(12px);
                    border: 2px solid rgba(255,255,255,0.2);
                    border-radius: 20px;
                    padding: 28px 20px;
                    cursor: pointer;
                    flex: 1;
                    min-width: 150px;
                    max-width: 180px;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    color: #fff;
                    font-family: inherit;
                    outline: none;
                }
                .city-card:hover, .city-card:focus {
                    background: rgba(255,255,255,0.22);
                    border-color: rgba(255,255,255,0.5);
                    transform: translateY(-6px) scale(1.03);
                    box-shadow: 0 12px 40px rgba(0,0,0,0.25);
                }
                .city-card:active {
                    transform: translateY(-2px) scale(0.98);
                }
                .city-card-icon {
                    font-size: 2.8rem;
                    margin-bottom: 12px;
                    filter: drop-shadow(0 4px 8px rgba(0,0,0,0.2));
                }
                .city-card-name {
                    font-size: 1.25rem;
                    font-weight: 700;
                    margin-bottom: 4px;
                }
                .city-card-sub {
                    font-size: 0.8rem;
                    color: rgba(255,255,255,0.65);
                }
                .city-picker-note {
                    color: rgba(255,255,255,0.55);
                    font-size: 0.75rem;
                    margin-top: 28px;
                }
                /* Confirm button that appears after selection */
                .city-confirm-wrap {
                    margin-top: 24px;
                    animation: cityConfirmSlideUp 0.3s ease-out;
                }
                @keyframes cityConfirmSlideUp {
                    from { opacity: 0; transform: translateY(20px); }
                    to   { opacity: 1; transform: translateY(0); }
                }
                .city-confirm-btn {
                    background: #fff;
                    color: #0a8754;
                    border: none;
                    border-radius: 14px;
                    padding: 14px 48px;
                    font-size: 1.1rem;
                    font-weight: 700;
                    font-family: inherit;
                    cursor: pointer;
                    box-shadow: 0 6px 24px rgba(0,0,0,0.2);
                    transition: all 0.2s ease;
                }
                .city-confirm-btn:hover {
                    transform: scale(1.05);
                    box-shadow: 0 8px 32px rgba(0,0,0,0.3);
                }
                .city-card.selected {
                    background: rgba(255,255,255,0.3);
                    border-color: #fff;
                    box-shadow: 0 0 0 3px rgba(255,255,255,0.4), 0 12px 40px rgba(0,0,0,0.25);
                    transform: translateY(-6px) scale(1.03);
                }
            `;
            document.head.appendChild(style);
            document.body.appendChild(overlay);

            let selectedCity = null;
            const cards = overlay.querySelectorAll('.city-card');
            const cardsContainer = overlay.querySelector('.city-picker-cards');

            cards.forEach(card => {
                card.addEventListener('click', () => {
                    selectedCity = card.dataset.city;
                    // Highlight selected card
                    cards.forEach(c => c.classList.remove('selected'));
                    card.classList.add('selected');

                    // Show confirm button if not already shown
                    if (!overlay.querySelector('.city-confirm-wrap')) {
                        const confirmWrap = document.createElement('div');
                        confirmWrap.className = 'city-confirm-wrap';
                        confirmWrap.innerHTML = `<button class="city-confirm-btn">تأكيد — ${CityService.CITY_LABELS[selectedCity]}</button>`;
                        cardsContainer.parentElement.insertBefore(confirmWrap, overlay.querySelector('.city-picker-note'));

                        confirmWrap.querySelector('.city-confirm-btn').addEventListener('click', () => {
                            CityService.setCity(selectedCity);
                            overlay.style.animation = 'cityPickerFadeIn 0.3s ease-out reverse';
                            setTimeout(() => {
                                overlay.remove();
                                style.remove();
                                resolve(selectedCity);
                            }, 280);
                        });
                    } else {
                        // Update button text if user switches selection
                        overlay.querySelector('.city-confirm-btn').textContent = `تأكيد — ${CityService.CITY_LABELS[selectedCity]}`;
                    }
                });
            });
        });
    },

    /**
     * Ensure a city is selected. If not, shows the picker.
     * Call this at app startup to gate the experience.
     * @returns {Promise<string>} The selected city
     */
    async ensureCity() {
        if (this.hasCity()) {
            return this.getCity();
        }
        return this.showCityPicker();
    }
};

// Expose globally
window.CityService = CityService;
