
export type VideoCodec = "H264" | "H265" | "VP9" | "AV1";
export type AudioCodec = "AAC" | "MP3" | "OPUS" | "VORBIS";

export interface CodecSupport {
	video: VideoCodec[];
	audio: AudioCodec[];
}

export function detectCodecSupport(): CodecSupport {
	const video = document.createElement("video");

	const videoCodecs: VideoCodec[] = [];
	const audioCodecs: AudioCodec[] = [];

	// Test video codecs
	if (video.canPlayType('video/mp4; codecs="avc1.42E01E"') !== "") {
		videoCodecs.push("H264");
	}
	if (video.canPlayType('video/mp4; codecs="hev1.1.6.L93.B0"') !== "") {
		videoCodecs.push("H265");
	}
	if (video.canPlayType('video/webm; codecs="vp9"') !== "") {
		videoCodecs.push("VP9");
	}
	if (video.canPlayType('video/mp4; codecs="av01.0.04M.08"') !== "") {
		videoCodecs.push("AV1");
	}

	// Fallback: if no codecs detected, add H264 (most compatible)
	if (videoCodecs.length === 0) {
		videoCodecs.push("H264");
	}

	// Test audio codecs
	if (video.canPlayType('audio/mp4; codecs="mp4a.40.2"') !== "") {
		audioCodecs.push("AAC");
	}
	if (video.canPlayType("audio/mpeg") !== "") {
		audioCodecs.push("MP3");
	}
	if (video.canPlayType('audio/webm; codecs="opus"') !== "") {
		audioCodecs.push("OPUS");
	}
	if (video.canPlayType('audio/ogg; codecs="vorbis"') !== "") {
		audioCodecs.push("VORBIS");
	}

	// Fallback: if no audio codecs detected, add AAC (most compatible)
	if (audioCodecs.length === 0) {
		audioCodecs.push("AAC");
	}

	return { video: videoCodecs, audio: audioCodecs };
}

export function formatTime(seconds: number): string {
	const hours = Math.floor(seconds / 3600);
	const minutes = Math.floor((seconds % 3600) / 60);
	const secs = Math.floor(seconds % 60);

	if (hours > 0) {
		return `${hours}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
	}
	return `${minutes}:${secs.toString().padStart(2, "0")}`;
}
