Skip to content

A self-hosted media server and file management system

83.9 KB
Raw Blame
<script setup lang="ts">
import type { ContextMenuItem, PopoverItem } from '@/types/types';

import { controlsHideTime, playbackDataBuffer, playerHealthBuffer, volumeDelta, playbackDelta, playbackMin, playbackMax } from '@/service/player/playerConstants';
import { getScreenSize, handleStorageURL, isInputLikeElement, isMobileDevice, toFormattedDate, toFormattedDuration } from '@/service/util';
import { computed, nextTick, onBeforeUnmount, onMounted, provide, ref, useTemplateRef, watch } from 'vue';
import { copyVideoFrame, saveVideoFrame } from '@/service/player/frameService';
import { usePlaybackProgress } from '@/composables/player/usePlaybackProgress';
import { useRoute, useRouter } from 'vue-router';
import { UseCreatePlayback } from '@/service/mutations';
import { useVideoPlayback } from '@/service/queries';
import { ToastController } from '@/components/cedar-ui/toast';
import { useContentStore } from '@/stores/ContentStore';
import { debounce, round } from 'lodash-es';
import { useTranscript } from '@/components/video/transcript/useTranscript';
import { useAuthStore } from '@/stores/AuthStore';
import { ContextMenu } from '@/components/cedar-ui/context-menu';
import { GlobalModal } from '@/components/cedar-ui/modal';
import { useAppStore } from '@/stores/AppStore';
import { storeToRefs } from 'pinia';
import { getMediaUrl } from '@/service/api';
import { useRecord } from '@/service/records/useRecords';
import { cn, toast } from '@aminnausin/cedar-ui';
import { MediaType } from '@/types/types';
import { onSeek } from '@/service/player/seekBus';
import { FLAGS } from '@/config/featureFlags';

import AudioSpectrographPanel from '@/components/video/audio/AudioSpectrographPanel.vue';
import VideoControlWrapper from '@/components/video/VideoControlWrapper.vue';
import VideoPopoverSlider from '@/components/video/popover/VideoPopoverSlider.vue';
import AudioSpectrograph from '@/components/video/audio/AudioSpectrograph.vue';
import PlayerAudioTracks from '@/components/video/audio/PlayerAudioTracks.vue';
import VideoPopoverItem from '@/components/video/popover/VideoPopoverItem.vue';
import PlayerTranscript from '@/components/video/transcript/PlayerTranscript.vue';
import PlayerSubtitles from '@/components/video/subtitles/PlayerSubtitles.vue';
import VideoPartyPanel from '@/components/video/plugins/party/VideoPartyPanel.vue';
import PlayerSkipIntro from '@/components/video/plugins/skip-intro/PlayerSkipIntro.vue';
import PlayerOSDTimer from '@/components/video/OSD/PlayerOSDTimer.vue';
import PlayerBackdrop from '@/components/video/PlayerBackdrop.vue';
import PlayerOSDBase from '@/components/video/OSD/PlayerOSDBase.vue';
import VideoTimeline from '@/components/video/VideoTimeline.vue';
import VideoHeatmap from '@/components/video/VideoHeatmap.vue';
import VideoPopover from '@/components/video/popover/VideoPopover.vue';
import VideoButton from '@/components/video/button/VideoButton.vue';
import VideoSlider from '@/components/video/slider/VideoSlider.vue';
import VideoLyrics from '@/components/video/plugins/lyrics/VideoLyrics.vue';
import PlayerStats from '@/components/video/plugins/stats/PlayerStats.vue';

import ProiconsPictureInPictureEnter from '~icons/proicons/picture-in-picture-enter';
import ProiconsPictureInPictureExit from '~icons/proicons/picture-in-picture-exit';
import ProiconsFullScreenMaximize from '~icons/proicons/full-screen-maximize';
import ProiconsFullScreenMinimize from '~icons/proicons/full-screen-minimize';
import ProiconsTextHighlightColor from '~icons/proicons/text-highlight-color';
import ProiconsTextAlignLeft from '~icons/proicons/text-align-left';
import ProiconsArrowTrending from '~icons/proicons/arrow-trending';
import TablerMicrophone2Off from '~icons/tabler/microphone-2-off';
import ProiconsFastForward from '~icons/proicons/fast-forward';
import ProiconsVolumeMute from '~icons/proicons/volume-mute';
import ProiconsVolumeLow from '~icons/proicons/volume-low';
import ProiconsCheckmark from '~icons/proicons/checkmark';
import TablerMicrophone2 from '~icons/tabler/microphone-2';
import IconSpectrograph from '@/components/icons/IconSpectrograph.vue';
import ProiconsSparkle2 from '~icons/proicons/sparkle-2';
import ProiconsSettings from '~icons/proicons/settings';
import IconCaptionsOff from '@/components/icons/IconCaptionsOff.vue';
import ProiconsSpinner from '~icons/proicons/spinner';
import ProiconsReverse from '~icons/proicons/reverse';
import ProiconsVolume from '~icons/proicons/volume';
import IconTheatreOff from '@/components/icons/IconTheatreOff.vue';
import IconTheatreOn from '@/components/icons/IconTheatreOn.vue';
import IconCaptions from '@/components/icons/IconCaptions.vue';
import ProiconsPlay from '~icons/proicons/play';
import MagePlaylist from '~icons/mage/playlist';
import CircumTimer from '~icons/circum/timer';
import IconPause from '@/components/icons/IconPause.vue';

export type PlayerViewMode = 'normal' | 'theatre' | 'fullscreen';

/**
 * Z-Index Layout (lowest on list is in front)
 *
 * 1  → Audio Background Blur
 *
 * 3  → Video
 *     → Thumbnail or Album Art for Audio
 *
 * 4  → Controls Gradient
 *     → Title Gradient
 *     → Tap Controls
 *
 * 5  → Lyrics / Subtitles
 *     → Loading Icon
 *     → Play Icon
 *     → Pause Icon
 *
 * 6   → Title
 *      → Lyrics Top / Bottom Padding
 *       ↳ (Used to prevent overlap or accidental interaction
 *          with lyrics buttons at the top and bottom areas)
 *
 * 7  → Lyrics Preview / Edit Button
 *     → Player Controls
 *     → Timeline Buffer / Progress / Thumb / Input
 *     → Player Buttons (Play, Mute, FS, etc.)
 *     → Volume Slider
 *     → Watch Party Panel
 *     → Video Stats Panel
 *
 * 9  → Video Tooltip Slider (Timeline Tooltip)
 *
 * 10 → Video Popover (Settings, Sliders, etc.)
 *
 * 30 → Context Menu (Global overlay in fullscreen)
 */

const router = useRouter();
const route = useRoute();

let unSub: () => boolean; // Unsub from seek bus

const emit = defineEmits(['loadedData', 'seeked', 'play', 'pause', 'ended', 'loadedMetadata']);

// Global State
// So isAutoPlay determines if the video should auto start, and has no ui toggle
// But isPlaylist determines if should navigate to next video at the end of current video and has a ui toggle called Autoplay ????????????
const {
    contextMenuItems,
    contextMenuStyle,
    contextMenuItemStyle,
    playbackHeatmap,
    ambientMode,
    lightMode,
    isAutoPlay,
    isPlaylist,
    usingPlayerModernUI,
    isAudioGraphEnabled,
    showAutoSubtitles,
    showSeekButtons,
    showLyricsMetadata,
    useAmLyrics,
} = storeToRefs(useAppStore());
const { setContextMenu, closeContextMenu } = useAppStore();
const { updateViewCount } = useContentStore();
const { createRecord } = useRecord();

const { stateVideo, stateFolder, nextVideoURL, previousVideoURL } = storeToRefs(useContentStore());
const { userData } = storeToRefs(useAuthStore());

// API Cache
const progressCache = ref<{ metadata_id: number; progress: number }[]>([]);
const metadataId = ref<number>(Number.NaN);
const currentId = ref<number | null>(null);

// API
const { data: playbackData } = useVideoPlayback(metadataId);
const createPlayback = UseCreatePlayback().mutate;

// Playback Progress
const { startInterval: startProgressInterval, stopInterval: stopProgressInterval } = usePlaybackProgress(
    computed(() => (currentId.value ? metadataId.value : Number.NaN)),
    getCurrentTime,
);

// V-models for inputs
const timeDuration = computed(() => {
    return stateVideo.value?.metadata?.duration ?? 1;
});
const timeElapsed = ref(0); // Out of 100
const timeSeeking = ref('');
const timeSeekLeft = ref(0);
const timeSeekRight = ref(0);
const currentVolume = ref(0.5);
const cachedVolume = ref(0.5);
const currentSpeed = ref(1);

//#region Player State
const shouldUpdateUI = computed(() => (isShowingControls.value || isShowingStats.value) && !isScrubbing.value && !isLoading.value);

const latestPlayRequestId = ref<number>(0);
const controlsHideTimeout = ref<number>();
const volumeChangeTimeout = ref<number>();
const autoSeekTimeout = ref<number>();
const timeDisplay = ref<'timeElapsed' | 'timeRemaining'>('timeElapsed');

const isShowingAudioGraphSettings = ref(false);
const isPlayerSizeConstrained = computed(() => (isAudio.value || aspectRatio.value.isPortrait) && isNormalView.value); // Is size determined by album art or portrait video
const isThumbnailDismissed = ref(false);
const isPictureInPicture = ref(false);
const isShowingControls = ref(false);
const isLoadingMetadata = ref(false);
const isChangingVolume = ref(false);
const isShowingLyrics = ref(false);
const isShowingParty = ref(false);
const isShowingStats = ref(false);
const isMediaSession = ref(false);
const isScrubbing = ref(false);
const isLoading = ref(false);
const isLooping = ref(false);
const isPaused = ref(true);
const isMuted = ref(false);

const rewindTick = ref(0);
const fastForwardTick = ref(0);

const viewMode = ref<PlayerViewMode>('normal');

const isFullScreen = computed(() => viewMode.value == 'fullscreen');
const isTheatreView = computed(() => viewMode.value === 'theatre');
const isNormalView = computed(() => viewMode.value === 'normal');

const isThumbnailVisible = computed(() => !!posterUrl.value && !isThumbnailDismissed.value);

//#endregion

//#region Player Info
const endsAtTime = ref('00:00');
const bufferTime = ref<number>(0);
const bufferPercentage = ref<number>(0);
const frameHealth = ref<string>('0/0');
const playerHealthCounter = ref(0);
const bufferHealth = computed(() => {
    return toFormattedDuration(bufferTime.value, false) ?? '0s';
});

//#endregion

const videoButtonOffset = computed(() => {
    return 8 + (isNormalView.value ? 0 : 8);
});

const timeStrings = computed(() => {
    const timeElapsedVerbose = toFormattedDuration((timeElapsed.value / 100) * timeDuration.value, false, 'verbose') ?? 'Unknown';
    const timeDurationVerbose = toFormattedDuration(timeDuration.value, false, 'verbose') ?? 'Unknown';
    return {
        timeElapsed: toFormattedDuration((timeElapsed.value / 100) * timeDuration.value, true, 'digital') ?? '00:00',
        timeRemaining: '-' + (toFormattedDuration((1 - timeElapsed.value / 100) * timeDuration.value, true, 'digital') ?? '00:00'),
        timeDuration: toFormattedDuration(timeDuration.value, true, 'digital') ?? '00:00',
        timeVerbose: `${timeElapsedVerbose} out of ${timeDurationVerbose}`,
        timeElapsedVerbose,
    };
});

const keyBinds = computed(() => {
    let keys = {
        mute: ` (m)`,
        previous: ' (shift+p)',
        play: ' (k)',
        next: ' (shift+n)',
        theatre: ' (t)',
        fullscreen: ' (f)',
        lyrics: ' (c)',
        subtitles: ' (c)',
        backwards: ` (←)`,
        forwards: ` (→)`,
    };

    if (isMobileDevice()) {
        keys = {
            mute: ``,
            previous: '',
            play: '',
            next: '',
            theatre: '',
            fullscreen: '',
            lyrics: '',
            subtitles: '',
            forwards: '',
            backwards: '',
        };
    }

    return {
        mute: `${isMuted.value ? 'Unmute' : 'Mute'}${keys.mute}`,
        previous: `Play Previous${keys.previous}`,
        play: `${isPaused.value ? 'Play' : 'Pause'}${keys.play}`,
        next: `Play Next${keys.next}`,
        theatre: `${isTheatreView.value ? 'Exit Theatre Mode' : 'Theatre Mode'}${keys.theatre}`,
        fullscreen: `${isFullScreen.value ? 'Exit Full Screen' : 'Full Screen'}${keys.fullscreen}`,
        lyrics: `Toggle Lyrics ${keys.lyrics}`,
        subtitles: stateVideo.value.subtitles.length > 0 ? `Toggle Subtitles ${keys.lyrics}` : 'Subtitles',
        forwards: `Seek -10s ${keys.forwards}`,
        backwards: `Seek 10s ${keys.backwards}`,
    };
});

// Elements
const player = useTemplateRef('player');
const popover = useTemplateRef('player-popover');
const timeline = useTemplateRef('player-timeline');
const container = useTemplateRef('player-container');

const playerContextMenu = useTemplateRef('context-menu');
const playerLyrics = useTemplateRef('player-lyrics');
const playerSubtitles = useTemplateRef('player-subtitles');
const playerAudioTracks = useTemplateRef('player-audio-tracks');
const playerSpectrograph = useTemplateRef('player-spectrograph');

const progressTooltip = computed(() => timeline.value?.progressTooltip);

// const url = ref('');

const playerContextMenuItems = computed<ContextMenuItem[]>(() =>
    [
        {
            text: 'Loop',
            icon: isLooping.value ? ProiconsCheckmark : undefined,
            selected: isLooping.value,
            action: () => {
                isLooping.value = !isLooping.value;
            },
        },
        {
            text: 'Player Stats',
            icon: isShowingStats.value ? ProiconsCheckmark : undefined,
            selected: isShowingStats.value,
            action: () => {
                isShowingStats.value = !isShowingStats.value;
            },
        },
        {
            text: 'Watch Party',
            icon: isShowingParty.value ? ProiconsCheckmark : undefined,
            selected: isShowingParty.value,
            disabled: !userData.value?.id,
            action: () => {
                isShowingParty.value = !isShowingParty.value;
            },
        },
        {
            text: 'Transcript',
            icon: isShowingTranscript.value ? ProiconsCheckmark : undefined,
            selected: isShowingTranscript.value,
            selectedIcon: ProiconsCheckmark,
            hidden: isAudio.value,
            action: () => {
                isShowingTranscript.value = !isShowingTranscript.value;
            },
        },
        {
            text: 'Show Miniplayer',
            icon: isPictureInPicture.value ? ProiconsCheckmark : undefined,
            selected: isPictureInPicture.value,
            hidden: !document.pictureInPictureEnabled || isAudio.value,
            action: () => {
                if (isLoading.value) return;
                togglePictureInPicture();
            },
        },
        {
            text: 'Show Metadata',
            icon: showLyricsMetadata.value ? ProiconsCheckmark : undefined,
            selected: showLyricsMetadata.value,
            hidden: !(isAudio.value || stateFolder.value.is_majority_audio) || (showLyricsMetadata.value && !isShowingLyrics.value),
            disabled: !stateVideo.value.metadata?.poster_image?.path,
            action: () => {
                if (!showLyricsMetadata.value) isShowingLyrics.value = true;
                showLyricsMetadata.value = !showLyricsMetadata.value;
            },
        },
        {
            text: 'Use AM-Lyrics',
            icon: useAmLyrics.value ? ProiconsCheckmark : undefined,
            selected: useAmLyrics.value,
            hidden: !FLAGS.USE_AM_LYRICS || !isShowingLyrics.value || !(isAudio.value || stateFolder.value.is_majority_audio),
            action: () => {
                useAmLyrics.value = !useAmLyrics.value;
            },
        },
        {
            text: 'Audio Graph Menu',
            icon: isShowingAudioGraphSettings.value ? ProiconsCheckmark : undefined,
            selected: isShowingAudioGraphSettings.value,
            hidden: !isAudioGraphEnabled.value,
            action: () => {
                isShowingAudioGraphSettings.value = !isShowingAudioGraphSettings.value;
            },
        },
        {
            text: 'Save Frame',
            hidden: isAudio.value,
            action: () => {
                if (!player.value) return;
                saveVideoFrame(player.value);
            },
        },
        {
            text: 'Copy Frame',
            hidden: isAudio.value,
            action: () => {
                if (!player.value) return;
                copyVideoFrame(player.value);
            },
        },
    ].map((item) => ({ ...item, selectedStyle: '' })),
);

const videoPopoverItems = computed<PopoverItem[]>(() => [
    {
        text: 'Ambient Mode',
        title: 'Toggle Ambient Mode',
        icon: ProiconsSparkle2,
        selectedIcon: ProiconsCheckmark,
        selected: ambientMode.value,
        disabled: lightMode.value,
        action: () => {
            ambientMode.value = !ambientMode.value;
        },
    },
    {
        text: 'Heatmap',
        title: 'Toggle Playback Heatmap',
        icon: ProiconsArrowTrending,
        selectedIcon: ProiconsCheckmark,
        selected: playbackHeatmap.value,
        action: () => {
            playbackHeatmap.value = !playbackHeatmap.value;
        },
    },
    { divider: true },
    {
        text: 'Lyrics',
        title: `Toggle Lyrics`,
        icon: isShowingLyrics.value ? TablerMicrophone2 : TablerMicrophone2Off,
        iconStyle: `*:stroke-[1.4px]`,
        selectedIcon: ProiconsCheckmark,
        selected: isShowingLyrics.value,
        selectedIconStyle: 'stroke-none',
        disabled: getScreenSize() !== 'default' || (!isAudio.value && !stateFolder.value.is_majority_audio),
        action: () => {
            isShowingLyrics.value = !isShowingLyrics.value;
        },
    },
    {
        text: 'Autoplay',
        title: `Toggle autoplaying the next ${isAudio.value ? 'track' : 'video'}`,
        icon: MagePlaylist,
        selectedIcon: ProiconsCheckmark,
        selected: isPlaylist.value,
        action: handleToggleAutoplay,
    },
    {
        text: 'Transcript',
        title: `Toggle video transcript`,
        icon: ProiconsTextAlignLeft,
        selected: isShowingTranscript.value,
        selectedIcon: ProiconsCheckmark,
        disabled: isAudio.value,
        action: () => {
            isShowingTranscript.value = !isShowingTranscript.value;
        },
    },
    {
        text: 'Auto Subtitles',
        title: `Automatically select the default subtitle track`,
        icon: showAutoSubtitles.value ? IconCaptions : IconCaptionsOff,
        selectedIcon: ProiconsCheckmark,
        selected: showAutoSubtitles.value,
        action: () => (showAutoSubtitles.value = !showAutoSubtitles.value),
        disabled: isAudio.value,
    },
    { divider: true },
    {
        text: 'Audio Graph',
        title: 'Toggle Audio Visualiser',
        icon: IconSpectrograph,
        selectedIcon: ProiconsCheckmark,
        selected: isAudioGraphEnabled.value,
        action: () => {
            isAudioGraphEnabled.value = !isAudioGraphEnabled.value;
            if (!isAudioGraphEnabled.value) isShowingAudioGraphSettings.value = false;
        },
    },
    {
        text: 'Modern UI',
        title: `Toggle backgrounds on player controls`,
        icon: ProiconsTextHighlightColor,
        selectedIcon: ProiconsCheckmark,
        selected: usingPlayerModernUI.value,
        action: () => {
            usingPlayerModernUI.value = FLAGS.FORCE_MODERN_PLAYER_UI ? true : !usingPlayerModernUI.value;
        },
        disabled: FLAGS.FORCE_MODERN_PLAYER_UI,
    },
    {
        text: 'Miniplayer',
        title: 'Toggle Picture-in-picture',
        icon: isPictureInPicture.value ? ProiconsPictureInPictureExit : ProiconsPictureInPictureEnter,
        selectedIcon: ProiconsCheckmark,
        selected: isPictureInPicture.value,
        disabled: !document.pictureInPictureEnabled || isAudio.value,
        action: () => {
            if (isLoading.value) return;
            togglePictureInPicture();
        },
    },
]);

// Computed Player State

const isAudio = computed(() => {
    return stateVideo.value.metadata?.media_type === MediaType.AUDIO;
});

const aspectRatio = computed(() => {
    if (isAudio.value || !stateVideo.value.metadata?.resolution_width || !stateVideo.value.metadata?.resolution_height) return { isPortrait: false, isAspectVideo: false };

    const w = stateVideo.value.metadata.resolution_width;
    const h = stateVideo.value.metadata.resolution_height;
    return {
        isPortrait: stateVideo.value.metadata.resolution_width < stateVideo.value.metadata.resolution_height,
        isAspectVideo: Math.abs(w / h - 16 / 9) < 0.01,
    };
});

const audioPoster = computed(() => {
    return (
        stateVideo.value.metadata?.poster_image?.path ??
        stateFolder.value.series?.poster_image?.path ??
        handleStorageURL(stateFolder.value.series?.thumbnail_url) ??
        '/storage/thumbnails/default.webp'
    );
});

const posterUrl = computed(() => {
    const url = stateVideo.value.metadata?.poster_image?.path;
    const audioFallback = stateFolder.value.series?.poster_image?.path ?? handleStorageURL(stateFolder.value.series?.thumbnail_url) ?? '/storage/thumbnails/default.webp';

    return isAudio.value ? (url ?? audioFallback) : url;
});

const initVideoPlayer = async (previousId: number) => {
    if (stateVideo.value.id === currentId.value || stateVideo.value.id === previousId) {
        // Only reset metadata on statevideo update if id is the same
        initBrowserMetadata();
        return;
    }

    const root = document.getElementById('root');

    if (isPictureInPicture.value) {
        isPictureInPicture.value = false;
        togglePictureInPicture();
    }

    if (playerSubtitles.value && playerSubtitles.value.defaultSubtitleTrack && showAutoSubtitles.value)
        playerSubtitles.value.handleSubtitles(playerSubtitles.value.defaultSubtitleTrack); // Select default track on init if exists
    else playerSubtitles.value?.clearSubtitles(); // Otherwise clear

    isLooping.value = false;
    currentSpeed.value = 1;
    currentId.value = null;
    isThumbnailDismissed.value = false;
    isLoadingMetadata.value = true;

    resetPlayerInfo();

    timeElapsed.value = 0; // HOTFIX: I do not know why this wasn't here already but if a video is changed before the previous one loaded, the time is not reset
    if (!root) return;

    root.scrollIntoView();

    if (progressCache.value && progressCache.value.length > 0) {
        createPlayback({ entries: progressCache.value });
        progressCache.value = [];
    }

    metadataId.value = stateVideo.value?.metadata ? stateVideo.value?.metadata.id : NaN;

    initBrowserMetadata();

    if (!isFullScreen.value && !isAutoPlay.value) {
        onPlayerPause();
        debouncedEndTime(); // Generate end time on video change
        return;
    }

    await nextTick();

    onPlayerPlay();
    // url.value = await getMediaUrl(stateVideo.value.path ?? '');
};

const initBrowserMetadata = () => {
    handleInitMediaSession();
    addJsonLd();
};

const handleInitMediaSession = () => {
    navigator.mediaSession.metadata = null;

    if (!isMediaSession.value || Number.isNaN(metadataId.value)) return;

    // This uses series image unlike the regular posterUrl
    // TODO: Fix
    const artworkURL = posterUrl.value ?? handleStorageURL(stateFolder.value.series?.thumbnail_url) ?? new URL('/storage/thumbnails/default.webp', globalThis.location.origin).href;

    const studioName = stateVideo.value.metadata?.artist ?? stateFolder.value?.series?.studio;
    const folderName = stateVideo.value.metadata?.album ?? stateFolder.value.series?.title ?? stateFolder.value.name;
    const artist = `${studioName ? studioName + ' · ' : ''}${folderName}`; //OLD CODE: (studioName ? `${studioName} · ${folderName}` : null) || (isAudio.value ? folderName : null);

    const newMediaSession = new MediaMetadata({
        title: stateVideo.value.metadata?.title || stateVideo.value.name,
        artist: artist || 'Unknown Artist', // Unknown artist should never happen with this logic
        album: folderName || 'Unknown Album',
        artwork: [
            { src: artworkURL, sizes: '128x128', type: 'image/webp' },
            { src: artworkURL, sizes: '256x256', type: 'image/webp' },
            { src: artworkURL, sizes: '512x512', type: 'image/webp' },
        ],
    });
    navigator.mediaSession.metadata = newMediaSession;
};

//#region Player Events

// Could use a rename -> this is for the playback heatmap, not playback progress (new as of 2026-04)
const handleProgress = (override = false) => {
    if (!player.value || !stateVideo.value.metadata?.id) return;

    const progress = player.value.currentTime / player.value.duration;

    if (Number.isNaN(progress) || !progress) return;

    progressCache.value = [...progressCache.value, { metadata_id: stateVideo.value?.metadata?.id, progress: Number.parseFloat(progress.toFixed(2)) * 1000 }];

    if (progressCache.value.length >= playbackDataBuffer || override) {
        createPlayback({ entries: progressCache.value });
        progressCache.value = [];
    }
};

/**
 * Handle On Play
 *
 * If the player is not paused, pause the player and return.
 *
 * Otherwise, play the player.
 * Generate end time.
 * Emit 'play' event.
 *
 * If this is the first time the player has played this video or if override is set...
 * Record video progress and force publish it, ignoring the buffer.
 * Create a history record.
 * Update video view count.
 *
 * Otherwise, record video progress and quit.
 * @param override force first time playback of video.
 */
const onPlayerPlay = async (override = false, recordProgress = true) => {
    if (!player.value || !stateVideo.value.id) return;

    /* if (isLoading.value) {
        const description = stateVideo.value.metadata?.codec ? ` Make sure your browser supports the format "${stateVideo.value.metadata.codec}"` : '';
        toast.warning(`Content still loading...`, {
            description,
        });
        onPlayerPause();
        return;
    } */
    const playRequestId = ++latestPlayRequestId.value;
    try {
        isAutoPlay.value = false;
        isLoading.value = true;
        await player.value.play();

        if (playRequestId !== latestPlayRequestId.value) return;

        isLoading.value = false;
        // Set isPaused to false?
        emit('loadedData');
        emit('play');

        if (isShowingControls.value) resetControlsTimeout();

        if (!recordProgress) return;

        if (currentId.value === stateVideo.value.id && !override) {
            startProgressInterval();
            handleProgress();
            return; // stop recording every time video seek
        }

        currentId.value = stateVideo.value.id;
        createRecord.mutate({ video_id: stateVideo.value.id });
        isThumbnailDismissed.value = true;
        updateViewCount(stateVideo.value.id);
        handleProgress(true);
        startProgressInterval();
        getEndTime();

        if (isMediaSession.value) navigator.mediaSession.playbackState = 'playing';
    } catch (error) {
        if ((error instanceof DOMException && error.name === 'AbortError') || playRequestId !== latestPlayRequestId.value) {
            return;
        }

        toast.error('Error playing content...', { description: `${error ?? ''}` });
        isLoading.value = false;
        console.error(error);
    }
};

const onPlayerPause = () => {
    if (!player.value) return;

    latestPlayRequestId.value++;
    player.value.pause();

    stopProgressInterval(); // stop interval that records playback progress on player pause and player end but not on loop or playlist

    if (!isPaused.value) isPaused.value = true;
    emit('pause');

    if (isMediaSession.value) navigator.mediaSession.playbackState = 'paused';
};

const onPlayerEnded = () => {
    currentId.value = null;
    if (isLooping.value) {
        onPlayerPlay();
        return;
    }

    emit('ended');

    if (isPlaylist.value) {
        handleNext(true);
        return;
    }

    onPlayerPause();
};

const onPlayerLoadStart = () => {
    if (isLoading.value || !stateVideo.value?.path) return;
    isLoading.value = true;
};

const onPlayerLoadeddata = () => {
    if (!stateVideo.value || !player.value) return;
    if (stateVideo.value.metadata && !stateVideo.value.metadata.duration && !isNaN(player.value.duration)) {
        stateVideo.value.metadata.duration = player.value.duration ?? 0;
        timeElapsed.value = 0;
    }

    isLoadingMetadata.value = false;

    handleLoadUrlTime();
    isLoading.value = false;
    emit('loadedData');
    emit('loadedMetadata');
};

const onPlayerWaiting = () => {
    if (player.value?.loop) {
        createRecord.mutate({ video_id: stateVideo.value.id });
        updateViewCount(stateVideo.value.id);
        handleProgress(true);
    }
};

const cacheVolume = () => {
    if (!player.value) return;
    localStorage.setItem('videoVolume', currentVolume.value.toString());
};

//#endregion

const debouncedCacheVolume = debounce(cacheVolume, 300);

const handleVolumeChange = (dir: number = 0) => {
    if (!player.value) return;

    isChangingVolume.value = false;

    if (dir) {
        currentVolume.value = round(Math.max(Math.min(parseFloat(`${currentVolume.value}`) + volumeDelta * dir, 1), 0), 2);
    }

    player.value.volume = currentVolume.value;

    if (currentVolume.value === 0) isMuted.value = true;
    else isMuted.value = false;
    debouncedCacheVolume();

    if (volumeChangeTimeout.value) clearTimeout(volumeChangeTimeout.value);
    volumeChangeTimeout.value = globalThis.setTimeout(() => {
        isChangingVolume.value = true;
    }, 100);
};

const handleVolumeWheel = (event: WheelEvent) => {
    if (!player.value) return;
    event.preventDefault();

    handleVolumeChange(event.deltaY < 0 ? 1 : -1);
};

const handleSpeedChange = (_: Event, dir: number = 0) => {
    if (!player.value) return;

    if (dir) {
        currentSpeed.value = round(Math.max(Math.min(parseFloat(`${currentSpeed.value}`) + playbackDelta * dir, playbackMax), playbackMin), 2);
    }

    player.value.playbackRate = currentSpeed.value;
    return true;
};

const handleSpeedWheel = (event: WheelEvent) => {
    if (!player.value) return;
    event.preventDefault();

    handleSpeedChange(new Event('SpeedChange'), event.deltaY < 0 ? 1 : -1);
};

const handleMute = () => {
    if (!player.value) return;

    if (isMuted.value) {
        currentVolume.value = cachedVolume.value;
        player.value.volume = cachedVolume.value;
    } else if (!isMuted.value) {
        cachedVolume.value = currentVolume.value;
        currentVolume.value = 0;
        player.value.volume = 0;
    }

    isMuted.value = !isMuted.value;
};

const handlePlayerToggle = () => {
    if (isPaused.value) {
        onPlayerPlay();
        return;
    }

    onPlayerPause();
};

function handleAutoSeek(seconds: number) {
    if (!player.value) return;

    const newTimeElapsed = Math.min(Math.max(player.value.currentTime + seconds, 0), timeDuration.value);

    player.value.currentTime = newTimeElapsed;
    timeElapsed.value = (newTimeElapsed / timeDuration.value) * 100;

    if (!isPaused.value) onPlayerPlay(false, false);
    else if (!currentId.value) isThumbnailDismissed.value = true;

    if (autoSeekTimeout.value) clearTimeout(autoSeekTimeout.value);
    autoSeekTimeout.value = globalThis.setTimeout(() => {
        if (seconds > 0) {
            timeSeekRight.value += seconds;
            fastForwardTick.value++;
            rewindTick.value = 0;
        } else {
            timeSeekLeft.value += seconds;
            rewindTick.value++;
            fastForwardTick.value = 0;
        }
    }, 100);
}

const handleLyrics = () => {
    isShowingLyrics.value = !isShowingLyrics.value;
};

const cycleViewMode = async (mode: PlayerViewMode) => {
    if (!container.value) return;
    switch (mode) {
        case 'fullscreen':
            if (viewMode.value === 'fullscreen') break;
            if (isPictureInPicture.value) await togglePictureInPicture();
            if (document.fullscreenElement === null) await container.value.requestFullscreen();
            if (!isAudio.value && 'lock' in screen.orientation) screen.orientation.lock('landscape').catch(() => {});
            viewMode.value = 'fullscreen';
            document.documentElement.classList.add('fullscreen');
            break;
        case 'theatre':
            viewMode.value = 'theatre';
            break;
        default:
            if (document.fullscreenElement !== null) await document.exitFullscreen();
            document.documentElement.classList.remove('fullscreen');
            (screen.orientation as ScreenOrientation).unlock?.();
            viewMode.value = 'normal';
            break;
    }

    if (playerContextMenu.value?.contextMenuOpen) playerContextMenu.value?.contextMenuToggle();
    closeContextMenu();
};

const handleTheatre = () => {
    cycleViewMode(isNormalView.value ? 'theatre' : 'normal');
};

const handleFullScreen = async () => {
    if (!container.value) return;
    try {
        if (!isFullScreen.value || document.fullscreenElement === null) {
            cycleViewMode('fullscreen');
        } else {
            cycleViewMode('normal');
        }
    } catch (error) {
        document.documentElement.classList.remove('fullscreen');
        toast.error('Unable to switch fullscreen mode...');
        console.log(error);
    }
};

const handleFullScreenChange = (e: Event) => {
    // Should this do anything? its an uncontrolled side effect? viewmode should only change in a single function?
    // This handles other events like picture in picture exiting fullscreen without a button press
    // viewMode.value = document.fullscreenElement !== null ? 'fullscreen' : 'normal';
    cycleViewMode(document.fullscreenElement === null ? 'normal' : 'fullscreen');
};

const handleVisibilityChange = () => {
    // Firefox Android doesn't reliably fire `fullscreenchange`
    if (document.visibilityState === 'visible' && isFullScreen.value && document.fullscreenElement === null) {
        cycleViewMode('normal');
    }
};

/** Main UI Stack
 *
 * Triggers when not scrubbing and not loading and showing controls
 *
 * Calls getBufferHealth()
 *      -> Calls getPlayerInfo()
 *          -> Updates bufferTime and bufferPercentage based on time elapsed
 *              -> Triggers update to buffer bar
 *          -> Updates framehealth
 * Updates timeElapsed
 *      -> Triggers a whole load of stuff
 */
const handlePlayerTimeUpdate = (event: any) => {
    // update time if showing controls or showing stats, or paused, or not seeking
    if (!shouldUpdateUI.value) return;
    getBufferHealth();

    // if playing or have not started playing yet, force seek (I do not remember what this is for)
    if (isShowingControls.value && (!isPaused.value || currentId.value === null)) {
        timeElapsed.value = (event.target.currentTime / timeDuration.value) * 100;
    }
};

function getCurrentTime() {
    return player.value?.currentTime ?? 0;
}

//#region Seek

const handleManualSeek = async (seconds: number) => {
    if (!player.value) return;

    seconds = Math.min(Math.max(seconds, 0), timeDuration.value);

    timeElapsed.value = (seconds / timeDuration.value) * 100;

    handleSeek(seconds);
};

const handleSeek = (seconds?: number) => {
    if (!player.value || timeElapsed.value < 0 || timeElapsed.value > 100) return;

    if (!currentId.value) isThumbnailDismissed.value = true;

    isScrubbing.value = false;
    isLoading.value = true;
    player.value.currentTime = seconds ?? (timeElapsed.value / 100) * timeDuration.value;
};

const onSeeked = () => {
    debouncedEndTime();
    emit('seeked');
    getPlayerInfo();
    if (isPaused.value) {
        isLoading.value = false;
        return;
    }
    onPlayerPlay();
};

const handleSeekPreview = () => {
    if (!player.value || isScrubbing.value) return;
    if (!isScrubbing.value) isScrubbing.value = true;
};

//#endregion

function resetControlsTimeout() {
    isShowingControls.value = true;

    clearTimeout(controlsHideTimeout.value);
    controlsHideTimeout.value = globalThis.setTimeout(handleControlsTimeout, controlsHideTime);
}

function handleControlsTimeout() {
    if (isPaused.value || popover.value?.popoverOpen || playerSubtitles.value?.subtitlesPopover?.popoverOpen || playerAudioTracks.value?.audioTracksPopover?.popoverOpen) return;
    if (controlsHideTimeout.value) clearTimeout(controlsHideTimeout.value);

    isShowingControls.value = false;
    popover.value?.handleClose();
    progressTooltip.value?.hide();
}

const debouncedEndTime = debounce(getEndTime, 100);

function playerMouseActivity(_: any) {
    if (!isPaused.value) {
        resetControlsTimeout();
        return;
    }

    debouncedEndTime();

    if (!controlsHideTimeout.value && isShowingControls.value) return;

    isShowingControls.value = true;
    clearTimeout(controlsHideTimeout.value);
}

function getEndTime() {
    const timeDelta = (timeDuration.value - (timeElapsed.value / 100) * timeDuration.value) * 1000;
    if (!player.value || !stateVideo.value?.id || isNaN(timeDelta)) {
        return;
    }
    endsAtTime.value = toFormattedDate(new Date(new Date().getTime() + timeDelta), true, {
        hour: '2-digit',
        minute: '2-digit',
        hour12: true,
    });
}

// Buffers getting player information for the stats panel and the buffer bar
function getBufferHealth() {
    playerHealthCounter.value += 1;

    if (playerHealthCounter.value >= playerHealthBuffer) {
        getPlayerInfo();
        playerHealthCounter.value = 0;
    }
}

// Gets playback information for the stats panel and updates the buffer bar
function getPlayerInfo() {
    if (!player.value) return;

    const playbackQuality = player.value.getVideoPlaybackQuality();
    const currentTime = player.value.currentTime;
    const buffered = player.value.buffered;

    let bufferedSeconds = 0;

    for (let i = 0; i < buffered.length; i++) {
        if (buffered.start(i) <= currentTime && currentTime <= buffered.end(i)) {
            bufferedSeconds = buffered.end(i) - currentTime;
            break;
        }
    }

    bufferTime.value = bufferedSeconds;
    bufferPercentage.value = (bufferedSeconds / timeDuration.value) * 100 + timeElapsed.value;
    frameHealth.value = playbackQuality && playbackQuality.totalVideoFrames > 0 ? `${playbackQuality.droppedVideoFrames} / ${playbackQuality.totalVideoFrames}` : 'N/A';
}

function resetPlayerInfo() {
    bufferPercentage.value = 0;
    bufferTime.value = 0;
    frameHealth.value = '0/0';
}

const handleLoadSavedVolume = () => {
    const savedVolume = parseFloat(localStorage.getItem('videoVolume') ?? '');
    if (Number.isNaN(savedVolume) || !player.value) {
        handleVolumeChange();
        return;
    }

    const normalVolume = Math.max(0, Math.min(savedVolume, 1));
    currentVolume.value = normalVolume;
    player.value.volume = normalVolume;

    if (normalVolume === 0) isMuted.value = true;
};

const handleLoadUrlTime = async () => {
    if (!route.query.t) return;
    const seconds = Number.parseInt(route.query.t.toString());
    handleManualSeek(seconds);
};

const handleNext = (useAutoPlay = isAudio.value || (!!isPlaylist.value && !isPaused.value)) => {
    if (!nextVideoURL.value) {
        toast('Reached end of playlist');
        return;
    }
    isAutoPlay.value = useAutoPlay;
    router.push(nextVideoURL.value);
};

const handlePrevious = (useAutoPlay = isAudio.value || (!!isPlaylist.value && !isPaused.value)) => {
    if (!previousVideoURL.value) {
        toast('Reached start of playlist');
        return;
    }
    isAutoPlay.value = useAutoPlay;
    router.push(previousVideoURL.value);
};

/**
 * Media key handler for playing and pausing the player.
 * @param explicitAction depending on the source (keybind or media session) explictly play / pause or simply toggle
 */
const handlePlayPause = (explicitAction?: 'play' | 'pause') => {
    if (explicitAction === 'play') onPlayerPlay();
    else if (explicitAction === 'pause') onPlayerPause();
    else handlePlayerToggle();
};

const handleToggleAutoplay = () => {
    isPlaylist.value = !isPlaylist.value;
    const mediaType = stateFolder.value.is_majority_audio ? 'track' : 'video';
    const description = isPlaylist.value ? `Will autoplay the next ${mediaType}.` : `Will not autoplay ${mediaType}s.`;
    toast(`Autoplay ${isPlaylist.value ? 'Enabled' : 'Disabled'}`, { description });
};

//#region Keybinds and MediaSession (semi-coupled)

// Debounced actions shared by keybinds and media session action handlers
const debouncedHandleNext = debounce(handleNext, 50, { leading: true, trailing: false });
const debouncedHandlePrevious = debounce(handlePrevious, 50, { leading: true, trailing: false });
const debouncedHandlePlayPause = debounce(handlePlayPause, 50, { leading: true, trailing: false });

const SUPPORTED_KEYBINDS = [
    'ArrowLeft',
    'ArrowRight',
    'ArrowUp',
    'ArrowDown',
    'l',
    'N',
    'P',
    'p',
    'j',
    'k',
    'm',
    'c',
    ' ',
    'f',
    't',
    'Escape',
    'MediaTrackNext',
    'MediaTrackPrevious',
    'MediaPlayPause',
] as const;

type SupportedKeyBind = (typeof SUPPORTED_KEYBINDS)[number];

const handleKeyBinds = (event: KeyboardEvent, override = false) => {
    if (!SUPPORTED_KEYBINDS.includes(event.key as SupportedKeyBind)) return;
    if (isInputLikeElement(event.target, event.key) && !override) return;
    if (event.ctrlKey) return;

    const key = event.key as SupportedKeyBind;

    switch (key) {
        case 'ArrowLeft':
        case 'j':
            handleAutoSeek(event.shiftKey ? -5 : -10);
            break;
        case 'ArrowRight':
        case 'l':
            handleAutoSeek(event.shiftKey ? 5 : 10);
            break;
        case 'N':
            if (!event.shiftKey) return;
            handleNext();
            break;
        case 'p':
        case 'P':
            if (!event.shiftKey) {
                handleToggleAutoplay(); // Toggle playlist/autoplay with P
                break;
            }
            handlePrevious();
            break;
        case 'm':
            handleMute();
            break;
        case 'c':
            if (isAudio.value || stateFolder.value.is_majority_audio) handleLyrics();
            else playerSubtitles.value?.handleSubtitles();
            break;
        case 'f':
            handleFullScreen();
            break;
        case 't':
            handleTheatre();
            break;
        case 'Escape':
            if (isTheatreView.value) handleTheatre();
            break;
        case 'ArrowUp':
            event.preventDefault();
            handleVolumeWheel(new WheelEvent('wheel', { deltaY: -1 }));
            break;
        case 'ArrowDown':
            event.preventDefault();
            handleVolumeWheel(new WheelEvent('wheel', { deltaY: 1 }));
            break;
        case 'k':
        case ' ':
        case 'MediaPlayPause':
            event.preventDefault();
            debouncedHandlePlayPause();
            break;
        case 'MediaTrackNext':
            event.preventDefault();
            debouncedHandleNext();
            break;
        case 'MediaTrackPrevious':
            event.preventDefault();
            debouncedHandlePrevious();
            break;
        default:
            break;
    }
};

const handleMediaSessionEvents = () => {
    if (!('mediaSession' in navigator)) {
        console.warn('Media Session API is not supported in this browser.');
        isMediaSession.value = false;
        return;
    }
    isMediaSession.value = true;
    navigator.mediaSession.setActionHandler('play', () => {
        debouncedHandlePlayPause('play');
    });

    navigator.mediaSession.setActionHandler('pause', () => {
        debouncedHandlePlayPause('pause');
    });

    navigator.mediaSession.setActionHandler('seekbackward', () => {
        handleAutoSeek(-10);
    });

    navigator.mediaSession.setActionHandler('seekforward', () => {
        handleAutoSeek(10);
    });

    navigator.mediaSession.setActionHandler('previoustrack', () => {
        debouncedHandlePrevious();
    });

    navigator.mediaSession.setActionHandler('nexttrack', () => {
        debouncedHandleNext();
    });

    navigator.mediaSession.setActionHandler('seekto', (details: MediaSessionActionDetails) => {
        if (!details.seekTime) return;
        handleManualSeek(details.seekTime);
    });
};

//#endregion

//#region PictureInPicture

const togglePictureInPicture = async () => {
    if (!player.value || isLoading.value) return;

    try {
        if (document.pictureInPictureElement) {
            await document.exitPictureInPicture();
        } else {
            await player.value!.requestPictureInPicture();
        }

        popover.value?.handleClose();
    } catch (error) {
        console.error(error);
        toast.error('Unable to toggle miniplayer');
    }
};

// Toggles PIP mode when triggered via native browser buttons. Needs to prevent default because the water for the PIP state manually sets PIP mode.
const enterPictureInPicture = (e?: Event) => {
    e?.preventDefault();
    isPictureInPicture.value = true;
};

// Does not need to prevent default because the watcher exits PIP mode conditionally
const leavePictureInPicture = (e: Event) => {
    isPictureInPicture.value = false;
};

//#endregion

const stopScrub = () => {
    isScrubbing.value = false;
};

//#region Experiments

const addJsonLd = () => {
    const existingData = document.getElementById('mal-sync-jsonld');
    if (existingData) {
        existingData.remove();
    }

    if (stateVideo.value.metadata?.media_type === MediaType.AUDIO) return;

    const script = document.createElement('script');
    script.id = 'mal-sync-jsonld';
    script.type = 'application/ld+json';

    const jsonLd = {
        title: stateFolder.value.title ?? stateFolder.value.name,
        season: stateVideo.value.season ?? 1,
        episode: stateVideo.value.episode ?? 1,
        name: `Episode ${stateVideo.value.episode}`,
        page: 'episode',
        metadataId: metadataId.value,
    };

    script.textContent = JSON.stringify(jsonLd);
    document.head.appendChild(script);
};

//#endregion

//#region Transcript

const { isShowingTranscript, placement: transcriptPlacement, registerTranscriptContext, unregisterTranscriptContext } = useTranscript();

registerTranscriptContext({
    player,
    viewMode,
    subtitleTrack: computed(() => playerSubtitles.value?.currentSubtitleTrack ?? playerSubtitles.value?.defaultSubtitleTrack),
    metadataId: computed(() => stateVideo.value.metadata?.id),
    seek: handleManualSeek,
    close: () => (isShowingTranscript.value = false),
    generated: (track) => stateVideo.value.subtitles.push(track),
});

//#endregion

//#region Hooks

provide('player', player);
provide('isAudio', isAudio);

watch(stateVideo, (_, old) => {
    initVideoPlayer(old.id);
});

watch(isShowingControls, async (visible) => {
    if (!visible || !shouldUpdateUI.value || !player.value) return;
    handlePlayerTimeUpdate({ target: player.value });
    await nextTick();
});

// Must reposition subtitles when player changes from absolute to static
watch([isThumbnailVisible, viewMode], async () => {
    await nextTick();
    playerSubtitles.value?.resizeOctopus(); // This doesn't fix the issue. It is a bug with the version of subtitlesOctopus I use
});

watch(
    () => [route.query.t, route.query.video],
    async (value, old) => {
        if (isLoadingMetadata.value) return;

        if (value[1] === old[1]) {
            // if time changes but video id does not change
            handleLoadUrlTime();
        }
    },
    { immediate: false },
);

onMounted(() => {
    if (document.pictureInPictureElement) document.exitPictureInPicture();
    handleLoadSavedVolume();
    handleMediaSessionEvents();
    globalThis.addEventListener('keydown', handleKeyBinds);
    document.addEventListener('fullscreenchange', handleFullScreenChange);
    document.addEventListener('visibilitychange', handleVisibilityChange);
    globalThis.addEventListener('pointerup', stopScrub);
    globalThis.addEventListener('contextmenu', stopScrub);
    unSub = onSeek(handleManualSeek);
});

onBeforeUnmount(() => {
    globalThis.removeEventListener('pointerup', stopScrub);
    globalThis.removeEventListener('contextmenu', stopScrub);
    globalThis.removeEventListener('keydown', handleKeyBinds);
    document.removeEventListener('fullscreenchange', handleFullScreenChange);
    document.removeEventListener('visibilitychange', handleVisibilityChange);

    unregisterTranscriptContext();

    isShowingTranscript.value = false;

    if (unSub) unSub();

    debouncedCacheVolume.cancel();
});

defineExpose({
    isAudio,
    isPictureInPicture,
    audioPoster,
    viewMode,
    getCurrentTime,
});
//#endregion
</script>

<template>
    <div :class="['transition-overlay pointer-events-none', { active: isTheatreView }]" />
    <div v-if="isTheatreView" class="pointer-events-none aspect-video w-full rounded-lg bg-black/30" />
    <div
        :class="
            cn(
                'relative overflow-clip',
                'text-xs',
                {
                    'theatre-mode player-transition animate-theatre-enter': isTheatreView,
                    'rounded-lg': isNormalView,
                    'rounded-sm': isFullScreen,
                },
                isShowingControls ? 'cursor-auto' : 'cursor-none!',
            )
        "
        :style="{
            '--subtitles-z-index': isThumbnailDismissed ? 5 : 3,
        }"
        ref="player-container"
        id="player-container"
        @mousemove="playerMouseActivity"
        @touchmove="playerMouseActivity"
        @mouseleave="handleControlsTimeout"
        @focusin="playerMouseActivity"
        @contextmenu="
            (e: any) => {
                setContextMenu(e, { items: playerContextMenuItems }, isNormalView);
                if (!isNormalView) {
                    playerContextMenu?.contextMenuToggle(e, true);
                }
            }
        "
    >
        <!-- Player and Thumbnail (Z-3)-->
        <div
            :class="[
                'z-3 flex size-full justify-center',
                { 'aspect-video bg-black': !stateVideo.path || (isLoadingMetadata && !isAudio) }, // Default size before load is possible
            ]"
        >
            <video
                id="video-source"
                ref="player"
                type="video/mp4"
                preload="metadata"
                aria-describedby="Play/Pause"
                controlsList="nodownload"
                :style="{ '--subtitle-font-multiplier': playerSubtitles?.subtitleSizeMultiplier ?? 1 }"
                :class="
                    cn(
                        `absolute size-full object-contain select-none focus:outline-hidden`,
                        { 'static z-3': !isAudio && (!posterUrl || (posterUrl && isThumbnailDismissed)) }, // Force position if no poster exists
                        { 'bg-black': !isAudio && !aspectRatio.isAspectVideo }, // Black bg when video does not fill aspect-video
                        isPlayerSizeConstrained ? 'max-h-[71vh]' : 'aspect-video', // Force 16:9 for all non portrait video (reduces cls and uncertainty)
                        isFullScreen || isTheatreView
                            ? '[--subtitle-cue-size:1.2rem] [--subtitle-font-size:180%]'
                            : '[--subtitle-cue-size:0.8em] [--subtitle-font-size:100%] sm:[--subtitle-font-size:136%]',
                        '[--subtitle-bottom-offset:0.5em]',
                        { '[--subtitle-bottom-offset:3em] sm:[--subtitle-bottom-offset:2em]': isShowingControls },
                    )
                "
                :src="stateVideo?.path ? '/' + stateVideo.path.split('/').map(encodeURIComponent).join('/') : undefined"
                @play="isPaused = false"
                @pause="isPaused = true"
                @ended="onPlayerEnded"
                @loadstart="onPlayerLoadStart"
                @loadedmetadata="onPlayerLoadeddata"
                @seeked="onSeeked"
                @waiting="onPlayerWaiting"
                @timeupdate="handlePlayerTimeUpdate"
                @click="handlePlayerToggle"
                @enterpictureinpicture="enterPictureInPicture"
                @leavepictureinpicture="leavePictureInPicture"
            >
                <track
                    v-if="playerSubtitles?.currentSubtitleTrack?.codec !== 'ass'"
                    kind="captions"
                    :label="playerSubtitles?.currentSubtitleTrack?.language ?? 'und'"
                    :srclang="playerSubtitles?.currentSubtitleTrack?.language ?? 'und'"
                    :src="playerSubtitles?.currentSubtitleTrackUrl"
                />
                Your browser does not support the video tag.
            </video>
            <!-- The thumbnail or blurred copy of the album art as a backdrop to the clear art (Z-3) -->
            <PlayerBackdrop
                :aspect-ratio="aspectRatio"
                :poster-url="posterUrl"
                :is-visible="isAudio || isThumbnailVisible"
                :is-showing-lyrics="isShowingLyrics"
                :is-normal-view="isNormalView"
                :is-theatre-view="isTheatreView"
                :is-player-size-constrained="isPlayerSizeConstrained"
            />
        </div>

        <!-- UI Layers -->

        <!-- Increases video sharpness on edge somehow-->
        <div class="pointer-events-none absolute inset-0 backdrop-blur-[0px]" style="z-index: 3" v-show="!isFullScreen" />

        <!-- UI Toolbar Z-10 (Title, Toolbar Buttons) -->
        <div style="z-index: 10" :class="cn('ui-layer inset-0 top-2 mx-2 flex h-5 items-center gap-1', { 'top-0 mx-4 h-11': isFullScreen || isTheatreView })">
            <h2 v-show="isShowingControls && (isFullScreen || isTheatreView)" :class="'pointer-events-auto line-clamp-1 text-xl drop-shadow-md transition-colors'">
                {{ stateVideo.title }}
            </h2>
            <span class="pointer-events-auto ml-auto flex h-5 max-w-2/5 shrink-0 flex-wrap items-center justify-end gap-1 overflow-y-hidden" id="player-toolbar"></span>
        </div>

        <!-- OSD Z-9 -->
        <div :class="['ui-layer inset-0 flex flex-col select-none', { 'text-sm': !isNormalView }]" style="z-index: 9">
            <!-- Volume -->
            <div :class="cn('absolute top-4 right-0 left-0 flex justify-center', { 'top-12 sm:top-20': !isNormalView })">
                <PlayerOSDTimer
                    :is-triggered="isChangingVolume"
                    class="flex items-center justify-center gap-1 bg-black/60 p-1 px-2 ps-2.5 text-center tabular-nums drop-shadow-lg"
                    :component="PlayerOSDBase"
                >
                    <ProiconsVolume v-if="currentVolume > 0.3" class="size-4" />
                    <ProiconsVolumeLow v-else-if="currentVolume > 0" class="size-4" />
                    <ProiconsVolumeMute v-else class="size-4" />
                    {{ Math.round(currentVolume * 100) }}%
                </PlayerOSDTimer>
            </div>

            <!-- Seek -->
            <div class="absolute top-0 left-0 flex h-full w-1/4 flex-col items-center justify-center gap-1">
                <PlayerOSDTimer :is-triggered="rewindTick" :hide-on-false="true" :duration="2000" class="flex flex-col items-center gap-1" @on-hide="timeSeekLeft = 0">
                    <PlayerOSDBase class="aspect-square w-fit">
                        <ProiconsReverse class="size-6" />
                    </PlayerOSDBase>
                    <PlayerOSDBase class="px-2 py-1 ps-2.5 text-center">
                        <span :key="timeSeekLeft" class="animate-pop inline-block tabular-nums">{{ Math.round(timeSeekLeft) }}s</span>
                    </PlayerOSDBase>
                </PlayerOSDTimer>
            </div>
            <div class="absolute top-0 right-0 flex h-full w-1/4 flex-col items-center justify-center gap-1">
                <PlayerOSDTimer :is-triggered="fastForwardTick" :hide-on-false="true" :duration="2000" class="flex flex-col items-center gap-1" @on-hide="timeSeekRight = 0">
                    <PlayerOSDBase class="aspect-square w-fit">
                        <ProiconsFastForward class="size-6" />
                    </PlayerOSDBase>
                    <PlayerOSDBase class="px-2 py-1 ps-2.5 text-center">
                        <span :key="timeSeekRight" class="animate-pop inline-block tabular-nums">+{{ Math.round(timeSeekRight) }}s</span>
                    </PlayerOSDBase>
                </PlayerOSDTimer>
            </div>

            <div v-show="isLoading" class="absolute inset-0 flex items-center justify-center">
                <ProiconsSpinner class="size-8 animate-spin" />
            </div>

            <!-- Play Icon -->
            <div class="absolute inset-0 flex items-center justify-center">
                <PlayerOSDTimer
                    class="aspect-square bg-black/60 drop-shadow-lg"
                    :enter-active="'ease-out duration-300'"
                    :is-triggered="isPaused && currentId !== null"
                    :hide-on-false="true"
                    :duration="700"
                    :component="PlayerOSDBase"
                >
                    <ProiconsPlay :class="`xs:size-8 size-4 *:stroke-1!`" />
                </PlayerOSDTimer>
            </div>

            <!-- Pause Icon -->
            <div class="absolute inset-0 flex items-center justify-center">
                <PlayerOSDTimer
                    class="aspect-square bg-black/60 drop-shadow-lg"
                    :enter-active="'ease-out duration-300'"
                    :is-triggered="!isPaused"
                    :hide-on-false="true"
                    :duration="700"
                    :component="PlayerOSDBase"
                >
                    <IconPause class="xs:size-8 size-4" />
                </PlayerOSDTimer>
            </div>
        </div>

        <!-- UI Panels Z-7 (Stats, Options)-->
        <div
            style="z-index: 7; height: calc(100% - calc(var(--spacing) * 18))"
            :class="
                cn('ui-layer scrollbar-hide inset-x-0 flex flex-wrap justify-between gap-2', 'xms:top-2 top-9 bottom-16 mx-2', {
                    'top-11! mx-4': isFullScreen || isTheatreView,
                })
            "
        >
            <!-- UI Panels Left -->
            <div :class="cn('flex w-fit flex-col gap-2')">
                <!-- Video Stats (Z-7) -->
                <PlayerStats
                    :close-stats="() => (isShowingStats = false)"
                    :is-showing-stats="isShowingStats"
                    :is-audio="isAudio"
                    :buffer-health="bufferHealth"
                    :frame-health="frameHealth"
                    :player="player"
                />

                <AudioSpectrographPanel
                    v-if="playerSpectrograph"
                    v-show="isShowingAudioGraphSettings"
                    :close-panel="() => (isShowingAudioGraphSettings = false)"
                    :toggle-scale="playerSpectrograph?.toggleScale"
                />
            </div>

            <!-- UI Panels Right -->
            <div
                :class="cn('flex h-full flex-1 flex-col items-end gap-2', { 'xxs:mt-7': isNormalView && isShowingParty })"
                :style="{
                    '--watch-party-margin': isNormalView ? (isShowingParty ? 7 : 0) : 11,
                    maxHeight: 'calc(100% - var(--spacing) * var(--watch-party-margin))',
                }"
            >
                <!-- Watch Party (Z-7) -->
                <VideoPartyPanel :is-showing-party="isShowingParty" />
                <PlayerTranscript :is-visible="transcriptPlacement === 'overlay'" />
            </div>
        </div>

        <!-- Overlay Controls and Notifications Z-8 (Skip Intro, Timeline) -->
        <div style="z-index: 8" class="ui-layer inset-0 flex">
            <!-- Overlay controls  -->
            <div :class="['absolute bottom-18 xl:bottom-23', isNormalView ? 'left-2' : 'left-4', '-ms-1 flex h-fit max-h-28 max-w-42 flex-col-reverse gap-1 overflow-clip p-1']">
                <!-- Skip Intro (Z-7) -->
                <PlayerSkipIntro
                    v-if="!isAudio"
                    :is-showing-controls="isShowingControls"
                    :time-duration="timeDuration"
                    :time-elapsed-percent="timeElapsed"
                    :handle-auto-seek="handleAutoSeek"
                    :is-normal-view="isNormalView"
                />
            </div>

            <!-- Controls (Z-8) -->
            <div
                v-cloak
                :class="
                    cn(
                        '@container pointer-events-none! mt-auto h-14 w-full transition-transform duration-300',
                        isShowingControls ? 'translate-y-0 ease-out' : 'translate-y-[102%] ease-in',
                    )
                "
            >
                <div
                    :class="
                        cn(
                            'flex h-14 w-full flex-col justify-end',
                            // bg-linear-to-b from-transparent to-neutral-900/30 -> Causes rendering bug on firefox android
                            {
                                'p-2': isFullScreen || isTheatreView,
                            },
                        )
                    "
                >
                    <!-- Heatmap and Timeline -->
                    <VideoTimeline
                        ref="player-timeline"
                        :buffer-percentage="bufferPercentage"
                        :time-duration="timeDuration"
                        :time-elapsed-verbose="timeStrings.timeElapsedVerbose"
                        :video-button-offset="videoButtonOffset"
                        v-model="timeElapsed"
                        @seek="handleSeek"
                        @seek-preview="handleSeekPreview"
                        @key-bind="handleKeyBinds"
                    >
                        <VideoHeatmap :playback-data="playbackData" :is-showing-controls="isShowingControls" />
                    </VideoTimeline>

                    <!-- Controls -->
                    <div id="player-controls" :class="['pointer-events-auto relative flex w-full items-center gap-1 px-2', isFullScreen || isTheatreView ? 'pt-2' : 'py-1.5']">
                        <VideoControlWrapper>
                            <VideoButton
                                @click="handlePlayerToggle"
                                :title="keyBinds.play"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                            >
                                <template #icon>
                                    <ProiconsPlay v-if="isPaused" class="size-4" />
                                    <IconPause v-else class="size-4" />
                                </template>
                            </VideoButton>
                        </VideoControlWrapper>

                        <VideoControlWrapper class="xs:flex hidden items-center gap-1" v-if="previousVideoURL || nextVideoURL">
                            <VideoButton
                                v-if="previousVideoURL"
                                id="play-previous"
                                :class="cn('hidden @[28rem]:block', { block: isFullScreen })"
                                :title="keyBinds.previous"
                                :icon="ProiconsReverse"
                                :to="previousVideoURL"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                            />

                            <VideoButton
                                v-if="nextVideoURL"
                                id="play-next"
                                :title="keyBinds.next"
                                :icon="ProiconsFastForward"
                                :to="nextVideoURL"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                            />
                        </VideoControlWrapper>
                        <VideoControlWrapper class="hidden items-center gap-1 sm:flex" v-if="!isMobileDevice() && showSeekButtons">
                            <VideoButton
                                id="seek-backwards"
                                :title="keyBinds.backwards"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                                @click="handleAutoSeek(-10)"
                            >
                                <template #icon>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="size-4">
                                        <path
                                            fill="currentColor"
                                            d="m12 11.6l2.5 2.5q.275.275.275.7t-.275.7t-.7.275t-.7-.275l-2.8-2.8q-.15-.15-.225-.337T10 11.975V8q0-.425.288-.712T11 7t.713.288T12 8zM7.488 20.3q-1.638-.7-2.863-1.925T2.7 15.512T2 12t.7-3.512t1.925-2.863T7.488 3.7T11 3q.275 0 .513.013t.512.062q.425 0 .713.288t.287.712t-.288.713t-.712.287q-.275 0-.513-.038T11 5Q8.05 5 6.025 7.025T4 12t2.025 4.975T11 19t4.975-2.025T18 12q0-.425.288-.712T19 11t.713.288T20 12q0 1.875-.7 3.513t-1.925 2.862t-2.863 1.925T11 21t-3.512-.7"
                                        />
                                        <rect fill="currentColor" x="16" y="5" width="6" height="2" rx="1" />
                                    </svg>
                                </template>
                            </VideoButton>
                            <VideoButton
                                id="seek-forwards"
                                :title="keyBinds.forwards"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                                @click="handleAutoSeek(10)"
                            >
                                <template #icon>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="size-4">
                                        <path
                                            fill="currentColor"
                                            d="m12 11.6l2.5 2.5q.275.275.275.7t-.275.7t-.7.275t-.7-.275l-2.8-2.8q-.15-.15-.225-.337T10 11.975V8q0-.425.288-.712T11 7t.713.288T12 8zM18 6h-2q-.425 0-.712-.287T15 5t.288-.712T16 4h2V2q0-.425.288-.712T19 1t.713.288T20 2v2h2q.425 0 .713.288T23 5t-.288.713T22 6h-2v2q0 .425-.288.713T19 9t-.712-.288T18 8zM7.488 20.3q-1.638-.7-2.863-1.925T2.7 15.512T2 12t.7-3.512t1.925-2.863T7.488 3.7T11 3q.275 0 .513.013t.512.062q.425 0 .713.288t.287.712t-.288.713t-.712.287q-.275 0-.513-.038T11 5Q8.05 5 6.025 7.025T4 12t2.025 4.975T11 19t4.975-2.025T18 12q0-.425.288-.712T19 11t.713.288T20 12q0 1.875-.7 3.513t-1.925 2.862t-2.863 1.925T11 21t-3.512-.7"
                                        />
                                    </svg>
                                </template>
                            </VideoButton>
                        </VideoControlWrapper>

                        <VideoControlWrapper class="hidden sm:flex" v-show="endsAtTime !== '00:00' && endsAtTime !== ''">
                            <div
                                class="flex gap-1 rounded-full p-1 px-1.5 leading-4 text-nowrap text-white/80 hover:bg-white/10 hover:text-white"
                                :title="`The ${isAudio ? 'audio' : 'video'} will finish at ${endsAtTime}`"
                            >
                                <p>Ends at</p>
                                <time class="text-nowrap">{{ endsAtTime }}</time>
                            </div>
                        </VideoControlWrapper>

                        <VideoControlWrapper class="ml-auto">
                            <VideoButton
                                class="xs:flex ml-auto hidden ps-1.5 leading-4 text-nowrap select-text"
                                @click="timeDisplay = timeDisplay === 'timeElapsed' ? 'timeRemaining' : 'timeElapsed'"
                                :title="timeStrings.timeVerbose"
                                :use-tooltip="false"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                            >
                                <template #icon>
                                    <time>{{ timeStrings[timeDisplay] }}</time>
                                    <span class="xm:block hidden"> / </span>
                                    <time class="xm:block hidden">{{ timeStrings.timeDuration }}</time>
                                </template>
                            </VideoButton>

                            <section :class="['group -mr-0.5 flex h-full items-center rounded-full p-1 hover:bg-white/10', { 'sm:mr-0': isNormalView }]" @wheel.prevent>
                                <VideoButton
                                    :title="keyBinds.mute"
                                    class="duration-150 ease-out"
                                    @click="handleMute"
                                    @wheel.prevent="handleVolumeWheel"
                                    :use-tooltip="true"
                                    :target-element="player ?? undefined"
                                    :controls="isShowingControls"
                                    :offset="videoButtonOffset"
                                    :vertical-offset="'-3.25rem'"
                                    :use-background="false"
                                >
                                    <template #icon>
                                        <ProiconsVolume v-if="currentVolume > 0.3" class="size-4" />
                                        <ProiconsVolumeLow v-else-if="currentVolume > 0" class="size-4" />
                                        <ProiconsVolumeMute v-else class="size-4" />
                                    </template>
                                </VideoButton>
                                <VideoSlider
                                    v-model="currentVolume"
                                    :text="`Volume: ${Math.round(currentVolume * 100)}%`"
                                    :action="() => handleVolumeChange()"
                                    :wheel-action="handleVolumeWheel"
                                    :force-visibilty="isFullScreen"
                                />
                            </section>
                            <VideoButton
                                class="xms:block hidden"
                                @click="handleLyrics()"
                                :title="keyBinds.lyrics"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                                v-if="isAudio || stateFolder.is_majority_audio"
                            >
                                <template #icon>
                                    <TablerMicrophone2 v-if="isShowingLyrics" class="size-4 *:stroke-[1.4px]" />
                                    <TablerMicrophone2Off v-else class="size-4 *:stroke-[1.4px]" />
                                </template>
                            </VideoButton>
                            <template v-else>
                                <PlayerSubtitles
                                    ref="player-subtitles"
                                    :video-button-offset="videoButtonOffset"
                                    :using-player-modern-u-i="usingPlayerModernUI"
                                    :get-current-time="getCurrentTime"
                                    :title="keyBinds.subtitles"
                                />
                                <PlayerAudioTracks
                                    ref="player-audio-tracks"
                                    :video-button-offset="videoButtonOffset"
                                    :using-player-modern-u-i="usingPlayerModernUI"
                                    :title="'Languages'"
                                />
                            </template>
                            <VideoPopover
                                :popoverClass="cn('max-w-44 md:max-w-42 rounded-lg h-fit')"
                                ref="player-popover"
                                :margin="80"
                                :player="player ?? undefined"
                                :button-attributes="{
                                    'target-element': player ?? undefined,
                                    'use-tooltip': !popover?.popoverOpen,
                                    offset: videoButtonOffset,
                                }"
                            >
                                <template #buttonIcon>
                                    <ProiconsSettings class="size-4 transition-transform duration-500 ease-in-out hover:rotate-180" />
                                </template>
                                <template #content>
                                    <section class="scrollbar-minimal xs:h-28 flex h-14 flex-col overflow-y-auto pe-0.5 transition-transform md:h-fit md:pe-0">
                                        <VideoPopoverItem v-for="(item, index) in videoPopoverItems" :key="index" v-bind="item" />
                                        <VideoPopoverSlider
                                            v-model="currentSpeed"
                                            :text="`Speed`"
                                            :shortcut="`${Math.round(currentSpeed * 100)}%`"
                                            :icon="CircumTimer"
                                            :min="playbackMin"
                                            :max="playbackMax"
                                            :step="playbackDelta"
                                            :action="handleSpeedChange"
                                            :wheel-action="handleSpeedWheel"
                                            :title="'Change Playback Speed'"
                                            :default-value="1"
                                        />
                                        <VideoPopoverSlider
                                            v-if="false"
                                            v-model="currentVolume"
                                            :hidden="true"
                                            :text="`Volume`"
                                            :shortcut="`${Math.round(currentVolume * 100)}%`"
                                            :icon="currentVolume > 0.3 ? ProiconsVolume : currentVolume > 0 ? ProiconsVolumeLow : ProiconsVolumeMute"
                                            :min="0"
                                            :max="1"
                                            :step="0.05"
                                            :action="() => handleVolumeChange()"
                                            :wheel-action="handleVolumeWheel"
                                            :title="'Change Volume'"
                                        />
                                    </section>
                                </template>
                            </VideoPopover>
                            <VideoButton
                                @click="handleTheatre"
                                :title="keyBinds.theatre"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                                v-show="!isFullScreen"
                                class="xsm:block hidden"
                            >
                                <template #icon>
                                    <IconTheatreOff v-if="isTheatreView" class="size-4" />
                                    <IconTheatreOn v-else class="size-4" />
                                </template>
                            </VideoButton>
                            <VideoButton
                                @click="handleFullScreen"
                                :title="keyBinds.fullscreen"
                                :use-tooltip="true"
                                :target-element="player ?? undefined"
                                :controls="isShowingControls"
                                :offset="videoButtonOffset"
                            >
                                <template #icon>
                                    <ProiconsFullScreenMinimize v-if="isFullScreen" class="size-4" />
                                    <ProiconsFullScreenMaximize v-else class="size-4" />
                                </template>
                            </VideoButton>
                        </VideoControlWrapper>
                    </div>
                </div>
            </div>
        </div>

        <!-- Interactable UI Z-6 (Lyrics) -->
        <div style="z-index: 6" class="ui-layer inset-0 flex">
            <!-- Lyrics (Z-6) -->
            <Transition
                enter-active-class="ease-out"
                enter-from-class="translate-y-full opacity-0"
                enter-to-class="translate-y-0 opacity-100"
                leave-active-class="ease-in"
                leave-from-class="translate-y-0 opacity-100"
                leave-to-class="translate-y-full opacity-0"
                @after-enter="playerLyrics?.scrollToCurrent()"
            >
                <div :class="`flex size-full opacity-0 transition-[opacity,translate] duration-300`" v-show="isShowingLyrics">
                    <VideoLyrics
                        v-if="isAudio || stateFolder.is_majority_audio"
                        ref="player-lyrics"
                        :player="player"
                        :raw-lyrics="stateVideo?.metadata?.lyrics ?? ''"
                        :time-duration="timeDuration"
                        :is-paused="isPaused"
                        :is-showing-lyrics="isShowingLyrics"
                        @seek="handleManualSeek"
                        @play="handlePlayerToggle"
                    />
                </div>
            </Transition>
        </div>

        <!-- Base Interaction and Visual Layers Z-4 (Tap Controls, Gradients) -->
        <div style="z-index: 4" class="ui-layer inset-0 select-none">
            <!-- Tap Controls (Z-4) -->
            <span
                v-if="isMobileDevice() || !showSeekButtons"
                aria-describedby="Skip Backward"
                :class="['pointer-events-auto absolute top-0 left-0 h-full', isFullScreen ? 'w-1/4' : 'w-1/3 sm:w-1/4']"
                @dblclick.stop="handleAutoSeek(-10)"
            ></span>
            <span
                v-if="isMobileDevice() || !showSeekButtons"
                :class="['pointer-events-auto absolute top-0 right-0 h-full', isFullScreen ? 'w-1/4' : 'w-1/3 sm:w-1/4']"
                aria-describedby="Skip Forward"
                @dblclick.stop="handleAutoSeek(10)"
            ></span>
            <!-- Blocks bottom of tap controls but I am not sure why since player controls are already on top -->
            <span class="pointer-events-auto absolute bottom-0 h-1/6 w-full"></span>

            <!-- Non Interactable -->
            <!-- Lyrics Background Blur (Z-4) (below other non-interactables) -->
            <Transition
                enter-active-class="ease-out"
                enter-from-class="opacity-0"
                enter-to-class="opacity-100"
                leave-active-class="ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
            >
                <div
                    :class="`absolute inset-0 size-full bg-neutral-950/20 backdrop-blur-lg transition-opacity duration-300`"
                    v-show="(isAudio || stateFolder.is_majority_audio) && isShowingLyrics"
                />
            </Transition>

            <!-- Controls Gradient (Z-4) -->
            <Transition
                enter-active-class="ease-out"
                enter-from-class="translate-y-4/5 opacity-0"
                enter-to-class="translate-y-0 opacity-100"
                leave-active-class="ease-in"
                leave-from-class="translate-y-0 opacity-100"
                leave-to-class="translate-y-4/5 opacity-0"
            >
                <div
                    v-show="isShowingControls"
                    :class="`from-00% absolute bottom-0 left-0 h-32 w-full bg-linear-to-b from-neutral-900/0 to-neutral-900/30 transition-[translate,opacity] duration-300`"
                    v-cloak
                ></div>
            </Transition>

            <!-- Title Gradient (Z-4) -->
            <Transition
                enter-active-class="ease-out"
                enter-from-class="-translate-y-full"
                enter-to-class="translate-y-0"
                leave-active-class="ease-in"
                leave-from-class="translate-y-0"
                leave-to-class="-translate-y-full"
            >
                <div
                    v-show="isShowingControls && (isFullScreen || isTheatreView)"
                    :class="`absolute top-0 left-0 h-16 w-full bg-linear-to-b from-black to-transparent opacity-40 transition-[translate] duration-300`"
                    v-cloak
                ></div>
            </Transition>

            <!-- Audio Graph -->
            <AudioSpectrograph class="absolute bottom-0 w-full" v-if="player" :is-enabled="isAudioGraphEnabled" ref="player-spectrograph" />
        </div>

        <div class="dark pointer-events-none absolute inset-0 size-full text-white" v-show="isFullScreen || isTheatreView">
            <GlobalModal :teleport-disabled="true" v-if="isFullScreen || isTheatreView" />
            <ToastController :teleport-disabled="true" :position="'bottom-left'" v-if="isFullScreen || isTheatreView" />
            <ContextMenu
                ref="context-menu"
                :items="contextMenuItems"
                :style="contextMenuStyle"
                :itemStyle="contextMenuItemStyle ?? 'hover:bg-primary hover:text-white'"
                scrollContainer="window"
                teleport-disabled
            />
        </div>
    </div>
</template>

<style scoped lang="css">
/* OSD */

@keyframes pop {
    0% {
        transform: scale(0.8);
    }
    100% {
        transform: scale(1);
    }
}
.animate-pop {
    animation: pop 200ms ease-out forwards;
}

/* Theatre Mode */

@keyframes theatreEnter {
    0% {
        transform: scale(0.5);
        opacity: 0.9;
        border-radius: var(--radius-lg);
    }
    90% {
        border-radius: var(--radius-sm);
    }
    100% {
        transform: scale(1);
        opacity: 1;
        border-radius: 0;
    }
}

.animate-theatre-enter {
    animation: theatreEnter var(--tw-duration, 500ms) cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

.transition-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0);
    z-index: 9998;
    pointer-events: none;
    transition: background-color 500ms ease;
}

.transition-overlay.active {
    background: rgba(0, 0, 0, 1);
}

.player-transition {
    transition-property:
        transform,
        border-radius opacity;
    will-change: transform;
}

.theatre-mode {
    position: fixed;
    inset: 0;
    width: 100vw;
    height: 100dvh;
    background: black;
    z-index: 9999;
}

.theatre-mode video {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* Player */

.ui-layer {
    position: absolute;
    pointer-events: none;
    font-family: var(--font-mono);
    color: var(--color-white);
}

video::cue {
    font-weight: normal;
    background-color: transparent;
    color: #ffffff;
    font-family: var(--font-figtree);
    text-shadow: 0px 0px 7px #000;
}

@supports selector(video::-webkit-media-text-track-container) {
    video::cue {
        font-size: 1em;
    }

    /* Incompatible with Firefox */
    video::-webkit-media-text-track-container {
        font-size: clamp(90%, calc(var(--subtitle-font-size, 100%) * var(--subtitle-font-multiplier, 1)), 240%) !important;
    }

    /* Incompatible with Firefox */
    video::-webkit-media-text-track-display {
        margin-left: 15%;
        max-width: 70%;
        padding-bottom: clamp(1em, calc(calc(var(--subtitle-bottom-offset, 0em) - (var(--subtitle-font-multiplier, 1) * 0.6em))), 3em) !important;
    }
}

@supports not selector(video::-webkit-media-text-track-container) {
    video::cue {
        font-size: clamp(0.75em, calc(var(--subtitle-cue-size, 1rem) * var(--subtitle-font-multiplier, 1)), 2.2em);
    }
}
</style>