export function useWebcamCapture() {
    let stream: MediaStream | null = null;

    async function startCamera(videoElement: HTMLVideoElement): Promise<void> {
        stream = await navigator.mediaDevices.getUserMedia({
            video: {
                facingMode: 'user',
                width: { ideal: 1280 },
                height: { ideal: 720 },
            },
            audio: false,
        });

        videoElement.srcObject = stream;
        await videoElement.play();
    }

    function stopCamera(): void {
        stream?.getTracks().forEach((track) => track.stop());
        stream = null;
    }

    function capture(videoElement: HTMLVideoElement): string {
        const canvas = document.createElement('canvas');
        canvas.width = videoElement.videoWidth;
        canvas.height = videoElement.videoHeight;

        const context = canvas.getContext('2d');

        if (!context) {
            throw new Error('Gagal menyiapkan kanvas foto.');
        }

        context.save();
        context.translate(canvas.width, 0);
        context.scale(-1, 1);
        context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
        context.restore();

        return canvas.toDataURL('image/jpeg', 0.85);
    }

    return {
        startCamera,
        stopCamera,
        capture,
    };
}
