// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/merchant-user-detail.js

// Create custom logger for merchant user detail
const merchantUserDetailLog = window.LogConfig.createLogger('MERCHANT-USER-DETAIL');

function merchantUserDetailPage() {
    return {
        // Inherit base layout functionality from init-alpine.js
        ...data(),

        // Merchant user detail page specific state
        currentPage: 'merchant-users',
        merchantUser: null,
        loading: false,
        saving: false,
        error: null,
        userId: null,
        showToggleStatusModal: false,
        showDeleteModal: false,
        showDeleteFinalModal: false,

        // Initialize
        async init() {
            // Load i18n translations
            await I18n.loadModule('tenancy');

            merchantUserDetailLog.info('=== MERCHANT USER DETAIL PAGE INITIALIZING ===');

            // Prevent multiple initializations
            if (window._merchantUserDetailInitialized) {
                merchantUserDetailLog.warn('Merchant user detail page already initialized, skipping...');
                return;
            }
            window._merchantUserDetailInitialized = true;

            // Get user ID from URL
            const path = window.location.pathname;
            const match = path.match(/\/admin\/merchant-users\/(\d+)$/);

            if (match) {
                this.userId = match[1];
                merchantUserDetailLog.info('Viewing merchant user:', this.userId);
                await this.loadMerchantUser();
            } else {
                merchantUserDetailLog.error('No user ID in URL');
                this.error = 'Invalid merchant user URL';
                Utils.showToast('Invalid merchant user URL', 'error');
            }

            merchantUserDetailLog.info('=== MERCHANT USER DETAIL PAGE INITIALIZATION COMPLETE ===');
        },

        // Load merchant user data
        async loadMerchantUser() {
            merchantUserDetailLog.info('Loading merchant user details...');
            this.loading = true;
            this.error = null;

            try {
                const url = `/admin/users/${this.userId}`;
                window.LogConfig.logApiCall('GET', url, null, 'request');

                const startTime = performance.now();
                const response = await apiClient.get(url);
                const duration = performance.now() - startTime;

                window.LogConfig.logApiCall('GET', url, response, 'response');
                window.LogConfig.logPerformance('Load Merchant User Details', duration);

                // Transform API response
                this.merchantUser = {
                    ...response,
                    full_name: [response.first_name, response.last_name].filter(Boolean).join(' ') || null
                };

                merchantUserDetailLog.info(`Merchant user loaded in ${duration}ms`, {
                    id: this.merchantUser.id,
                    username: this.merchantUser.username,
                    owned_merchants_count: this.merchantUser.owned_merchants_count,
                    store_memberships_count: this.merchantUser.store_memberships_count
                });

            } catch (error) {
                window.LogConfig.logError(error, 'Load Merchant User Details');
                this.error = error.message || 'Failed to load merchant user details';
                Utils.showToast('Failed to load merchant user details', 'error');
            } finally {
                this.loading = false;
            }
        },

        // Format date
        formatDate(dateString) {
            if (!dateString) {
                return '-';
            }
            return Utils.formatDate(dateString);
        },

        // Toggle user status
        async toggleStatus() {
            const action = this.merchantUser.is_active ? 'deactivate' : 'activate';
            merchantUserDetailLog.info(`Toggle status: ${action}`);

            this.saving = true;
            try {
                const url = `/admin/users/${this.userId}/status`;
                window.LogConfig.logApiCall('PUT', url, null, 'request');

                const response = await apiClient.put(url);

                window.LogConfig.logApiCall('PUT', url, response, 'response');

                this.merchantUser.is_active = response.is_active;
                Utils.showToast(`User ${action}d successfully`, 'success');
                merchantUserDetailLog.info(`User ${action}d successfully`);

            } catch (error) {
                window.LogConfig.logError(error, `Toggle Status (${action})`);
                Utils.showToast(error.message || `Failed to ${action} user`, 'error');
            } finally {
                this.saving = false;
            }
        },

        // Intermediate step for double-confirm delete
        confirmDeleteStep() {
            merchantUserDetailLog.info('First delete confirmation accepted, showing final confirmation');
            this.showDeleteFinalModal = true;
        },

        // Delete user
        async deleteUser() {
            merchantUserDetailLog.info('Delete user requested:', this.userId);

            this.saving = true;
            try {
                const url = `/admin/users/${this.userId}`;
                window.LogConfig.logApiCall('DELETE', url, null, 'request');

                await apiClient.delete(url);

                window.LogConfig.logApiCall('DELETE', url, null, 'response');

                Utils.showToast('User deleted successfully', 'success');
                merchantUserDetailLog.info('User deleted successfully');

                // Redirect to merchant users list
                setTimeout(() => window.location.href = '/admin/merchant-users', 1500);

            } catch (error) {
                window.LogConfig.logError(error, 'Delete User');
                Utils.showToast(error.message || 'Failed to delete user', 'error');
            } finally {
                this.saving = false;
            }
        },

        // Refresh user data
        async refresh() {
            merchantUserDetailLog.info('=== MERCHANT USER REFRESH TRIGGERED ===');
            await this.loadMerchantUser();
            Utils.showToast('Merchant user details refreshed', 'success');
            merchantUserDetailLog.info('=== MERCHANT USER REFRESH COMPLETE ===');
        }
    };
}

merchantUserDetailLog.info('Merchant user detail module loaded');
