// app/modules/loyalty/static/storefront/js/loyalty-history.js
// Customer loyalty transaction history
const loyaltyHistoryLog = window.LogConfig.loggers.loyaltyHistory || window.LogConfig.createLogger('loyaltyHistory');

function customerLoyaltyHistory() {
    return {
        ...storefrontLayoutData(),

        // Data
        card: null,
        transactions: [],

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

        // State
        loading: false,

        async init() {
            loyaltyHistoryLog.info('Customer loyalty history initializing...');
            await this.loadData();
        },

        async loadData() {
            this.loading = true;
            try {
                await Promise.all([
                    this.loadCard(),
                    this.loadTransactions()
                ]);
            } catch (error) {
                loyaltyHistoryLog.error('Failed to load history:', error);
            } finally {
                this.loading = false;
            }
        },

        async loadCard() {
            try {
                const response = await apiClient.get('/storefront/loyalty/card');
                if (response) {
                    this.card = response.card;
                }
            } catch (error) {
                loyaltyHistoryLog.warn('Failed to load card:', error.message);
            }
        },

        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);

                const response = await apiClient.get(`/storefront/loyalty/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);
                    loyaltyHistoryLog.info(`Loaded ${this.transactions.length} transactions`);
                }
            } catch (error) {
                loyaltyHistoryLog.error('Failed to load transactions:', error);
            }
        },

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

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

        getTransactionLabel(tx) {
            const type = tx.transaction_type || '';
            if (type) {
                return I18n.t('loyalty.transactions.' + type, {defaultValue: type.replace(/_/g, ' ')});
            }
            return type;
        },

        formatNumber(num) {
            if (num == null) return '0';
            return new Intl.NumberFormat('en-US').format(num);
        },

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