import Alpine from 'alpinejs';

Alpine.data('waitingRoom', () => ({
    message: 'Waiting for the host to let you in…',
    denied: false,
    pollTimer: null,

    init() {
        this.pollTimer = setInterval(() => this.poll(), 2500);
        this.poll();
    },

    destroy() {
        if (this.pollTimer) {
            clearInterval(this.pollTimer);
        }
    },

    async poll() {
        const url = this.$el.dataset.statusUrl;
        if (!url) return;

        try {
            const res = await fetch(url, { headers: { Accept: 'application/json' } });
            const data = await res.json();

            if (data.ended && data.redirect) {
                window.location.href = data.redirect;
                return;
            }

            if (data.redirect) {
                window.location.href = data.redirect;
                return;
            }

            if (data.denied) {
                this.denied = true;
                this.message = 'The host declined your request to join.';
                clearInterval(this.pollTimer);
            }
        } catch {
            // ignore transient errors
        }
    },
}));

Alpine.data('leaveFeedback', () => ({
    rating: 0,
    audioRating: 0,
    videoRating: 0,
    hoverRating: 0,
    hoverAudio: 0,
    hoverVideo: 0,
    comment: '',

    setRating(value) {
        this.rating = value;
    },

    setAudioRating(value) {
        this.audioRating = value;
    },

    setVideoRating(value) {
        this.videoRating = value;
    },

    canSubmit() {
        return this.rating > 0;
    },
}));

window.Alpine = Alpine;
Alpine.start();
