// app/modules/catalog/static/admin/js/product-detail.js
/**
 * Admin store product detail page logic
 * View and manage individual store catalog products
 */

const adminStoreProductDetailLog = window.LogConfig.loggers.adminStoreProductDetail ||
    window.LogConfig.createLogger('adminStoreProductDetail', false);

adminStoreProductDetailLog.info('Loading...');

function adminStoreProductDetail() {
    adminStoreProductDetailLog.info('adminStoreProductDetail() called');

    // Extract product ID from URL
    const pathParts = window.location.pathname.split('/');
    const productId = parseInt(pathParts[pathParts.length - 1]);

    return {
        // Inherit base layout state
        ...data(),

        // Set page identifier
        currentPage: 'store-products',

        // Product ID from URL
        productId: productId,

        // Loading states
        loading: true,
        error: '',

        // Product data
        product: null,

        // Modals
        showRemoveModal: false,
        removing: false,

        async init() {
            adminStoreProductDetailLog.info('Store Product Detail init() called, ID:', this.productId);

            // Guard against multiple initialization
            if (window._adminStoreProductDetailInitialized) {
                adminStoreProductDetailLog.warn('Already initialized, skipping');
                return;
            }
            window._adminStoreProductDetailInitialized = true;

            // Load product data
            await this.loadProduct();

            adminStoreProductDetailLog.info('Store Product Detail initialization complete');
        },

        /**
         * Load product details
         */
        async loadProduct() {
            this.loading = true;
            this.error = '';

            try {
                const response = await apiClient.get(`/admin/store-products/${this.productId}`);
                this.product = response;
                adminStoreProductDetailLog.info('Loaded product:', this.product.id);
            } catch (error) {
                adminStoreProductDetailLog.error('Failed to load product:', error);
                this.error = error.message || 'Failed to load product details';
            } finally {
                this.loading = false;
            }
        },

        /**
         * Open edit modal (placeholder for future implementation)
         */
        openEditModal() {
            window.dispatchEvent(new CustomEvent('toast', {
                detail: { message: 'Edit functionality coming soon', type: 'info' }
            }));
        },

        /**
         * Toggle active status
         */
        async toggleActive() {
            // TODO: Implement PATCH endpoint for status update
            window.dispatchEvent(new CustomEvent('toast', {
                detail: {
                    message: 'Status toggle functionality coming soon',
                    type: 'info'
                }
            }));
        },

        /**
         * Confirm remove
         */
        confirmRemove() {
            this.showRemoveModal = true;
        },

        /**
         * Execute remove
         */
        async executeRemove() {
            this.removing = true;

            try {
                await apiClient.delete(`/admin/store-products/${this.productId}`);

                adminStoreProductDetailLog.info('Product removed:', this.productId);

                window.dispatchEvent(new CustomEvent('toast', {
                    detail: {
                        message: 'Product removed from catalog successfully',
                        type: 'success'
                    }
                }));

                // Redirect to store products list
                setTimeout(() => {
                    window.location.href = '/admin/store-products';
                }, 1000);
            } catch (error) {
                adminStoreProductDetailLog.error('Failed to remove product:', error);
                window.dispatchEvent(new CustomEvent('toast', {
                    detail: { message: error.message || 'Failed to remove product', type: 'error' }
                }));
            } finally {
                this.removing = false;
                this.showRemoveModal = false;
            }
        },

        /**
         * Format price for display
         */
        formatPrice(price, currency = 'EUR') {
            if (price === null || price === undefined) return '-';
            const numPrice = typeof price === 'string' ? parseFloat(price) : price;
            if (isNaN(numPrice)) return price;

            return new Intl.NumberFormat('de-DE', {
                style: 'currency',
                currency: currency || 'EUR'
            }).format(numPrice);
        },

        /**
         * Format date for display
         */
        formatDate(dateString) {
            if (!dateString) return '-';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('en-GB', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (e) {
                return dateString;
            }
        }
    };
}
