// app/modules/loyalty/static/shared/js/loyalty-transactions-list.js
// Shared Alpine.js data factory for loyalty transactions listing pages.
// Used by store, merchant, and admin frontends.

const loyaltyTransactionsListLog = window.LogConfig.loggers.loyaltyTransactionsList || window.LogConfig.createLogger('loyaltyTransactionsList');

/**
 * Factory that returns an Alpine.js data object for loyalty transaction listing.
 *
 * @param {Object} config
 * @param {string}  config.apiPrefix       - API path prefix, e.g. '/store/loyalty'
 * @param {boolean} config.showStoreFilter - Whether to show the store/location dropdown filter
 * @param {string}  config.currentPage     - Alpine currentPage identifier
 */
function loyaltyTransactionsList(config) {
    const guardKey = '_loyaltyTransactionsList_' + config.currentPage + '_initialized';

    return {
        ...data(),
        currentPage: config.currentPage,

        // Data
        transactions: [],
        locations: [],

        // Filters
        filters: {
            search: '',
            type: '',
            store_id: ''
        },

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

        // State
        loading: false,
        error: null,

        // Config (exposed for templates)
        _config: config,

        async init() {
            loyaltyTransactionsListLog.info('=== LOYALTY TRANSACTIONS LIST INITIALIZING ===', config.currentPage);
            if (window[guardKey]) return;
            window[guardKey] = true;

            const parentInit = data().init;
            if (parentInit) {
                await parentInit.call(this);
            }

            if (window.PlatformSettings) {
                try {
                    this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
                } catch (error) {
                    loyaltyTransactionsListLog.warn('Failed to get rows per page setting:', error.message);
                }
            }

            await this.loadData();
            loyaltyTransactionsListLog.info('=== LOYALTY TRANSACTIONS LIST INITIALIZATION COMPLETE ===');
        },

        async loadData() {
            this.loading = true;
            this.error = null;
            try {
                const parallel = [this.loadTransactions()];
                if (config.showStoreFilter) {
                    parallel.push(this.loadLocations());
                }
                await Promise.all(parallel);
            } catch (error) {
                loyaltyTransactionsListLog.error('Failed to load data:', error);
                this.error = error.message;
            } finally {
                this.loading = false;
            }
        },

        async loadTransactions() {
            try {
                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.type) params.append('type', this.filters.type);
                if (this.filters.store_id) params.append('store_id', this.filters.store_id);

                const response = await apiClient.get(config.apiPrefix + '/transactions?' + params);
                if (response) {
                    this.transactions = response.transactions || [];
                    this.pagination.total = response.total || 0;
                    this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
                }
            } catch (error) {
                loyaltyTransactionsListLog.error('Failed to load transactions:', error);
                throw error;
            }
        },

        async loadLocations() {
            try {
                const response = await apiClient.get(config.apiPrefix + '/locations');
                if (response) {
                    this.locations = Array.isArray(response) ? response : (response.locations || []);
                }
            } catch (error) {
                loyaltyTransactionsListLog.warn('Failed to load locations:', error.message);
            }
        },

        debouncedSearch() {
            if (this._searchTimeout) clearTimeout(this._searchTimeout);
            this._searchTimeout = setTimeout(() => {
                this.pagination.page = 1;
                this.loadTransactions();
            }, 300);
        },

        applyFilter() {
            this.pagination.page = 1;
            this.loadTransactions();
        },

        // Pagination helpers
        get totalPages() {
            return this.pagination.pages;
        },

        get startIndex() {
            return this.pagination.total === 0
                ? 0
                : (this.pagination.page - 1) * this.pagination.per_page + 1;
        },

        get endIndex() {
            const end = this.pagination.page * this.pagination.per_page;
            return end > this.pagination.total ? this.pagination.total : end;
        },

        get pageNumbers() {
            const pages = [];
            const total = this.totalPages;
            const current = this.pagination.page;

            if (total <= 7) {
                for (let i = 1; i <= total; i++) pages.push(i);
            } else {
                pages.push(1);
                if (current > 3) pages.push('...');
                const start = Math.max(2, current - 1);
                const end = Math.min(total - 1, current + 1);
                for (let i = start; i <= end; i++) pages.push(i);
                if (current < total - 2) pages.push('...');
                pages.push(total);
            }
            return pages;
        },

        previousPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadTransactions();
            }
        },

        nextPage() {
            if (this.pagination.page < this.totalPages) {
                this.pagination.page++;
                this.loadTransactions();
            }
        },

        goToPage(num) {
            if (num !== '...' && num >= 1 && num <= this.totalPages) {
                this.pagination.page = num;
                this.loadTransactions();
            }
        },

        /**
         * Returns Tailwind CSS classes for a transaction type badge.
         * @param {string} type - Transaction type (e.g. 'earn', 'redeem', 'bonus', 'adjustment', 'expire')
         * @returns {string} CSS class string
         */
        getTransactionBadgeClass(type) {
            switch (type) {
                case 'earn':
                    return 'bg-green-100 text-green-800';
                case 'redeem':
                    return 'bg-blue-100 text-blue-800';
                case 'bonus':
                    return 'bg-purple-100 text-purple-800';
                case 'adjustment':
                    return 'bg-yellow-100 text-yellow-800';
                case 'expire':
                    return 'bg-red-100 text-red-800';
                default:
                    return 'bg-gray-100 text-gray-800';
            }
        },

        // Formatting helpers
        formatNumber(num) {
            return num == null ? '0' : new Intl.NumberFormat('en-US').format(num);
        },

        formatDate(dateString) {
            if (!dateString) return 'Never';
            try {
                return new Date(dateString).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                });
            } catch (e) {
                return dateString;
            }
        },

        formatDateTime(dateString) {
            if (!dateString) return 'Never';
            try {
                return new Date(dateString).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (e) {
                return dateString;
            }
        }
    };
}

if (!window.LogConfig.loggers.loyaltyTransactionsList) {
    window.LogConfig.loggers.loyaltyTransactionsList = window.LogConfig.createLogger('loyaltyTransactionsList');
}
loyaltyTransactionsListLog.info('Loyalty transactions list shared module loaded');
