'use client';

import { useAuth } from '@clerk/nextjs';
import { useGateValue } from '@statsig/react-bindings';
import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { usePathname } from 'next/navigation';
import React, {
  memo,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { twMerge } from 'tailwind-merge';
import { useIsClient, useOnClickOutside, useResizeObserver } from 'usehooks-ts';

import { useStores } from '@/app/(root)/AppProviders';
import { isLiveRadioPath } from '@/app/(root)/live-radio/util';
import Button, {
  BaseButtonProps,
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { isVideoHooksPath } from '@/components/hooksPlayer/utils';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Link from '@/components/link/Link';
import PlaybackProgress, {
  PlaybackProgressProps,
} from '@/components/mediaPlayback/PlaybackProgress';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import BaseSongActions from '@/components/song/SongActions';
import { formatDuration } from '@/components/song/songUtils';
import { Tooltip } from '@/components/tooltip/Tooltip';
import { useModalContext } from '@/context/ModalContext';
import { useBreakpointLg, useBreakpointMd } from '@/hooks/useBreakpoint';
import usePolledValue from '@/hooks/usePolledValue';
import {
  NextTrackIcon,
  PauseIcon,
  PlayIcon,
  PreviousTrackIcon,
  QueueIcon,
  RepeatIcon,
  ReplayIcon,
  ShuffleIcon,
  Volume0Icon,
  VolumeDownIcon,
  VolumeMuteIcon,
  VolumeOnIcon,
} from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';
import { getClipTitle } from '@/utils/clip';
import { SMALL_IMAGE } from '@/utils/constants';

import VolumeSlider from './VolumeSlider';

interface PlaybarProps {
  className?: string;
  hidden?: boolean;
  disableControls?: boolean;
}

const PlaybarClipInfo: React.FC<{
  className?: string;
  children?: React.ReactNode;
  clip: Clip;
  onImageClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
  onTitleClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
}> = memo(function PlaybarClipInfo(props) {
  const { className, children, clip, onImageClick, onTitleClick } = props;
  const title = getClipTitle(clip);
  return (
    <div
      className={twMerge(
        'relative flex h-full w-full flex-1 flex-row items-center gap-2',
        className
      )}
    >
      <Link
        className='h-14 w-9 shrink-0 overflow-clip rounded-md md:h-12'
        href={`/song/${clip.id}`}
        aria-label={`Playbar: Title for ${clip.title}`}
        onClick={onImageClick}
      >
        <ImageWithFallback
          imageSize={
            // for shorts, images are not square - don't resize until we fix the aspect ratio
            clip.metadata.is_suno_short ? undefined : SMALL_IMAGE
          }
          className='h-full w-full object-cover'
          src={clip.image_url || null}
          alt={`Cover image for ${clip?.title}`}
          aria-label={`Playbar: Cover image for ${clip?.title}`}
        />
      </Link>
      <div className='relative flex w-full min-w-0 flex-1 flex-col md:w-auto'>
        <Marquee className='-mx-0.5 px-0.5'>
          <Link
            href={`/song/${clip.id || ''}`}
            className='text-sm leading-5 font-medium whitespace-nowrap text-foreground-primary hover:underline'
            aria-label={`Playbar: Title for ${title}`}
            onClick={onTitleClick}
          >
            {title}
          </Link>
        </Marquee>
        <Link
          href={`/@${clip.handle}`}
          className='relative flex w-max max-w-full text-xs leading-4 font-medium text-foreground-tertiary hover:underline md:w-fit'
          aria-label={`Playbar: Artist for ${clip?.title}`}
        >
          <span className='line-clamp-1 w-full lg:max-w-[150px]'>
            {clip.display_name}
          </span>
        </Link>
        {children}
      </div>
    </div>
  );
});

const Marquee: React.FC<React.HTMLAttributes<HTMLDivElement>> = (props) => {
  const { children, className, ...restProps } = props;
  const [needsMarquee, setNeedsMarquee] = useState(false);

  const ref = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);

  const checkContentSize = useCallback(() => {
    const containerWidth = ref.current?.clientWidth ?? 0;
    const contentWidth = contentRef.current?.scrollWidth ?? 0;
    setNeedsMarquee(contentWidth > containerWidth);
  }, []);

  useResizeObserver({
    ref: ref as React.RefObject<HTMLDivElement>,
    onResize: checkContentSize,
  });

  useEffect(() => {
    checkContentSize();
  }, [children, checkContentSize]);

  return (
    <div
      className={twMerge(
        'relative overflow-x-clip',
        '[--marquee-gap:6rem]',
        clsx({ 'mask-x-from-[calc(100%-1rem)]': needsMarquee }),
        className
      )}
      ref={ref}
      {...restProps}
    >
      <div
        className={clsx(
          'flex w-max flex-row items-center gap-(--marquee-gap) overflow-visible',
          {
            'animate-marquee animate-duration-[10s]': needsMarquee,
            '[--marquee-end:-50%] [--marquee-start:0%]': needsMarquee,
          }
        )}
      >
        <div ref={contentRef}>{children}</div>
        {/* Hide duplicated content from screen readers */}
        <div
          className={clsx('mr-(--marquee-gap)', { hidden: !needsMarquee })}
          aria-hidden='true'
        >
          {children}
        </div>
      </div>
    </div>
  );
};

const SongActions = memo(BaseSongActions);

const VolumeButton: React.FC<
  {
    className?: string;
    onPointerDown: (e: React.PointerEvent) => void;
    ref: React.RefObject<any>;
  } & Pick<BaseButtonProps, 'variant' | 'shape' | 'size' | 'iconClassName'>
> = memo(
  observer(function VolumeButton(props) {
    const {
      className,
      onPointerDown,
      ref,
      variant = ButtonVariant.Inherit,
      shape = ButtonShape.Rounded,
      size = ButtonSize.Mini,
      iconClassName,
    } = props;
    const { playbar } = useStores();
    const isClient = useIsClient();

    if (!isClient) return null;

    const icon =
      playbar.displayVolume === 0
        ? VolumeMuteIcon
        : playbar.displayVolume < 0.2
          ? Volume0Icon
          : playbar.displayVolume < 0.6
            ? VolumeDownIcon
            : VolumeOnIcon;

    return (
      <Button
        variant={variant}
        shape={shape}
        size={size}
        icon={icon}
        iconClassName={iconClassName}
        className={twMerge('cursor-pointer', className)}
        enableHoverState
        onPointerDown={onPointerDown}
        aria-label='Playbar: Volume Slider'
        ref={ref}
      />
    );
  })
);

const PlaybarScrubber: React.FC<PlaybackProgressProps> = observer((props) => {
  const { className, ...restProps } = props;
  const { playbar } = useStores();

  const { duration, isPlaying } = playbar;

  const [dragPosition, setDragPosition] = useState<number | null>(null);
  const isDragging = dragPosition != null;

  const getCurrentTime = useCallback(
    () => dragPosition ?? playbar.getCurrentTime(),
    [dragPosition, playbar]
  );

  const [currentTime, updateCurrentTime] = usePolledValue(getCurrentTime, {
    enabled: isPlaying,
    pollingInterval: 150,
  });

  useEffect(() => {
    // Prevent highlighting on the page when dragging playbar
    if (isDragging) {
      document.body.classList.add('no-drag', 'cursor-pointer');
    } else {
      document.body.classList.remove('no-drag', 'cursor-pointer');
    }
    playbar.setIsDragging(isDragging);
  }, [isDragging, playbar]);

  const handleSeekStart = useCallback((time: number | null) => {
    setDragPosition(time);
  }, []);

  const handleSeekMove = useCallback((time: number | null) => {
    if (time != null) {
      setDragPosition(time);
    }
  }, []);

  const handleSeekEnd = useCallback(
    (time: number | null) => {
      updateCurrentTime();
      if (time != null) {
        playbar.userSetCurrentProgressWithTime(time);
      }
      setDragPosition(null);
    },
    [updateCurrentTime, playbar]
  );

  return (
    <PlaybackProgress
      className={twMerge(
        '[--track-progress-color:var(--color-foreground-primary)]',
        '[--track-remaining-color:var(--color-background-glass-dense)]',
        '[--button-color:var(--color-foreground-primary)]',
        '[--time-color:var(--color-foreground-tertiary)]',
        className
      )}
      timeClassName={playbar.clip ? undefined : 'opacity-0'}
      currentTime={currentTime}
      duration={playbar.clip?.metadata?.duration || undefined}
      estimatedDuration={playbar.clip ? duration : undefined}
      showEstimatedDurationSpinner={!!playbar.clip}
      onSeekStart={handleSeekStart}
      onSeekMove={handleSeekMove}
      onSeekEnd={handleSeekEnd}
      {...restProps}
    />
  );
});

const PlaybackTime: React.FC<PlaybackProgressProps> = observer((props) => {
  const { className } = props;
  const { playbar } = useStores();

  const { duration, isPlaying } = playbar;

  const getCurrentTime = useCallback(() => playbar.getCurrentTime(), [playbar]);

  const [currentTime] = usePolledValue(getCurrentTime, {
    enabled: isPlaying,
    pollingInterval: 150,
  });

  return (
    <div className={className}>
      {playbar.clip?.metadata?.duration == null
        ? formatDuration(currentTime)
        : `${formatDuration(currentTime)} / ${formatDuration(playbar.clip?.metadata?.duration ?? duration)}`}
    </div>
  );
});

const PlaybarQueueButton: React.FC<{ className?: string; clipId: string }> =
  observer((props) => {
    const { className, clipId } = props;
    const { playbar } = useStores();
    const { openModal } = useModalContext();
    const isDesktop = useBreakpointLg();

    return (
      <Button
        className={className}
        variant={ButtonVariant.Inherit}
        size={ButtonSize.Mini}
        icon={QueueIcon}
        iconClassName='w-5 h-5 m-0.5'
        onClick={() => {
          playbar.toggleShowSongQueue();
          if (!isDesktop) {
            openModal(ModalTypes.SONG_QUEUE);
          }
          logWebUserEvent({
            actionName: 'SongActionQueueClicked',
            context: {
              clipId,
            },
          });
        }}
        aria-label='Playbar: Song Queue'
      />
    );
  });

interface PlayControlsProps {
  className?: string;
  disableControls?: boolean;
  clip: Clip | null;
  showVolumeTooltip?: boolean;
  buttonVariant?: ButtonVariant;
  buttonSize?: ButtonSize;
  buttonShape?: ButtonShape;
  buttonIconClassName?: string;
  playButtonVariant?: ButtonVariant;
  playButtonSize?: ButtonSize;
  playButtonShape?: ButtonShape;
  playButtonIconClassName?: string;
  extraButtonVariant?: ButtonVariant;
  extraButtonSize?: ButtonSize;
  extraButtonShape?: ButtonShape;
  extraButtonIconClassName?: string;
  isCompactLayout?: boolean;
}

const PlayControls: React.FC<PlayControlsProps> = memo(
  observer(function PlayControls(props) {
    const {
      className,
      disableControls = false,
      clip,
      showVolumeTooltip = false,
      buttonVariant = ButtonVariant.Inherit,
      buttonSize = ButtonSize.Small,
      buttonShape = ButtonShape.Pill,
      buttonIconClassName = 'w-6 h-6 m-0',
      playButtonVariant = buttonVariant,
      playButtonSize = buttonSize,
      playButtonShape = buttonShape,
      playButtonIconClassName = buttonIconClassName,
      extraButtonVariant = buttonVariant,
      extraButtonSize = buttonSize,
      extraButtonShape = buttonShape,
      extraButtonIconClassName = buttonIconClassName,
      isCompactLayout = false,
    } = props;
    const { playbar } = useStores();
    const isClient = useIsClient();

    // The loop button is configured to (eventually) have more than two states,
    // which we will most likely use to toggle between:
    //  - No repeat (off)
    //  - Repeat (the whole queue on a loop--not implemented yet)
    //  - Repeat 1 (just the current song over and over)
    const { repeat: isRepeatEnabled } = playbar;
    const {
      active: loopButtonActive,
      icon: loopButtonIcon,
      label: loopButtonLabel,
      onClick: onLoopButtonClick,
    } = useMemo(() => {
      if (isRepeatEnabled) {
        return {
          active: true,
          icon: RepeatIcon, // Repeat 1
          label: 'Disable repeat',
          onClick() {
            playbar.toggleRepeat(false);
            playbar.updatePlaybarState();
          },
        };
      }
      return {
        active: false,
        icon: ReplayIcon, // Repeat without number
        label: 'Enable repeat 1',
        onClick() {
          playbar.toggleRepeat(true);
          playbar.updatePlaybarState();
        },
      };
    }, [playbar, isRepeatEnabled]);

    const hasClip = !!clip && !playbar.isClipPreloaded;
    const handlePlayerTogglePlay = useCallback(
      (e?: React.MouseEvent) => {
        if (e) {
          // Pause and clear the playbar clip
          if (e.altKey && e.shiftKey) {
            playbar.togglePlay(false);
            playbar.unsetClip();
            return;
          }
        }
        if (hasClip) {
          playbar.togglePlay();
        } else {
          playbar.noClipPlayCallback?.();
        }
      },
      [hasClip, playbar]
    );

    const showShuffleButton = isClient && !isCompactLayout;
    const showRepeatButton = isClient && !isCompactLayout;

    return (
      <div className={twMerge('flex flex-row items-center gap-2', className)}>
        {showShuffleButton ? (
          <Tooltip label={disableControls ? '' : 'Shuffle'}>
            <Button
              variant={extraButtonVariant}
              size={extraButtonSize}
              shape={extraButtonShape}
              icon={ShuffleIcon}
              iconClassName={extraButtonIconClassName}
              active={!disableControls && playbar.shuffle}
              disabled={disableControls}
              onClick={() => {
                playbar.toggleShuffle();
              }}
              aria-label='Playbar: Toggle shuffle button'
            />
          </Tooltip>
        ) : null}
        <Button
          variant={buttonVariant}
          size={buttonSize}
          shape={buttonShape}
          icon={PreviousTrackIcon}
          iconClassName={buttonIconClassName}
          onClick={() => {
            playbar.stepBackward();
          }}
          disabled={disableControls || !clip}
          aria-label='Playbar: Previous Song button'
        />
        <Tooltip
          label='Psst...you may want to turn up the volume!'
          isTooltipEnabled={showVolumeTooltip}
        >
          <Button
            variant={playButtonVariant}
            size={playButtonSize}
            shape={playButtonShape}
            icon={playbar.isPlaying ? PauseIcon : PlayIcon}
            iconClassName={playButtonIconClassName}
            disabled={disableControls || !clip}
            onClick={handlePlayerTogglePlay}
            aria-label={
              playbar.isPlaying
                ? 'Playbar: Pause button'
                : 'Playbar: Play button'
            }
          />
        </Tooltip>
        <Button
          variant={ButtonVariant.Inherit}
          size={ButtonSize.Small}
          shape={ButtonShape.Pill}
          icon={NextTrackIcon}
          iconClassName='w-6 h-6 m-0'
          active={playbar.canStepForward()}
          disabled={!playbar.canStepForward() || disableControls || !clip}
          onClick={() => {
            playbar.stepForward();
          }}
          aria-label='Playbar: Next Song button'
        />
        {showRepeatButton ? (
          <Tooltip label={disableControls ? '' : loopButtonLabel}>
            <Button
              variant={extraButtonVariant}
              size={extraButtonSize}
              shape={extraButtonShape}
              icon={loopButtonIcon}
              iconClassName={extraButtonIconClassName}
              active={!disableControls && loopButtonActive}
              disabled={disableControls}
              onClick={onLoopButtonClick}
              aria-label='Playbar: Toggle repeat button'
            />
          </Tooltip>
        ) : null}
      </div>
    );
  })
);

const PlaybarBackgroundImage: React.FC<
  {
    imageClassName?: string;
    src?: string;
  } & React.HTMLAttributes<HTMLDivElement>
> = observer((props) => {
  const { src, className, imageClassName, children, ...restProps } = props;

  return (
    <div
      className={twMerge(
        'relative after:absolute after:inset-0 after:bg-background-secondary/85',
        className
      )}
      {...restProps}
    >
      <div
        className={twMerge(
          'absolute inset-0',
          'bg-(image:--background-image) bg-cover bg-center',
          'blur-[40px]',
          imageClassName
        )}
        style={
          src
            ? ({ '--background-image': `url(${src})` } as React.CSSProperties)
            : undefined
        }
      >
        {children}
      </div>
    </div>
  );
});

const Playbar: React.FC<PlaybarProps> = observer((props) => {
  const { className, hidden = false, disableControls = false } = props;

  const { playbar, clips } = useStores();
  const { openModal } = useModalContext();

  const pathname = usePathname();

  const enableOmniplayer = useGateValue('web-omniplayer');
  const enableLoggedInMobileSongPage = useGateValue('logged-in-song-page-v2');

  const volumeSliderRef = useRef<any>(null);
  const clip = playbar.clip?.id ? clips.clipById[playbar.clip.id] : null;

  const isMobile = !useBreakpointMd();
  const { isSignedIn } = useAuth();

  const enableHotkeys =
    !disableControls &&
    !isVideoHooksPath(pathname) &&
    !isLiveRadioPath(pathname);

  useEffect(() => {
    playbar.initPlaybarState();
  }, [playbar]);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const handleBeforeUnload = () => {
        playbar.updatePlaybarState();
        window.removeEventListener('beforeunload', handleBeforeUnload);
      };
      window.addEventListener('beforeunload', handleBeforeUnload);
      return () => {
        window.removeEventListener('beforeunload', handleBeforeUnload);
      };
    }
  }, [playbar]);

  /**
   * Handles the click event for the play/pause button
   */
  const hasClip = !!clip && !playbar.isClipPreloaded;
  const handlePlayerTogglePlay = useCallback(() => {
    if (playbar.loadingStream) {
      // TODO: add new tracking on needs
    }
    if (hasClip) {
      playbar.togglePlay();
    } else {
      playbar.noClipPlayCallback?.();
    }
  }, [hasClip, playbar]);

  useHotkeys(
    'space',
    (e) => {
      handlePlayerTogglePlay();
      e.preventDefault();
    },
    { enabled: enableHotkeys },
    [handlePlayerTogglePlay]
  );

  useHotkeys(
    'alt+arrowleft,ctrl+arrowleft',
    (e) => {
      playbar.stepBackward();
      e.preventDefault();
    },
    { enabled: enableHotkeys },
    [playbar, pathname]
  );

  useHotkeys(
    'alt+arrowright,ctrl+arrowright',
    (e) => {
      if (playbar.canStepForward()) {
        playbar.stepForward();
        e.preventDefault();
      }
    },
    { enabled: enableHotkeys },
    [playbar, pathname]
  );

  const [isVolumeSliderOpen, setIsVolumeSliderOpen] = useState(false);
  const volumeButtonRef = useRef<any>(null);
  const handleVolumePointerDown = useCallback(
    (e: React.PointerEvent) => {
      setIsVolumeSliderOpen((prev) => !prev);
      if (e.currentTarget instanceof HTMLElement) {
        e.currentTarget.focus();
      }
      e.preventDefault();
      e.stopPropagation();
    },
    [setIsVolumeSliderOpen]
  );

  const { loadingDuration } = playbar;
  useEffect(() => {
    if (clip?.metadata?.duration && loadingDuration) {
      playbar.setDuration(clip?.metadata?.duration);
      playbar.setLoadingDuration(false);
      playbar.setClip(clip);
    }
  }, [loadingDuration, clip, playbar]);

  useOnClickOutside(volumeSliderRef, () => {
    if (isVolumeSliderOpen) {
      setIsVolumeSliderOpen(false);
    }
  });

  const handleImageClick = useCallback(
    (e: React.MouseEvent<HTMLAnchorElement>) => {
      // Check if we should navigate to mobile song page instead of opening omniplayer
      if (enableOmniplayer) {
        e.preventDefault();
        openModal(ModalTypes.OMNIPLAYER);
      }

      // Let the Link component handle navigation to mobile song page
      if (enableLoggedInMobileSongPage && isSignedIn && isMobile && clip) {
        return;
      }
    },
    [
      enableOmniplayer,
      enableLoggedInMobileSongPage,
      isSignedIn,
      isMobile,
      clip,
      openModal,
    ]
  );
  const handlePlayCountClick = useCallback(() => {
    if (clip) {
      playbar.playClip(clip);
    }
  }, [clip, playbar]);

  const handleTitleClick = useCallback(
    (_e: React.MouseEvent<HTMLAnchorElement>) => {
      // Check if we should navigate to mobile song page instead of opening preview
      if (enableLoggedInMobileSongPage && isSignedIn && isMobile && clip) {
        // Let the Link component handle navigation to mobile song page
        return;
      }

      // For other cases, maintain existing behavior (let Link navigate normally)
    },
    [enableLoggedInMobileSongPage, isSignedIn, isMobile, clip]
  );

  if (hidden) {
    return null;
  }

  return (
    <div
      className={twMerge(
        'relative',
        'h-auto md:min-h-21',
        'bg-background-secondary text-foreground-primary',
        'after:pointer-none after:absolute after:inset-x-0 after:top-0 after:border-t after:border-border-primary',
        className
      )}
    >
      <PlaybarBackgroundImage
        src={clip?.image_url || undefined}
        className='absolute inset-0 overflow-clip'
      />
      <div
        className={clsx(
          'flex flex-row items-center justify-between gap-2 px-2 md:px-4',
          'h-full min-h-20 w-full overflow-x-hidden overflow-y-visible md:min-h-21',
          'font-sans text-sm font-medium',
          {
            hidden: hidden,
          }
        )}
      >
        <div className='relative mr-auto min-w-32 flex-1 shrink-0 self-stretch'>
          {clip ? (
            <PlaybarClipInfo
              clip={clip}
              onImageClick={handleImageClick}
              onTitleClick={handleTitleClick}
            >
              {isMobile && clip ? (
                <SongActions
                  className='w-min'
                  buttonVariant={ButtonVariant.Inherit}
                  buttonSize={ButtonSize.Mini}
                  buttonIconClassName='m-0'
                  buttonAspectSquare={false}
                  clip={clip}
                  isPlaybar
                  onPlayCountClick={handlePlayCountClick}
                  showDislike={false}
                />
              ) : null}
            </PlaybarClipInfo>
          ) : null}
        </div>
        {isMobile ? (
          <div className='relative flex flex-col items-end self-stretch py-1'>
            <PlayControls
              className='flex-1 gap-1'
              disableControls={disableControls}
              clip={clip}
              isCompactLayout
            />
            <PlaybackTime className='px-2 font-mono text-xs font-bold text-foreground-inactive' />
          </div>
        ) : (
          <>
            <div className='relative max-w-[calc(min(50rem,100vw-32rem))] flex-1 basis-50'>
              <div className='mx-auto flex flex-col items-center justify-center gap-1'>
                <PlayControls
                  disableControls={disableControls}
                  clip={clip}
                  showVolumeTooltip={!isMobile && playbar.displayVolume < 0.2}
                  playButtonVariant={ButtonVariant.Primary}
                  playButtonIconClassName='w-5 h-5 m-0.5' // @TODO: Figma icon size is not consistent with icon library
                  extraButtonSize={ButtonSize.Mini}
                  extraButtonIconClassName='w-4 h-4 m-1' // @TODO: Figma icon size is not consistent with icon library
                />
                <PlaybarScrubber
                  className='w-full'
                  disabled={disableControls || !clip || !playbar.duration}
                />
              </div>
            </div>
            <div className='relative ml-auto min-w-48 flex-1 shrink-0'>
              <div className='flex flex-row items-center justify-end gap-1'>
                {clip ? (
                  <>
                    {clip.preview_seconds === undefined ? (
                      <PlaybarQueueButton
                        className='max-md:hidden'
                        clipId={clip?.id || ''}
                      />
                    ) : null}
                    <SongActions
                      className='w-min max-md:hidden'
                      buttonVariant={ButtonVariant.Inherit}
                      buttonIconClassName='size-5 m-0.5'
                      clip={clip}
                      isPlaybar
                      onPlayCountClick={handlePlayCountClick}
                    />
                  </>
                ) : null}
                <VolumeButton
                  className='max-md:hidden'
                  iconClassName='size-5 m-0.5'
                  ref={volumeButtonRef}
                  onPointerDown={handleVolumePointerDown}
                />
              </div>
            </div>
          </>
        )}
      </div>
      {isMobile ? (
        <PlaybarScrubber
          className='h-1 w-full [--button-width:0px] [--min-target-size:8px] [--track-width:4px]'
          trackClassName='rounded-none top-auto bottom-0 translate-y-0'
          remainingClassName='bg-background-tertiary'
          disabled={disableControls || !clip || !playbar.duration}
          showTime={false}
        />
      ) : null}
      {isVolumeSliderOpen && volumeButtonRef.current && (
        <VolumeSlider
          top={volumeButtonRef.current.getBoundingClientRect().top}
          left={volumeButtonRef.current.getBoundingClientRect().left}
          buttonWidth={volumeButtonRef.current.getBoundingClientRect().width}
          buttonHeight={volumeButtonRef.current.getBoundingClientRect().height}
          ref={volumeSliderRef}
        />
      )}
    </div>
  );
});

export default Playbar;
