/**
 * useCapture — WebRTC screen capture lifecycle
 *
 * Stream stored on window so it survives Vite HMR module re-evaluation.
 * Single implementation of getDisplayMedia + canvas capture.
 */

import { ref } from 'vue';
import { useHermes } from './useHermes';

// ── Stored on window.__hermes (survives HMR module re-evaluation) ──
const H = useHermes();

function getStream(): MediaStream | null { return H.captureStream || null; }
function setStream(s: MediaStream | null) { H.captureStream = s; }

const isActive = ref(false);

// Restore state on HMR re-evaluation
syncState();

function syncState() {
    const stream = getStream();
    isActive.value = !!(stream && stream.active && stream.getVideoTracks().some(t => t.readyState === 'live'));
    if (!isActive.value && stream) {
        stream.getTracks().forEach(t => t.stop());
        setStream(null);
    }
}

export function useCapture() {
    async function enable(): Promise<{ enabled: boolean; error?: string }> {
        const stream = getStream();
        if (stream && stream.active) {
            syncState();
            if (isActive.value) return { enabled: true };
        }
        try {
            const newStream = await navigator.mediaDevices.getDisplayMedia({
                video: { displaySurface: 'browser' } as any,
                preferCurrentTab: true,
            } as any);
            newStream.getVideoTracks()[0].onended = () => {
                setStream(null);
                syncState();
            };
            setStream(newStream);
            syncState();
            return { enabled: true };
        } catch (e: any) {
            setStream(null);
            syncState();
            return { enabled: false, error: `Capture denied: ${e.message}` };
        }
    }

    function disable() {
        const stream = getStream();
        if (stream) {
            stream.getTracks().forEach(t => t.stop());
            setStream(null);
        }
        syncState();
    }

    async function capture(quality = 0.7): Promise<{ dataUrl: string; length: number } | { error: string }> {
        syncState();
        const stream = getStream();
        if (!stream) return { error: 'Capture not enabled -- send enableCapture first' };

        const track = stream.getVideoTracks()[0];
        if (!track || track.readyState !== 'live') {
            setStream(null);
            syncState();
            return { error: 'Capture stream ended -- re-enable with enableCapture' };
        }

        const video = document.createElement('video');
        video.srcObject = stream;
        video.muted = true;
        await video.play();

        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d')!.drawImage(video, 0, 0);
        video.pause();
        video.srcObject = null;

        return new Promise(resolve => {
            canvas.toBlob(blob => {
                if (!blob) { resolve({ error: 'Canvas toBlob failed' }); return; }
                const reader = new FileReader();
                reader.onloadend = () => {
                    const dataUrl = reader.result as string;
                    resolve({ dataUrl, length: dataUrl.length });
                };
                reader.readAsDataURL(blob);
            }, 'image/jpeg', quality);
        });
    }

    function healthCheck(): { active: boolean; tracks: number; reason?: string } {
        const stream = getStream();
        if (!stream) return { active: false, tracks: 0, reason: 'no stream' };
        const tracks = stream.getVideoTracks();
        const live = tracks.filter(t => t.readyState === 'live');
        if (!stream.active || live.length === 0) {
            setStream(null);
            syncState();
            return { active: false, tracks: 0, reason: 'stream ended' };
        }
        return { active: true, tracks: live.length };
    }

    return { isActive, enable, disable, capture, healthCheck };
}
