// static/admin/js/store-edit.js

// ✅ Use centralized logger - ONE LINE!
// Create custom logger for store edit
const editLog = window.LogConfig.createLogger('STORE-EDIT');

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

        // Store edit page specific state
        currentPage: 'store-edit',
        loading: false,
        store: null,
        formData: {},
        errors: {},
        loadingStore: false,
        saving: false,
        storeCode: null,
        showToggleVerificationModal: false,
        showToggleActiveModal: false,
        showDeleteStoreModal: false,
        showDeleteStoreFinalModal: false,

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

            editLog.info('=== STORE EDIT PAGE INITIALIZING ===');

            // Prevent multiple initializations
            if (window._storeEditInitialized) {
                editLog.warn('Store edit page already initialized, skipping...');
                return;
            }
            window._storeEditInitialized = true;

            try {
                // Get store code from URL
                const path = window.location.pathname;
                const match = path.match(/\/admin\/stores\/([^\/]+)\/edit/);

                if (match) {
                    this.storeCode = match[1];
                    editLog.info('Editing store:', this.storeCode);
                    await this.loadStore();
                } else {
                    editLog.error('No store code in URL');
                    Utils.showToast(I18n.t('tenancy.messages.invalid_store_url'), 'error');
                    setTimeout(() => window.location.href = '/admin/stores', 2000);
                }

                editLog.info('=== STORE EDIT PAGE INITIALIZATION COMPLETE ===');
            } catch (error) {
                window.LogConfig.logError(error, 'Store Edit Init');
                Utils.showToast(I18n.t('tenancy.messages.failed_to_initialize_page'), 'error');
            }
        },

        // Load store data
        async loadStore() {
            editLog.info('Loading store data...');
            this.loadingStore = true;

            try {
                const url = `/admin/stores/${this.storeCode}`;
                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 Store', duration);

                this.store = response;

                // Initialize form data
                // For contact fields: empty if inherited (shows placeholder), actual value if override
                this.formData = {
                    name: response.name || '',
                    subdomain: response.subdomain || '',
                    description: response.description || '',
                    // Contact fields: empty string for inherited (will show merchant value as placeholder)
                    contact_email: response.contact_email_inherited ? '' : (response.contact_email || ''),
                    contact_phone: response.contact_phone_inherited ? '' : (response.contact_phone || ''),
                    website: response.website_inherited ? '' : (response.website || ''),
                    business_address: response.business_address_inherited ? '' : (response.business_address || ''),
                    tax_number: response.tax_number_inherited ? '' : (response.tax_number || ''),
                    // Marketplace URLs (no inheritance)
                    letzshop_csv_url_fr: response.letzshop_csv_url_fr || '',
                    letzshop_csv_url_en: response.letzshop_csv_url_en || '',
                    letzshop_csv_url_de: response.letzshop_csv_url_de || ''
                };

                editLog.info(`Store loaded in ${duration}ms`, {
                    store_code: this.store.store_code,
                    name: this.store.name
                });
                editLog.debug('Form data initialized:', this.formData);

            } catch (error) {
                window.LogConfig.logError(error, 'Load Store');
                Utils.showToast(I18n.t('tenancy.messages.failed_to_load_store'), 'error');
                setTimeout(() => window.location.href = '/admin/stores', 2000);
            } finally {
                this.loadingStore = false;
            }
        },

        // Format subdomain
        formatSubdomain() {
            this.formData.subdomain = this.formData.subdomain
                .toLowerCase()
                .replace(/[^a-z0-9-]/g, '');
            editLog.debug('Subdomain formatted:', this.formData.subdomain);
        },

        // Submit form
        async handleSubmit() {
            editLog.info('=== SUBMITTING STORE UPDATE ===');
            editLog.debug('Form data:', this.formData);

            this.errors = {};
            this.saving = true;

            try {
                const url = `/admin/stores/${this.storeCode}`;
                window.LogConfig.logApiCall('PUT', url, this.formData, 'request');

                const startTime = performance.now();
                const response = await apiClient.put(url, this.formData);
                const duration = performance.now() - startTime;

                window.LogConfig.logApiCall('PUT', url, response, 'response');
                window.LogConfig.logPerformance('Update Store', duration);

                this.store = response;
                Utils.showToast(I18n.t('tenancy.messages.store_updated_successfully'), 'success');
                editLog.info(`Store updated successfully in ${duration}ms`, response);

                // Optionally redirect back to list
                // setTimeout(() => window.location.href = '/admin/stores', 1500);

            } catch (error) {
                window.LogConfig.logError(error, 'Update Store');

                // Handle validation errors
                if (error.details && error.details.validation_errors) {
                    error.details.validation_errors.forEach(err => {
                        const field = err.loc?.[1] || err.loc?.[0];
                        if (field) {
                            this.errors[field] = err.msg;
                        }
                    });
                    editLog.debug('Validation errors:', this.errors);
                }

                Utils.showToast(error.message || 'Failed to update store', 'error');
            } finally {
                this.saving = false;
                editLog.info('=== STORE UPDATE COMPLETE ===');
            }
        },

        // Toggle verification
        async toggleVerification() {
            const action = this.store.is_verified ? 'unverify' : 'verify';
            editLog.info(`Toggle verification: ${action}`);

            this.saving = true;
            try {
                const url = `/admin/stores/${this.storeCode}/verification`;
                const payload = { is_verified: !this.store.is_verified };

                window.LogConfig.logApiCall('PUT', url, payload, 'request');

                const response = await apiClient.put(url, payload);

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

                this.store = response;
                Utils.showToast(`Store ${action}ed successfully`, 'success');
                editLog.info(`Store ${action}ed successfully`);

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

        // Toggle active status
        async toggleActive() {
            const action = this.store.is_active ? 'deactivate' : 'activate';
            editLog.info(`Toggle active status: ${action}`);

            this.saving = true;
            try {
                const url = `/admin/stores/${this.storeCode}/status`;
                const payload = { is_active: !this.store.is_active };

                window.LogConfig.logApiCall('PUT', url, payload, 'request');

                const response = await apiClient.put(url, payload);

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

                this.store = response;
                Utils.showToast(`Store ${action}d successfully`, 'success');
                editLog.info(`Store ${action}d successfully`);

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

        // Prompt delete store (first step of double confirm)
        promptDeleteStore() {
            editLog.info('Delete store requested');
            this.showDeleteStoreModal = true;
        },

        // Confirm first step, show final confirmation
        confirmDeleteStoreStep() {
            editLog.info('First delete confirmation accepted, showing final confirmation');
            this.showDeleteStoreFinalModal = true;
        },

        // Delete store
        async deleteStore() {
            this.saving = true;
            try {
                const url = `/admin/stores/${this.storeCode}?confirm=true`;
                window.LogConfig.logApiCall('DELETE', url, null, 'request');

                const response = await apiClient.delete(url);

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

                Utils.showToast(I18n.t('tenancy.messages.store_deleted_successfully'), 'success');
                editLog.info('Store deleted successfully');

                // Redirect to stores list
                setTimeout(() => {
                    window.location.href = '/admin/stores';
                }, 1500);

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

        // ===== Contact Field Inheritance Methods =====

        /**
         * Reset a single contact field to inherit from merchant.
         * Sets the field to empty string, which the backend converts to null (inherit).
         * @param {string} fieldName - The contact field to reset
         */
        resetFieldToMerchant(fieldName) {
            const contactFields = ['contact_email', 'contact_phone', 'website', 'business_address', 'tax_number'];
            if (!contactFields.includes(fieldName)) {
                editLog.warn('Invalid contact field:', fieldName);
                return;
            }

            editLog.info(`Resetting ${fieldName} to inherit from merchant`);
            this.formData[fieldName] = '';
        },

        /**
         * Reset all contact fields to inherit from merchant.
         */
        resetAllContactToMerchant() {
            editLog.info('Resetting all contact fields to inherit from merchant');

            const contactFields = ['contact_email', 'contact_phone', 'website', 'business_address', 'tax_number'];
            contactFields.forEach(field => {
                this.formData[field] = '';
            });

            Utils.showToast(I18n.t('tenancy.messages.all_contact_fields_reset_to_merchant_defa'), 'info');
        },

        /**
         * Check if any contact field has a value (not empty = has override).
         * @returns {boolean} True if at least one contact field has a value
         */
        hasAnyContactOverride() {
            const contactFields = ['contact_email', 'contact_phone', 'website', 'business_address', 'tax_number'];
            return contactFields.some(field => this.formData[field]);
        }
    };
}

editLog.info('Store edit module loaded');
