// app/modules/core/static/merchant/js/login.js
// noqa: js-003 - Standalone login page, doesn't use base layout
// noqa: js-004 - No sidebar on login page, doesn't need currentPage

// Use centralized logger
const loginLog = window.LogConfig.createLogger('MERCHANT-LOGIN');

function languageSelector(currentLang, enabledLanguages) {
    return {
        currentLang: currentLang || 'fr',
        languages: enabledLanguages || ['en', 'fr', 'de', 'lb'],
        async setLanguage(lang) {
            if (lang === this.currentLang) return;
            try {
                // noqa: JS-008 - Login page has no apiClient; raw fetch is intentional
                await fetch('/api/v1/platform/language/set', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ language: lang }),
                });
                window.location.reload();
            } catch (error) {
                loginLog.error('Failed to set language:', error);
            }
        },
    };
}

function merchantLogin() {
    return {
        dark: false,
        credentials: {
            email: '',
            password: ''
        },
        loading: false,
        error: null,
        success: null,
        errors: {},

        init() {
            // Guard against multiple initialization
            if (window._merchantLoginInitialized) return;
            window._merchantLoginInitialized = true;

            loginLog.info('=== MERCHANT LOGIN PAGE INITIALIZING ===');

            // Just set theme - NO auth checking, NO redirecting!
            // If user lands here with a valid token, the server-side route
            // already handles the redirect. Don't redirect from JS or it
            // creates an infinite loop with expired tokens.
            this.dark = localStorage.getItem('theme') === 'dark';

            const token = localStorage.getItem('merchant_token');
            if (token) {
                loginLog.warn('Found existing token on login page');
                loginLog.info('Not redirecting - server handles auth redirect, clearing stale token');
                localStorage.removeItem('merchant_token');
            }

            loginLog.info('=== MERCHANT LOGIN PAGE INITIALIZATION COMPLETE ===');
        },

        clearTokens() {
            loginLog.debug('Clearing merchant auth tokens...');
            localStorage.removeItem('merchant_token');
        },

        clearErrors() {
            this.error = null;
            this.success = null;
            this.errors = {};
        },

        validateForm() {
            this.clearErrors();
            let isValid = true;

            if (!this.credentials.email.trim()) {
                this.errors.email = 'Email is required';
                isValid = false;
            }

            if (!this.credentials.password) {
                this.errors.password = 'Password is required';
                isValid = false;
            } else if (this.credentials.password.length < 6) {
                this.errors.password = 'Password must be at least 6 characters';
                isValid = false;
            }

            return isValid;
        },

        async handleLogin() {
            loginLog.info('=== MERCHANT LOGIN ATTEMPT STARTED ===');

            if (!this.validateForm()) {
                loginLog.warn('Form validation failed, aborting login');
                return;
            }

            this.loading = true;
            this.clearErrors();

            try {
                loginLog.info('Calling merchant login API endpoint...');

                const url = '/merchants/auth/login';
                const payload = {
                    email_or_username: this.credentials.email.trim(),
                    password: this.credentials.password
                };

                const response = await apiClient.post(url, payload);

                loginLog.info('Login API response received');

                // Validate response
                if (!response.access_token && !response.token) {
                    loginLog.error('Invalid response: No access token');
                    throw new Error('Invalid response from server - no token');
                }

                loginLog.info('Login successful, storing authentication data...');

                // Store authentication data
                const token = response.access_token || response.token;
                localStorage.setItem('merchant_token', token);

                // Show success message
                this.success = 'Login successful! Redirecting...';

                // Check for last visited page
                const lastPage = localStorage.getItem('merchant_last_visited_page');
                const redirectTo = (lastPage && lastPage.startsWith('/merchants/') && !lastPage.includes('/login'))
                    ? lastPage
                    : '/merchants/dashboard';

                loginLog.info('Redirecting to:', redirectTo);
                window.location.href = redirectTo;

            } catch (error) {
                window.LogConfig.logError(error, 'MerchantLogin');

                this.error = error.message || 'Invalid email or password. Please try again.';

                // Only clear tokens on login FAILURE
                this.clearTokens();

            } finally {
                this.loading = false;
                loginLog.info('=== MERCHANT LOGIN ATTEMPT FINISHED ===');
            }
        },

        // Forgot password state
        rememberMe: false,
        showForgotPassword: false,
        forgotPasswordEmail: '',
        forgotPasswordLoading: false,

        async handleForgotPassword() {
            loginLog.info('=== FORGOT PASSWORD ATTEMPT ===');
            if (!this.forgotPasswordEmail.trim()) {
                this.error = 'Email is required';
                return;
            }

            this.forgotPasswordLoading = true;
            this.clearErrors();

            try {
                await apiClient.post('/merchants/auth/forgot-password', {
                    email: this.forgotPasswordEmail.trim()
                });
                this.success = 'If an account exists with this email, a password reset link has been sent.';
                this.forgotPasswordEmail = '';
            } catch (error) {
                window.LogConfig.logError(error, 'ForgotPassword');
                this.error = error.message || 'Failed to send reset email. Please try again.';
            } finally {
                this.forgotPasswordLoading = false;
            }
        },

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

loginLog.info('Merchant login module loaded');
