import Alpine from 'alpinejs';
import { fetchGameState, fetchGameStatistics } from './game';

Alpine.data('gameStatistics', ({ gameId }) => ({
    gameId: '',
    loading: false,
    isVisible: false,
    errorMessage: '',
    statistics: null,
    gameStateListener: null,

    async init() {
        this.gameId = String(gameId || '').trim();
        if (this.gameId === '') {
            return;
        }

        this.gameStateListener = (event) => {
            const detail = event?.detail ?? {};
            const eventGameId = String(detail?.gameId || detail?.detail?.gameId || '').trim();
            if (eventGameId !== this.gameId) {
                return;
            }

            const status = String(detail?.status || detail?.detail?.status || '');
            void this.handleStatus(status);
        };
        window.addEventListener('game:state-updated', this.gameStateListener);

        await this.refreshStatus();
    },

    destroy() {
        if (!(this.gameStateListener instanceof Function)) {
            return;
        }

        window.removeEventListener('game:state-updated', this.gameStateListener);
    },

    async refreshStatus() {
        try {
            const data = await fetchGameState(this.gameId);
            await this.handleStatus(String(data?.game?.status || ''));
        } catch (error) {
            this.isVisible = false;
            this.errorMessage = error instanceof Error ? error.message : 'Statistik konnte nicht geladen werden.';
        }
    },

    async handleStatus(status) {
        if (status !== 'FINISHED') {
            this.loading = false;
            this.isVisible = false;
            this.errorMessage = '';
            this.statistics = null;
            return;
        }

        await this.loadStatistics();
    },

    async loadStatistics() {
        if (this.loading) {
            return;
        }

        this.loading = true;
        this.isVisible = true;
        this.errorMessage = '';

        try {
            const payload = await fetchGameStatistics(this.gameId);
            this.statistics = payload?.statistics || null;
        } catch (error) {
            this.statistics = null;
            this.errorMessage = error instanceof Error ? error.message : 'Statistik konnte nicht geladen werden.';
        } finally {
            this.loading = false;
        }
    },

    formatAverage(value) {
        const number = Number(value);
        if (!Number.isFinite(number)) {
            return '0.00';
        }

        return number.toFixed(2);
    },

    formatDuration(totalSeconds) {
        const seconds = Number(totalSeconds);
        if (!Number.isFinite(seconds) || seconds < 0) {
            return '-';
        }

        const safeSeconds = Math.floor(seconds);
        const hours = Math.floor(safeSeconds / 3600);
        const minutes = Math.floor((safeSeconds % 3600) / 60);
        const remainingSeconds = safeSeconds % 60;

        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
    }
}));
