/*
 * chat 端一起看同步：显示播放器控制，并把播放/暂停/拖动同步给 admin。
 * 作者: @ccfork
 */
(function() {
    const config = window.CHAT_CONFIG || {};
    const apiUrl = config.apiUrl || 'chat_api.php';
    const sessionId = config.sessionId || '';
    const state = {
        controlSeq: 0,
        currentUrl: '',
        applying: false,
        syncTimer: null
    };
    const els = {};

    function $(id) {
        return document.getElementById(id);
    }

    function apiUrlFor(action, params = {}) {
        const query = new URLSearchParams({ action, ...params });
        return `${apiUrl}?${query.toString()}`;
    }

    async function apiPost(payload) {
        const res = await fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        return await res.json();
    }

    function videoPayload(action, eventName) {
        return {
            action,
            event: eventName,
            session_id: sessionId,
            current_time: els.video.currentTime || 0,
            duration: Number.isFinite(els.video.duration) ? els.video.duration : 0,
            paused: els.video.paused
        };
    }

    async function pushControl(eventName = 'sync') {
        if (!sessionId || !state.currentUrl || els.panel.hidden || state.applying) return;
        try {
            const data = await apiPost(videoPayload('chat_update_watch', eventName));
            if (data.success && data.state) {
                state.controlSeq = Number(data.state.control_seq || state.controlSeq);
            }
        } catch (error) {
            console.error('一起看控制同步失败:', error);
        }
    }

    function scheduleControl(eventName = 'sync') {
        clearTimeout(state.syncTimer);
        state.syncTimer = setTimeout(() => pushControl(eventName), 160);
    }

    async function applyWatch(watchState) {
        if (!watchState || !watchState.active || !watchState.url) {
            els.video.pause();
            window.WatchPlayer.destroyHls(els.video);
            els.video.removeAttribute('src');
            els.video.load();
            els.panel.hidden = true;
            state.currentUrl = '';
            state.controlSeq = Number(watchState?.control_seq || 0);
            return;
        }
        const incomingSeq = Number(watchState.control_seq || 0);
        if (incomingSeq <= state.controlSeq && state.currentUrl === watchState.url) return;
        if (watchState.last_controller === 'chat' && incomingSeq <= state.controlSeq) return;

        els.panel.hidden = false;
        state.applying = true;
        try {
            if (state.currentUrl !== watchState.url) {
                state.currentUrl = watchState.url;
                await window.WatchPlayer.setVideoSource(els.video, watchState.url);
            }
            const targetTime = Number(watchState.current_time || 0);
            if (Number.isFinite(targetTime) && Math.abs((els.video.currentTime || 0) - targetTime) > 0.8) {
                els.video.currentTime = targetTime;
            }
            if (watchState.paused) {
                els.video.pause();
            } else {
                els.video.play().catch(() => {});
            }
            state.controlSeq = incomingSeq;
        } finally {
            state.applying = false;
        }
    }

    async function pollWatch() {
        if (!sessionId) return;
        try {
            const res = await fetch(apiUrlFor('get_watch_state', { session_id: sessionId }), { cache: 'no-store' });
            const data = await res.json();
            if (data.success) await applyWatch(data.state);
        } catch (error) {
            console.error('一起看同步失败:', error);
        }
    }

    async function reportProgress() {
        if (!sessionId || !state.currentUrl || els.panel.hidden || state.applying) return;
        try {
            await apiPost(videoPayload('report_watch_progress', 'progress'));
        } catch (error) {
            console.error('一起看进度上报失败:', error);
        }
    }

    function init() {
        els.panel = $('chatWatchPanel');
        els.video = $('chatWatchVideo');
        if (!els.panel || !els.video) return;
        els.video.setAttribute('controlslist', 'nofullscreen nodownload noplaybackrate noremoteplayback');
        els.video.setAttribute('disablepictureinpicture', '');
        pollWatch();
        setInterval(pollWatch, 1000);
        setInterval(reportProgress, 1500);
        els.video.addEventListener('play', () => scheduleControl('play'));
        els.video.addEventListener('pause', () => scheduleControl('pause'));
        els.video.addEventListener('seeked', () => scheduleControl('seek'));
        els.video.addEventListener('timeupdate', () => {
            if (!els.video.paused) scheduleControl('progress');
        });
    }

    document.addEventListener('DOMContentLoaded', init);
})();
