// app/static/vendor/js/dashboard.js
/**
 * Vendor dashboard page logic
 */

// ✅ Use centralized logger
const vendorDashLog = window.LogConfig.loggers.dashboard;

console.log('[VENDOR DASHBOARD] Loading...');
console.log('[VENDOR DASHBOARD] data function exists?', typeof data);

function vendorDashboard() {
    console.log('[VENDOR DASHBOARD] vendorDashboard() called');
    console.log('[VENDOR DASHBOARD] data function exists inside?', typeof data);

    return {
        // ✅ Inherit base layout state (includes vendorCode, 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._vendorDashboardInitialized) {
                return;
            }
            window._vendorDashboardInitialized = true;

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

            await this.loadDashboardData();
        },

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

            try {
                // Load stats
                // NOTE: apiClient prepends /api/v1, and vendor context middleware handles vendor detection
                // So we just call /vendor/dashboard/stats → becomes /api/v1/vendor/dashboard/stats
                const statsResponse = await apiClient.get(
                    `/vendor/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(
                    `/vendor/orders?limit=5&sort=created_at:desc`
                );
                this.recentOrders = ordersResponse.items || [];

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

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

            } catch (error) {
                vendorDashLog.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() {
            await this.loadDashboardData();
        },

        formatCurrency(amount) {
            return new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'EUR'
            }).format(amount || 0);
        },

        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        }
    };
}