// app/static/store/js/dashboard.js
/**
 * Store dashboard page logic
 */

// ✅ Use centralized logger (with safe fallback)
const storeDashLog = window.LogConfig.loggers.dashboard ||
    window.LogConfig.createLogger('dashboard', false);

storeDashLog.info('Loading...');
storeDashLog.info('[STORE DASHBOARD] data function exists?', typeof data);

/**
 * Onboarding banner component.
 * Fetches onboarding steps from API, supports session-scoped dismiss.
 */
function onboardingBanner() {
    const t = (key, vars) => I18n.t(key, vars);
    return {
        t,
        visible: false,
        isOwner: true,
        steps: [],
        totalSteps: 0,
        completedSteps: 0,
        progressPercentage: 0,

        async init() {
            if (window._onboardingBannerInitialized) return;
            window._onboardingBannerInitialized = true;

            // Check session-scoped dismiss
            if (sessionStorage.getItem('onboarding_dismissed')) {
                return;
            }

            try {
                const response = await apiClient.get('/store/dashboard/onboarding');
                const steps = response.steps || [];
                this.isOwner = response.is_owner !== false;

                // Load module translations BEFORE setting reactive data
                // Keys are like "tenancy.onboarding...." — first segment is the module
                const modules = new Set();
                for (const step of steps) {
                    const mod = step.title_key?.split('.')[0];
                    if (mod) modules.add(mod);
                }
                await Promise.all([...modules].map(m => I18n.loadModule(m)));

                // Now set reactive data — Alpine re-renders with translations ready
                this.steps = steps;
                this.totalSteps = response.total_steps || 0;
                this.completedSteps = response.completed_steps || 0;
                this.progressPercentage = response.progress_percentage || 0;

                // Show banner only if there are incomplete steps
                if (this.totalSteps > 0 && !response.all_completed) {
                    this.visible = true;
                }
            } catch (error) {
                storeDashLog.error('Failed to load onboarding status', error);
            }
        },

        dismiss() {
            sessionStorage.setItem('onboarding_dismissed', 'true');
            this.visible = false;
        }
    };
}

function storeDashboard() {
    storeDashLog.info('[STORE DASHBOARD] storeDashboard() called');
    storeDashLog.info('[STORE DASHBOARD] data function exists inside?', typeof data);

    return {
        // ✅ Inherit base layout state (includes storeCode, dark mode, menu states)
        ...data(),

        // ✅ Set page identifier
        currentPage: 'dashboard',

        loading: false,
        error: '',
        stats: {
            products_count: 0,
            orders_count: 0,
            customers_count: 0,
            revenue: 0
        },
        recentOrders: [],
        recentProducts: [],

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

            try {
                // IMPORTANT: Call parent init first to set storeCode from URL
                const parentInit = data().init;
                if (parentInit) {
                    await parentInit.call(this);
                }

                await this.loadDashboardData();
            } catch (error) {
                storeDashLog.error('Failed to initialize dashboard:', error);
            }
        },

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

            try {
                // Load stats
                // NOTE: apiClient prepends /api/v1, and store context middleware handles store detection
                // So we just call /store/dashboard/stats → becomes /api/v1/store/dashboard/stats
                const statsResponse = await apiClient.get(
                    `/store/dashboard/stats`
                );

                // Map API response to stats (similar to admin dashboard pattern)
                this.stats = {
                    products_count: statsResponse.products?.total || 0,
                    orders_count: statsResponse.orders?.total || 0,
                    customers_count: statsResponse.customers?.total || 0,
                    revenue: statsResponse.revenue?.total || 0
                };

                // Load recent orders
                const ordersResponse = await apiClient.get(
                    `/store/orders?limit=5&sort=created_at:desc`
                );
                this.recentOrders = ordersResponse.items || [];

                // Load recent products
                const productsResponse = await apiClient.get(
                    `/store/products?limit=5&sort=created_at:desc`
                );
                this.recentProducts = productsResponse.items || [];

                storeDashLog.info('Dashboard data loaded', {
                    stats: this.stats,
                    orders: this.recentOrders.length,
                    products: this.recentProducts.length
                });

            } catch (error) {
                storeDashLog.error('Failed to load dashboard data', error);
                this.error = 'Failed to load dashboard data. Please try refreshing the page.';
            } finally {
                this.loading = false;
            }
        },

        async refresh() {
            try {
                await this.loadDashboardData();
            } catch (error) {
                storeDashLog.error('Failed to refresh dashboard:', error);
            }
        },

        formatCurrency(amount) {
            const locale = window.STORE_CONFIG?.locale || 'en-GB';
            const currency = window.STORE_CONFIG?.currency || 'EUR';
            return new Intl.NumberFormat(locale, {
                style: 'currency',
                currency: currency
            }).format(amount || 0);
        },

        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            const locale = window.STORE_CONFIG?.locale || 'en-GB';
            return date.toLocaleDateString(locale, {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        }
    };
}
