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

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

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

// Sidebar section state persistence
const MERCHANT_SIDEBAR_STORAGE_KEY = 'merchant_sidebar_sections';

function getMerchantSidebarSectionsFromStorage() {
    try {
        const stored = localStorage.getItem(MERCHANT_SIDEBAR_STORAGE_KEY);
        if (stored) {
            return JSON.parse(stored);
        }
    } catch (e) {
        console.warn('[MERCHANT INIT-ALPINE] Failed to load sidebar state from localStorage:', e);
    }
    // Default: empty — dynamic menu will initialize section state
    return {};
}

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

// Helper to find section ID for a page from menu data
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 data() {
    console.log('[MERCHANT INIT-ALPINE] data() function called');
    return {
        dark: false,
        isSideMenuOpen: false,
        isProfileMenuOpen: false,
        currentPage: '',
        merchantName: '',

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

        // Dynamic menu (loaded from API)
        menuData: null,
        menuLoading: false,

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

            // Load merchant name from JWT token
            const token = localStorage.getItem('merchant_token');
            if (token) {
                try {
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    this.merchantName = payload.merchant_name || payload.sub || 'Merchant';
                } catch (e) {
                    this.merchantName = 'Merchant';
                }
            }

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

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

            // Load dynamic menu
            this.loadMenuConfig();
        },

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

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

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

        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];
            saveMerchantSidebarSectionsToStorage(this.openSections);
        },

        // Auto-expand section containing current page
        expandSectionForCurrentPage() {
            if (!this.menuData) return;
            const section = findSectionForPage(this.menuData, this.currentPage);
            if (section && !this.openSections[section]) {
                this.openSections[section] = true;
                saveMerchantSidebarSectionsToStorage(this.openSections);
            }
        },

        // Dynamic menu loading from API
        async loadMenuConfig() {
            if (this.menuData || this.menuLoading) return;

            // Skip if apiClient is not available (e.g., on login page)
            if (typeof apiClient === 'undefined') {
                console.debug('Menu config: apiClient not available');
                return;
            }

            // Skip if not authenticated
            if (!localStorage.getItem('merchant_token')) {
                console.debug('Menu config: no merchant_token, skipping');
                return;
            }

            this.menuLoading = true;
            try {
                this.menuData = await apiClient.get('/merchants/core/menu/render/merchant');
                const sections = this.menuData?.sections || [];
                for (const section of sections) {
                    // Initialize openSections for new sections (default: open)
                    if (this.openSections[section.id] === undefined) {
                        this.openSections[section.id] = true;
                    }
                }
                saveMerchantSidebarSectionsToStorage(this.openSections);
                console.debug('Menu config loaded:', sections.length, 'sections');

                // Auto-expand section containing current page
                this.expandSectionForCurrentPage();
            } catch (e) {
                console.debug('Menu config not loaded, using fallback:', e?.message || e);
            } finally {
                this.menuLoading = false;
            }
        },

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

            try {
                // Call logout API
                await apiClient.post('/merchants/auth/logout');
                console.log('Logout API called successfully');
            } catch (error) {
                console.error('Logout API error (continuing anyway):', error);
            } finally {
                // Clear merchant tokens only
                console.log('Clearing merchant tokens...');
                localStorage.removeItem('merchant_token');

                console.log('Redirecting to login...');
                window.location.href = '/merchants/login';
            }
        }
    };
}

/**
 * Language Selector Component
 * Alpine.js component for language switching in merchant portal
 */
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;
