// app/static/store/js/init-alpine.js
/**
 * Alpine.js initialization for store pages
 * Provides common data and methods for all store pages
 */

// Use centralized logger (guarded: log-config.js loads with defer, so it may not be ready yet)
const storeLog = (window.LogConfig && window.LogConfig.log) || console;

console.log('[STORE INIT-ALPINE] Loading...');

// Sidebar section state persistence
const STORE_SIDEBAR_STORAGE_KEY = 'store_sidebar_sections';

function getStoreSidebarSectionsFromStorage() {
    try {
        const stored = localStorage.getItem(STORE_SIDEBAR_STORAGE_KEY);
        if (stored) {
            return JSON.parse(stored);
        }
    } catch (e) {
        console.warn('[STORE INIT-ALPINE] Failed to load sidebar state from localStorage:', e);
    }
    // Default: empty (populated dynamically from API response)
    return {};
}

function findSectionForPage(menuData, pageId) {
    if (!menuData?.sections) return null;
    for (const section of menuData.sections) {
        for (const item of (section.items || [])) {
            if (item.id === pageId) {
                return section.id;
            }
        }
    }
    return null;
}

function saveStoreSidebarSectionsToStorage(sections) {
    try {
        localStorage.setItem(STORE_SIDEBAR_STORAGE_KEY, JSON.stringify(sections));
    } catch (e) {
        console.warn('[STORE INIT-ALPINE] Failed to save sidebar state to localStorage:', e);
    }
}

function data() {
    console.log('[STORE INIT-ALPINE] data() function called');
    return {
        dark: false,
        isSideMenuOpen: false,
        isNotificationsMenuOpen: false,
        isProfileMenuOpen: false,
        currentPage: '',
        currentUser: {},
        store: null,
        storeCode: null,

        // Dynamic menu state
        menuData: null,
        menuLoading: false,

        // Sidebar collapsible sections state
        openSections: getStoreSidebarSectionsFromStorage(),

        init() {
            // Set current page from URL
            const path = window.location.pathname;
            const segments = path.split('/').filter(Boolean);
            // For /store/ABC/orders/123 -> 'orders' (skip numeric IDs)
            const last = segments[segments.length - 1] || 'dashboard';
            this.currentPage = /^\d+$/.test(last) && segments.length > 2
                ? segments[segments.length - 2]
                : last;

            // Get store code from server-rendered value or URL fallback
            this.storeCode = window.STORE_CODE || null;
            if (!this.storeCode && segments[0] === 'store' && segments[1]) {
                this.storeCode = segments[1];
            }

            // Load user from localStorage
            const user = localStorage.getItem('currentUser');
            if (user) {
                this.currentUser = JSON.parse(user);
            }

            // Load theme preference
            const theme = localStorage.getItem('theme');
            if (theme === 'dark') {
                this.dark = true;
            }

            // Load store info and dynamic menu
            this.loadStoreInfo();
            this.loadMenuConfig();

            // Save last visited page (for redirect after login)
            // Exclude login, logout, onboarding, error pages
            if (!path.includes('/login') &&
                !path.includes('/logout') &&
                !path.includes('/onboarding') &&
                !path.includes('/errors/')) {
                try {
                    localStorage.setItem('store_last_visited_page', path);
                } catch (e) {
                    // Ignore storage errors
                }
            }
        },

        async loadStoreInfo() {
            if (!this.storeCode) return;

            try {
                // apiClient prepends /api/v1, so /store/info/{code} → /api/v1/store/info/{code}
                const response = await apiClient.get(`/store/info/${this.storeCode}`);
                this.store = response;
                storeLog.debug('Store info loaded', this.store);
            } catch (error) {
                storeLog.error('Failed to load store info', error);
            }
        },

        async loadMenuConfig() {
            if (this.menuData || this.menuLoading) return;
            if (typeof apiClient === 'undefined') return;
            if (!localStorage.getItem('store_token')) return;

            this.menuLoading = true;
            try {
                this.menuData = await apiClient.get('/store/menu/render/store');
                // Initialize section open state from response
                for (const section of (this.menuData?.sections || [])) {
                    if (this.openSections[section.id] === undefined) {
                        this.openSections[section.id] = true;
                    }
                }
                saveStoreSidebarSectionsToStorage(this.openSections);
                this.expandSectionForCurrentPage();
            } catch (e) {
                console.debug('Menu config not loaded, using fallback:', e?.message || e);
            } finally {
                this.menuLoading = false;
            }
        },

        expandSectionForCurrentPage() {
            if (!this.menuData) return;
            const sectionId = findSectionForPage(this.menuData, this.currentPage);
            if (sectionId && !this.openSections[sectionId]) {
                this.openSections[sectionId] = true;
                saveStoreSidebarSectionsToStorage(this.openSections);
            }
        },

        toggleSideMenu() {
            this.isSideMenuOpen = !this.isSideMenuOpen;
        },

        closeSideMenu() {
            this.isSideMenuOpen = false;
        },

        toggleNotificationsMenu() {
            this.isNotificationsMenuOpen = !this.isNotificationsMenuOpen;
            if (this.isNotificationsMenuOpen) {
                this.isProfileMenuOpen = false;
            }
        },

        closeNotificationsMenu() {
            this.isNotificationsMenuOpen = false;
        },

        toggleProfileMenu() {
            this.isProfileMenuOpen = !this.isProfileMenuOpen;
            if (this.isProfileMenuOpen) {
                this.isNotificationsMenuOpen = false;
            }
        },

        closeProfileMenu() {
            this.isProfileMenuOpen = false;
        },

        toggleTheme() {
            this.dark = !this.dark;
            localStorage.setItem('theme', this.dark ? 'dark' : 'light');
        },

        // Sidebar section toggle with persistence
        toggleSection(section) {
            this.openSections[section] = !this.openSections[section];
            saveStoreSidebarSectionsToStorage(this.openSections);
        },

        async handleLogout() {
            console.log('🚪 Logging out store user...');

            try {
                // Call logout API
                await apiClient.post('/store/auth/logout');
                console.log('✅ Logout API called successfully');
            } catch (error) {
                console.error('⚠️ Logout API error (continuing anyway):', error);
            } finally {
                // Clear store tokens only (not admin or customer tokens)
                // Keep store_last_visited_page so user returns to same page after login
                console.log('🧹 Clearing store tokens...');
                localStorage.removeItem('store_token');
                localStorage.removeItem('store_user');
                localStorage.removeItem('currentUser');
                localStorage.removeItem('storeCode');
                // Note: Do NOT use localStorage.clear() - it would clear admin/customer tokens too

                console.log('🔄 Redirecting to login...');
                window.location.href = `/store/${this.storeCode}/login`;
            }
        }
    };
}

/**
 * Language Selector Component
 * Alpine.js component for language switching in store dashboard
 */
function languageSelector(currentLang, enabledLanguages) {
    return {
        isLangOpen: false,
        currentLang: currentLang || 'fr',
        languages: enabledLanguages || ['en', 'fr', 'de', 'lb'],
        languageNames: {
            'en': 'English',
            'fr': 'Français',
            'de': 'Deutsch',
            'lb': 'Lëtzebuergesch'
        },
        languageFlags: {
            'en': 'gb',
            'fr': 'fr',
            'de': 'de',
            'lb': 'lu'
        },
        async setLanguage(lang) {
            if (lang === this.currentLang) {
                this.isLangOpen = false;
                return;
            }
            try {
                const response = await fetch('/api/v1/platform/language/set', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ language: lang })
                });
                if (response.ok) {
                    this.currentLang = lang;
                    window.location.reload();
                }
            } catch (error) {
                console.error('Failed to set language:', error);
            }
            this.isLangOpen = false;
        }
    };
}

window.languageSelector = languageSelector;

/**
 * Email Settings Warning Component
 * Shows warning banner when store email settings are not configured
 *
 * Usage in template:
 * <div x-data="emailSettingsWarning()" x-show="showWarning">...</div>
 */
function emailSettingsWarning() {
    return {
        showWarning: false,
        loading: true,
        storeCode: null,

        async init() {
            // Get store code from server-rendered value or URL fallback
            this.storeCode = window.STORE_CODE || null;
            if (!this.storeCode) {
                const path = window.location.pathname;
                const segments = path.split('/').filter(Boolean);
                if (segments[0] === 'store' && segments[1]) {
                    this.storeCode = segments[1];
                }
            }

            // Skip if we're on the settings page (to avoid showing banner on config page)
            const path = window.location.pathname;
            if (path.includes('/settings')) {
                this.loading = false;
                return;
            }

            // Check email settings status
            await this.checkEmailStatus();
        },

        async checkEmailStatus() {
            try {
                const response = await apiClient.get('/store/email-settings/status');
                // Show warning if not configured
                this.showWarning = !response.is_configured;
            } catch (error) {
                // Don't show warning on error (might be 401, etc.)
                console.debug('[EmailWarning] Failed to check email status:', error);
                this.showWarning = false;
            } finally {
                this.loading = false;
            }
        }
    };
}

window.emailSettingsWarning = emailSettingsWarning;
