// noqa: js-006 - async init pattern is safe, loadData has try/catch
// static/admin/js/platform-homepage.js

// Use centralized logger
const platformHomepageLog = window.LogConfig.loggers.platformHomepage || window.LogConfig.createLogger('platformHomepage');

// ============================================
// PLATFORM HOMEPAGE MANAGER FUNCTION
// ============================================
function platformHomepageManager() {
    return {
        // Inherit base layout functionality from init-alpine.js
        ...data(),

        // Page identifier for sidebar active state
        currentPage: 'platform-homepage',

        // Platform homepage specific state
        page: null,
        loading: false,
        saving: false,
        error: null,
        successMessage: null,

        // Initialize
        async init() {
            platformHomepageLog.info('=== PLATFORM HOMEPAGE MANAGER INITIALIZING ===');

            // Prevent multiple initializations
            if (window._platformHomepageInitialized) {
                platformHomepageLog.warn('Platform homepage manager already initialized, skipping...');
                return;
            }
            window._platformHomepageInitialized = true;

            platformHomepageLog.group('Loading platform homepage');
            await this.loadPlatformHomepage();
            platformHomepageLog.groupEnd();

            platformHomepageLog.info('=== PLATFORM HOMEPAGE MANAGER INITIALIZATION COMPLETE ===');
        },

        // Load platform homepage from API
        async loadPlatformHomepage() {
            this.loading = true;
            this.error = null;

            try {
                platformHomepageLog.info('Fetching platform homepage...');

                // Fetch all platform pages
                const response = await apiClient.get('/admin/content-pages/platform?include_unpublished=true');

                platformHomepageLog.debug('API Response:', response);

                if (!response) {
                    throw new Error('Invalid API response');
                }

                // Handle response - API returns array directly
                const pages = Array.isArray(response) ? response : (response.data || response.items || []);

                // Find the homepage page (slug='home')
                const homepage = pages.find(page => page.slug === 'home');

                if (!homepage) {
                    platformHomepageLog.warn('Platform homepage not found, creating default...');
                    // Initialize with default values
                    this.page = {
                        id: null,
                        slug: 'home',
                        title: 'Welcome to Our Multi-Store Marketplace',
                        content: '<p>Connect stores with customers worldwide. Build your online store and reach millions of shoppers.</p>',
                        template: 'default',
                        content_format: 'html',
                        meta_description: 'Leading multi-store marketplace platform. Connect with thousands of stores and discover millions of products.',
                        meta_keywords: 'marketplace, multi-store, e-commerce, online shopping',
                        is_published: false,
                        show_in_header: false,
                        show_in_footer: false,
                        display_order: 0
                    };
                } else {
                    this.page = { ...homepage };
                    platformHomepageLog.info('Platform homepage loaded:', this.page);
                }

            } catch (err) {
                platformHomepageLog.error('Error loading platform homepage:', err);
                this.error = err.message || 'Failed to load platform homepage';
            } finally {
                this.loading = false;
            }
        },

        // Save platform homepage
        async savePage() {
            if (this.saving) return;

            this.saving = true;
            this.error = null;
            this.successMessage = null;

            try {
                platformHomepageLog.info('Saving platform homepage...');

                const payload = {
                    slug: 'platform_homepage',
                    title: this.page.title,
                    content: this.page.content,
                    content_format: this.page.content_format || 'html',
                    template: this.page.template,
                    meta_description: this.page.meta_description,
                    meta_keywords: this.page.meta_keywords,
                    is_published: this.page.is_published,
                    show_in_header: false,  // Homepage never in header
                    show_in_footer: false,  // Homepage never in footer
                    display_order: 0,
                    store_id: null  // Platform default
                };

                platformHomepageLog.debug('Payload:', payload);

                let response;
                if (this.page.id) {
                    // Update existing page
                    response = await apiClient.put(`/admin/content-pages/${this.page.id}`, payload);
                    platformHomepageLog.info('Platform homepage updated');
                } else {
                    // Create new page
                    response = await apiClient.post('/admin/content-pages/platform', payload);
                    platformHomepageLog.info('Platform homepage created');
                }

                if (response) {
                    // Handle response - API returns object directly
                    const pageData = response.data || response;
                    this.page = { ...pageData };
                    this.successMessage = 'Platform homepage saved successfully!';

                    // Clear success message after 3 seconds
                    setTimeout(() => {
                        this.successMessage = null;
                    }, 3000);
                }

            } catch (err) {
                platformHomepageLog.error('Error saving platform homepage:', err);
                this.error = err.message || 'Failed to save platform homepage';
            } finally {
                this.saving = false;
            }
        }
    };
}
