// app/modules/marketplace/static/admin/js/letzshop-store-directory.js
/**
 * Admin Letzshop Store Directory page logic
 * Browse and import stores from Letzshop marketplace
 */

const letzshopStoreDirectoryLog = window.LogConfig.loggers.letzshopStoreDirectory ||
    window.LogConfig.createLogger('letzshopStoreDirectory', false);

letzshopStoreDirectoryLog.info('Loading...');

function letzshopStoreDirectory() {
    letzshopStoreDirectoryLog.info('letzshopStoreDirectory() called');

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

        // Set page identifier for sidebar highlighting
        currentPage: 'letzshop-store-directory',

        // Data
        stores: [],
        stats: {},
        merchants: [],
        total: 0,
        page: 1,
        limit: 20,
        hasMore: false,

        // State
        loading: true,
        syncing: false,
        creating: false,
        error: '',
        successMessage: '',

        // Filters
        filters: {
            search: '',
            city: '',
            category: '',
            only_unclaimed: false,
        },

        // Modals
        showDetailModal: false,
        showCreateModal: false,
        selectedStore: null,
        createStoreData: {
            slug: '',
            name: '',
            merchant_id: '',
        },
        createError: '',

        // Init
        async init() {
            // Guard against multiple initialization
            if (window._letzshopStoreDirectoryInitialized) return;
            window._letzshopStoreDirectoryInitialized = true;

            letzshopStoreDirectoryLog.info('init() called');
            await Promise.all([
                this.loadStats(),
                this.loadStores(),
                this.loadMerchants(),
            ]);
        },

        // API calls
        async loadStats() {
            try {
                const data = await apiClient.get('/admin/letzshop/store-directory/stats');
                if (data.success) {
                    this.stats = data.stats;
                }
            } catch (e) {
                letzshopStoreDirectoryLog.error('Failed to load stats:', e);
            }
        },

        async loadStores() {
            this.loading = true;
            this.error = '';

            try {
                const params = new URLSearchParams({
                    page: this.page,
                    limit: this.limit,
                });

                if (this.filters.search) params.append('search', this.filters.search);
                if (this.filters.city) params.append('city', this.filters.city);
                if (this.filters.category) params.append('category', this.filters.category);
                if (this.filters.only_unclaimed) params.append('only_unclaimed', 'true');

                const data = await apiClient.get(`/admin/letzshop/store-directory/stores?${params}`);

                if (data.success) {
                    this.stores = data.stores;
                    this.total = data.total;
                    this.hasMore = data.has_more;
                } else {
                    this.error = data.detail || 'Failed to load stores';
                }
            } catch (e) {
                this.error = 'Failed to load stores';
                letzshopStoreDirectoryLog.error('Failed to load stores:', e);
            } finally {
                this.loading = false;
            }
        },

        async loadMerchants() {
            try {
                const data = await apiClient.get('/admin/merchants?limit=100');
                if (data.merchants) {
                    this.merchants = data.merchants;
                }
            } catch (e) {
                letzshopStoreDirectoryLog.error('Failed to load merchants:', e);
            }
        },

        async triggerSync() {
            this.syncing = true;
            this.error = '';
            this.successMessage = '';

            try {
                const data = await apiClient.post('/admin/letzshop/store-directory/sync');

                if (data.success) {
                    this.successMessage = data.message + (data.mode === 'celery' ? ` (Task ID: ${data.task_id})` : '');
                    // Reload data after a delay to allow sync to complete
                    setTimeout(() => {
                        this.loadStats();
                        this.loadStores();
                    }, 3000);
                } else {
                    this.error = data.detail || 'Failed to trigger sync';
                }
            } catch (e) {
                this.error = 'Failed to trigger sync';
                letzshopStoreDirectoryLog.error('Failed to trigger sync:', e);
            } finally {
                this.syncing = false;
            }
        },

        async createStore() {
            if (!this.createStoreData.merchant_id || !this.createStoreData.slug) return;

            this.creating = true;
            this.createError = '';

            try {
                const data = await apiClient.post(
                    `/admin/letzshop/store-directory/stores/${this.createStoreData.slug}/create-store?merchant_id=${this.createStoreData.merchant_id}`
                );

                if (data.success) {
                    this.showCreateModal = false;
                    this.successMessage = data.message;
                    this.loadStores();
                    this.loadStats();
                } else {
                    this.createError = data.detail || 'Failed to create store';
                }
            } catch (e) {
                this.createError = 'Failed to create store';
                letzshopStoreDirectoryLog.error('Failed to create store:', e);
            } finally {
                this.creating = false;
            }
        },

        // Modal handlers
        showStoreDetail(store) {
            this.selectedStore = store;
            this.showDetailModal = true;
        },

        openCreateStoreModal(store) {
            this.createStoreData = {
                slug: store.slug,
                name: store.name,
                merchant_id: '',
            };
            this.createError = '';
            this.showCreateModal = true;
        },

        // Utilities
        formatDate(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        },
    };
}

letzshopStoreDirectoryLog.info('Loaded');
