// static/admin/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 - ONE LINE!
// Create custom logger for login page
const loginLog = window.LogConfig.createLogger('LOGIN');

function languageSelector(currentLang, enabledLanguages) {
    return {
        currentLang: currentLang || 'en',
        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 adminLogin() {
    return {
        dark: false,
        credentials: {
            username: '',
            password: ''
        },
        loading: false,
        error: null,
        success: null,
        errors: {},
        rememberMe: false,
        showForgotPassword: false,
        forgotPasswordEmail: '',
        forgotPasswordLoading: false,

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

            loginLog.info('=== LOGIN PAGE INITIALIZING ===');
            loginLog.debug('Current pathname:', window.location.pathname);
            loginLog.debug('Current URL:', window.location.href);

            // Just set theme - NO auth checking, NO token clearing!
            this.dark = localStorage.getItem('theme') === 'dark';
            loginLog.debug('Dark mode:', this.dark);

            // DON'T clear tokens on init!
            // If user lands here with a valid token, they might be navigating manually
            // or got redirected. Let them try to login or navigate away.
            const token = localStorage.getItem('admin_token');
            if (token) {
                loginLog.warn('Found existing token on login page');
                loginLog.debug('Token preview:', token.substring(0, 20) + '...');
                loginLog.info('Not clearing token - user may have navigated here manually');
            } else {
                loginLog.debug('No existing token found');
            }

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

        clearTokens() {
            loginLog.debug('Clearing all auth tokens...');
            const tokensBefore = {
                admin_token: !!localStorage.getItem('admin_token'),
                admin_user: !!localStorage.getItem('admin_user'),
                token: !!localStorage.getItem('token')
            };
            loginLog.debug('Tokens before clear:', tokensBefore);

            localStorage.removeItem('admin_token');
            localStorage.removeItem('admin_user');
            localStorage.removeItem('token');

            const tokensAfter = {
                admin_token: !!localStorage.getItem('admin_token'),
                admin_user: !!localStorage.getItem('admin_user'),
                token: !!localStorage.getItem('token')
            };
            loginLog.debug('Tokens after clear:', tokensAfter);
        },

        clearErrors() {
            loginLog.debug('Clearing form errors');
            this.error = null;
            this.success = null;
            this.errors = {};
        },

        validateForm() {
            loginLog.debug('Validating login form...');
            this.clearErrors();
            let isValid = true;

            if (!this.credentials.username.trim()) {
                this.errors.username = 'Username is required';
                loginLog.warn('Validation failed: Username is required');
                isValid = false;
            }

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

            loginLog.info('Form validation result:', isValid ? 'VALID' : 'INVALID');
            return isValid;
        },

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

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

            this.loading = true;
            this.clearErrors();
            loginLog.debug('Login state set to loading');

            try {
                loginLog.info('Calling login API endpoint...');
                loginLog.debug('Username:', this.credentials.username);

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

                window.LogConfig.logApiCall('POST', url, { username: payload.username }, 'request');

                const startTime = performance.now();
                const response = await apiClient.post(url, payload);
                const duration = performance.now() - startTime;

                window.LogConfig.logApiCall('POST', url, {
                    hasToken: !!response.access_token,
                    user: response.user?.username
                }, 'response');
                window.LogConfig.logPerformance('Login', duration);

                loginLog.info(`Login API response received in ${duration}ms`);
                loginLog.debug('Response structure:', {
                    hasToken: !!response.access_token,
                    hasUser: !!response.user,
                    userRole: response.user?.role,
                    userName: response.user?.username
                });

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

                if (response.user && !['super_admin', 'platform_admin'].includes(response.user.role)) {
                    loginLog.error('Authorization failed: User is not admin', {
                        actualRole: response.user.role
                    });
                    throw new Error('Access denied. Admin privileges required.');
                }

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

                // Store authentication data
                localStorage.setItem('admin_token', response.access_token);
                localStorage.setItem('token', response.access_token);
                loginLog.debug('Token stored, length:', response.access_token.length);

                if (response.user) {
                    localStorage.setItem('admin_user', JSON.stringify(response.user));
                    loginLog.debug('User data stored:', {
                        username: response.user.username,
                        role: response.user.role,
                        id: response.user.id
                    });
                }

                // Verify storage
                const storedToken = localStorage.getItem('admin_token');
                const storedUser = localStorage.getItem('admin_user');
                loginLog.info('Storage verification:', {
                    tokenStored: !!storedToken,
                    userStored: !!storedUser,
                    tokenLength: storedToken?.length
                });

                // Show success message
                this.success = 'Login successful! Checking platform access...';
                loginLog.info('Success message displayed to user');

                // Check if platform selection is required
                try {
                    loginLog.info('Checking accessible platforms...');
                    const platformsResponse = await apiClient.get('/admin/auth/accessible-platforms');
                    loginLog.debug('Accessible platforms response:', platformsResponse);

                    if (platformsResponse.requires_platform_selection) {
                        // Platform admin needs to select a platform
                        loginLog.info('Platform selection required, redirecting...');
                        this.success = 'Login successful! Please select a platform...';
                        window.location.href = '/admin/select-platform';
                        return;
                    }

                    if (platformsResponse.is_super_admin && !platformsResponse.current_platform_id) {
                        // Super admin with no platform selected - offer platform selection
                        loginLog.info('Super admin without platform, redirecting to platform selector...');
                        this.success = 'Login successful! Select a platform or stay in global mode...';
                        window.location.href = '/admin/select-platform';
                        return;
                    }
                } catch (platformError) {
                    loginLog.warn('Could not check platforms, proceeding to dashboard:', platformError);
                }

                // Super admin or single platform - proceed to dashboard
                this.success = 'Login successful! Redirecting...';

                // Check for last visited page (saved before logout)
                const lastPage = localStorage.getItem('admin_last_visited_page');
                const redirectTo = (lastPage && lastPage.startsWith('/admin/') && !lastPage.includes('/login') && !lastPage.includes('/select-platform'))
                    ? lastPage
                    : '/admin/dashboard';

                loginLog.info('=== EXECUTING REDIRECT ===');
                loginLog.debug('Last visited page:', lastPage);
                loginLog.debug('Target URL:', redirectTo);

                // Use href instead of replace to allow back button
                window.location.href = redirectTo;

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

                this.error = error.message || 'Invalid username or password. Please try again.';
                loginLog.info('Error message displayed to user:', this.error);

                // Only clear tokens on login FAILURE
                this.clearTokens();
                loginLog.info('Tokens cleared after error');

            } finally {
                this.loading = false;
                loginLog.debug('Login state set to not loading');
                loginLog.info('=== LOGIN ATTEMPT FINISHED ===');
            }
        },

        async handleForgotPassword() {
            if (!this.forgotPasswordEmail) {
                this.error = 'Please enter your email address';
                return;
            }
            this.forgotPasswordLoading = true;
            this.clearErrors();

            try {
                const response = await apiClient.post('/admin/auth/forgot-password', {
                    email: this.forgotPasswordEmail
                });
                this.success = response.message || 'If an account exists with that email, a reset link has been sent.';
                this.forgotPasswordEmail = '';
            } catch (error) {
                // Show generic message to prevent email enumeration
                this.success = 'If an account exists with that email, a reset link has been sent.';
            } finally {
                this.forgotPasswordLoading = false;
            }
        },

        toggleDarkMode() {
            loginLog.debug('Toggling dark mode...');
            this.dark = !this.dark;
            localStorage.setItem('theme', this.dark ? 'dark' : 'light');
            loginLog.info('Dark mode:', this.dark ? 'ON' : 'OFF');
        }
    }
}

loginLog.info('Login module loaded');
