/**
 * Platform Detail - Alpine.js Component
 *
 * Displays platform overview, stats, and quick actions.
 */

const platformDetailLog = window.LogConfig.createLogger('PLATFORM_DETAIL');

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

    // Page identification
    currentPage: 'platform-detail',

    // State
    platform: null,
    stats: null,
    loading: true,
    error: null,
    platformCode: null,

    // Lifecycle
    async init() {
      platformDetailLog.info('=== PLATFORM DETAIL PAGE INITIALIZING ===');

      // Duplicate initialization guard
      if (window._platformDetailInitialized) {
        platformDetailLog.warn('Platform detail page already initialized, skipping...');
        return;
      }
      window._platformDetailInitialized = true;

      try {
        // Extract platform code from URL
        const path = window.location.pathname;
        const match = path.match(/\/admin\/platforms\/([^\/]+)$/);

        if (match) {
          this.platformCode = match[1];
          platformDetailLog.info('Viewing platform:', this.platformCode);
          await this.loadPlatform();
        } else {
          platformDetailLog.error('No platform code in URL');
          this.error = 'Platform code not found in URL';
          this.loading = false;
        }

        platformDetailLog.info('=== PLATFORM DETAIL PAGE INITIALIZATION COMPLETE ===');
      } catch (error) {
        window.LogConfig.logError(error, 'Platform Detail Init');
        this.error = 'Failed to initialize page';
        this.loading = false;
      }
    },

    // API Methods
    async loadPlatform() {
      try {
        const response = await apiClient.get(`/admin/platforms/${this.platformCode}`);
        this.platform = response;
        platformDetailLog.info(`Loaded platform: ${this.platformCode}`);
      } catch (err) {
        platformDetailLog.error('Error loading platform:', err);
        this.error = err.message || 'Failed to load platform';
        throw err;
      } finally {
        this.loading = false;
      }
    },

    // Helper Methods
    getPlatformIcon(code) {
      const icons = {
        main: 'home',
        oms: 'clipboard-list',
        loyalty: 'star',
        sitebuilder: 'template',
      };
      return icons[code] || 'globe-alt';
    },

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

    getPlatformUrl() {
      if (!this.platform) return '#';
      if (this.platform.domain) {
        return `https://${this.platform.domain}`;
      }
      // Development URL
      if (this.platform.code === 'main') {
        return '/';
      }
      return `/platforms/${this.platform.code}/`;
    },
  };
}
