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

// ✅ Use centralized logger
const merchantsLog = window.LogConfig.loggers.merchants || window.LogConfig.createLogger('merchants');

// ============================================
// MERCHANT LIST FUNCTION
// ============================================
function adminMerchants() {
    return {
        // Inherit base layout functionality
        ...data(),

        // Page identifier for sidebar active state
        currentPage: 'merchants',

        // Merchants page specific state
        merchants: [],
        stats: {
            total: 0,
            verified: 0,
            active: 0,
            totalStores: 0
        },
        loading: false,
        error: null,

        // Modal state
        showDeleteMerchantModal: false,
        merchantToDelete: null,

        // Search and filters
        filters: {
            search: '',
            is_active: '',
            is_verified: ''
        },

        // Pagination state
        pagination: {
            page: 1,
            per_page: 20,
            total: 0,
            pages: 0
        },

        // Initialize
        async init() {
            merchantsLog.info('=== COMPANIES PAGE INITIALIZING ===');

            // Prevent multiple initializations
            if (window._merchantsInitialized) {
                merchantsLog.warn('Merchants page already initialized, skipping...');
                return;
            }
            window._merchantsInitialized = true;

            // Load platform settings for rows per page
            if (window.PlatformSettings) {
                this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
            }

            merchantsLog.group('Loading merchants data');
            await this.loadMerchants();
            merchantsLog.groupEnd();

            merchantsLog.info('=== COMPANIES PAGE INITIALIZATION COMPLETE ===');
        },

        // Debounced search
        debouncedSearch() {
            if (this._searchTimeout) {
                clearTimeout(this._searchTimeout);
            }
            this._searchTimeout = setTimeout(() => {
                merchantsLog.info('Search triggered:', this.filters.search);
                this.pagination.page = 1;
                this.loadMerchants();
            }, 300);
        },

        // Computed: Get merchants for current page (already paginated from server)
        get paginatedMerchants() {
            return this.merchants;
        },

        // Computed: Total number of pages
        get totalPages() {
            return this.pagination.pages;
        },

        // Computed: Start index for pagination display
        get startIndex() {
            if (this.pagination.total === 0) return 0;
            return (this.pagination.page - 1) * this.pagination.per_page + 1;
        },

        // Computed: End index for pagination display
        get endIndex() {
            const end = this.pagination.page * this.pagination.per_page;
            return end > this.pagination.total ? this.pagination.total : end;
        },

        // Computed: Generate page numbers array with ellipsis
        get pageNumbers() {
            const pages = [];
            const totalPages = this.totalPages;
            const current = this.pagination.page;

            if (totalPages <= 7) {
                // Show all pages if 7 or fewer
                for (let i = 1; i <= totalPages; i++) {
                    pages.push(i);
                }
            } else {
                // Always show first page
                pages.push(1);

                if (current > 3) {
                    pages.push('...');
                }

                // Show pages around current page
                const start = Math.max(2, current - 1);
                const end = Math.min(totalPages - 1, current + 1);

                for (let i = start; i <= end; i++) {
                    pages.push(i);
                }

                if (current < totalPages - 2) {
                    pages.push('...');
                }

                // Always show last page
                pages.push(totalPages);
            }

            return pages;
        },

        // Load merchants with search and pagination
        async loadMerchants() {
            this.loading = true;
            this.error = null;

            try {
                merchantsLog.info('Fetching merchants from API...');

                const params = new URLSearchParams();
                params.append('skip', (this.pagination.page - 1) * this.pagination.per_page);
                params.append('limit', this.pagination.per_page);

                if (this.filters.search) {
                    params.append('search', this.filters.search);
                }
                if (this.filters.is_active) {
                    params.append('is_active', this.filters.is_active);
                }
                if (this.filters.is_verified) {
                    params.append('is_verified', this.filters.is_verified);
                }

                const response = await apiClient.get(`/admin/merchants?${params}`);

                if (response.merchants) {
                    this.merchants = response.merchants;
                    this.pagination.total = response.total;
                    this.pagination.pages = Math.ceil(response.total / this.pagination.per_page);

                    // Calculate stats from all merchants (need separate call for accurate stats)
                    this.stats.total = response.total;
                    this.stats.verified = this.merchants.filter(c => c.is_verified).length;
                    this.stats.active = this.merchants.filter(c => c.is_active).length;
                    this.stats.totalStores = this.merchants.reduce((sum, c) => sum + (c.store_count || 0), 0);

                    merchantsLog.info(`Loaded ${this.merchants.length} merchants (total: ${response.total})`);
                } else {
                    merchantsLog.warn('No merchants in response');
                    this.merchants = [];
                }
            } catch (error) {
                merchantsLog.error('Failed to load merchants:', error);
                this.error = error.message || 'Failed to load merchants';
                this.merchants = [];
            } finally {
                this.loading = false;
            }
        },

        // Edit merchant
        editMerchant(merchantId) {
            merchantsLog.info('Edit merchant:', merchantId);
            // TODO: Navigate to edit page
            window.location.href = `/admin/merchants/${merchantId}/edit`;
        },

        // Prompt delete merchant modal
        promptDeleteMerchant(merchant) {
            if (merchant.store_count > 0) {
                merchantsLog.warn('Cannot delete merchant with stores');
                Utils.showToast(`Cannot delete "${merchant.name}" because it has ${merchant.store_count} store(s). Please delete or reassign the stores first.`, 'warning');
                return;
            }
            this.merchantToDelete = merchant;
            this.showDeleteMerchantModal = true;
        },

        // Delete merchant
        async deleteMerchant(merchant) {
            try {
                merchantsLog.info('Deleting merchant:', merchant.id);

                await apiClient.delete(`/admin/merchants/${merchant.id}?confirm=true`);

                merchantsLog.info('Merchant deleted successfully');

                // Reload merchants
                await this.loadMerchants();
                await this.loadStats();

                Utils.showToast(`Merchant "${merchant.name}" deleted successfully`, 'success');
            } catch (error) {
                merchantsLog.error('Failed to delete merchant:', error);
                Utils.showToast(`Failed to delete merchant: ${error.message}`, 'error');
            }
        },

        // Pagination methods
        previousPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                merchantsLog.info('Previous page:', this.pagination.page);
                this.loadMerchants();
            }
        },

        nextPage() {
            if (this.pagination.page < this.totalPages) {
                this.pagination.page++;
                merchantsLog.info('Next page:', this.pagination.page);
                this.loadMerchants();
            }
        },

        goToPage(pageNum) {
            if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
                this.pagination.page = pageNum;
                merchantsLog.info('Go to page:', this.pagination.page);
                this.loadMerchants();
            }
        },

        // Format date for display
        formatDate(dateString) {
            if (!dateString) return 'N/A';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                });
            } catch (e) {
                merchantsLog.error('Date parsing error:', e);
                return dateString;
            }
        }
    };
}

// Register logger for configuration
if (!window.LogConfig.loggers.merchants) {
    window.LogConfig.loggers.merchants = window.LogConfig.createLogger('merchants');
}

merchantsLog.info('✅ Merchants module loaded');
