import { jsxs, jsx } from "react/jsx-runtime";
import * as React from "react";
import { c as cn } from "../../cn-FAaWYZ6x.js";
import { Button } from "../button/button.js";
import { Slider } from "../slider/slider.js";
import { Popover, PopoverTrigger, PopoverContent } from "../popover/popover.js";
import { c as createLucideIcon } from "../../createLucideIcon-Bni0WIE-.js";
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$6 = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["line", { x1: "12", x2: "12", y1: "8", y2: "12", key: "1pkeuh" }],
  ["line", { x1: "12", x2: "12.01", y1: "16", y2: "16", key: "4dfq90" }]
];
const CircleAlert = createLucideIcon("circle-alert", __iconNode$6);
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$5 = [["path", { d: "M21 12a9 9 0 1 1-6.219-8.56", key: "13zald" }]];
const LoaderCircle = createLucideIcon("loader-circle", __iconNode$5);
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$4 = [
  ["rect", { x: "14", y: "3", width: "5", height: "18", rx: "1", key: "kaeet6" }],
  ["rect", { x: "5", y: "3", width: "5", height: "18", rx: "1", key: "1wsw3u" }]
];
const Pause = createLucideIcon("pause", __iconNode$4);
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$3 = [
  [
    "path",
    {
      d: "M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",
      key: "10ikf1"
    }
  ]
];
const Play = createLucideIcon("play", __iconNode$3);
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$2 = [
  [
    "path",
    {
      d: "M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",
      key: "uqj9uw"
    }
  ],
  ["path", { d: "M16 9a5 5 0 0 1 0 6", key: "1q6k2b" }]
];
const Volume1 = createLucideIcon("volume-1", __iconNode$2);
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$1 = [
  [
    "path",
    {
      d: "M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",
      key: "uqj9uw"
    }
  ],
  ["path", { d: "M16 9a5 5 0 0 1 0 6", key: "1q6k2b" }],
  ["path", { d: "M19.364 18.364a9 9 0 0 0 0-12.728", key: "ijwkga" }]
];
const Volume2 = createLucideIcon("volume-2", __iconNode$1);
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode = [
  [
    "path",
    {
      d: "M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",
      key: "uqj9uw"
    }
  ],
  ["line", { x1: "22", x2: "16", y1: "9", y2: "15", key: "1ewh16" }],
  ["line", { x1: "16", x2: "22", y1: "9", y2: "15", key: "5ykzw1" }]
];
const VolumeX = createLucideIcon("volume-x", __iconNode);
const formatTime = (seconds) => {
  if (Number.isNaN(seconds) || seconds === Infinity) return "--:--";
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor(seconds % 3600 / 60);
  const secs = Math.floor(seconds % 60);
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  }
  return `${minutes}:${secs.toString().padStart(2, "0")}`;
};
const AudioPlayer = React.forwardRef(
  ({
    className,
    src,
    title,
    artist,
    isPlaying: controlledIsPlaying,
    currentTime: controlledCurrentTime,
    volume: controlledVolume,
    playbackRate: controlledPlaybackRate,
    showVolumeControl = true,
    showSpeedControl = true,
    isLoading = false,
    isBuffering = false,
    error,
    disabled = false,
    enableKeyboardShortcuts = false,
    onPlay,
    onPause,
    onSeek,
    onVolumeChange,
    onSpeedChange,
    onError,
    onEnded,
    ...props
  }, ref) => {
    const audioRef = React.useRef(null);
    const [internalIsPlaying, setInternalIsPlaying] = React.useState(false);
    const [internalCurrentTime, setInternalCurrentTime] = React.useState(0);
    const [internalVolume, setInternalVolume] = React.useState(1);
    const [internalPlaybackRate, setInternalPlaybackRate] = React.useState(1);
    const [isMuted, setIsMuted] = React.useState(false);
    const [previousVolume, setPreviousVolume] = React.useState(1);
    const [duration, setDuration] = React.useState(0);
    const [isAudioLoading, setIsAudioLoading] = React.useState(true);
    const [audioError, setAudioError] = React.useState(null);
    const isPlaying = controlledIsPlaying ?? internalIsPlaying;
    const currentTime = controlledCurrentTime ?? internalCurrentTime;
    const volume = controlledVolume ?? internalVolume;
    const playbackRate = controlledPlaybackRate ?? internalPlaybackRate;
    const hasError = error || audioError || src === "";
    const getVolumeIcon = React.useCallback((vol, muted) => {
      if (muted || vol === 0) return VolumeX;
      if (vol < 0.33) return Volume1;
      if (vol < 0.66) return Volume1;
      return Volume2;
    }, []);
    const handlePlayPause = React.useCallback(async () => {
      if (!audioRef.current || disabled || hasError) return;
      try {
        if (isPlaying) {
          audioRef.current.pause();
          setInternalIsPlaying(false);
          onPause?.();
        } else {
          await audioRef.current.play();
          setInternalIsPlaying(true);
          onPlay?.();
        }
      } catch (err) {
        console.error("Playback error:", err);
        setAudioError("Failed to play audio");
      }
    }, [isPlaying, disabled, hasError, onPlay, onPause]);
    const handleSeek = React.useCallback(
      (newTime) => {
        if (!audioRef.current || disabled) return;
        const time = Math.min(Math.max(0, newTime), duration);
        audioRef.current.currentTime = time;
        setInternalCurrentTime(time);
        onSeek?.(time);
      },
      [duration, disabled, onSeek]
    );
    const handleVolumeChange = React.useCallback(
      (newVolume) => {
        if (!audioRef.current || disabled) return;
        const vol = Math.min(Math.max(0, newVolume), 1);
        audioRef.current.volume = vol;
        setInternalVolume(vol);
        onVolumeChange?.(vol);
        if (vol === 0) {
          setIsMuted(true);
        } else {
          setIsMuted(false);
          setPreviousVolume(vol);
        }
      },
      [disabled, onVolumeChange]
    );
    const handleMuteToggle = React.useCallback(() => {
      if (!audioRef.current || disabled) return;
      if (isMuted) {
        const volToRestore = previousVolume > 0 ? previousVolume : 1;
        audioRef.current.volume = volToRestore;
        setInternalVolume(volToRestore);
        setIsMuted(false);
        onVolumeChange?.(volToRestore);
      } else {
        setPreviousVolume(volume);
        audioRef.current.volume = 0;
        setInternalVolume(0);
        setIsMuted(true);
        onVolumeChange?.(0);
      }
    }, [disabled, isMuted, previousVolume, volume, onVolumeChange]);
    const handleSpeedChange = React.useCallback(
      (newSpeed) => {
        if (!audioRef.current || disabled) return;
        const speed = Math.min(Math.max(0.25, newSpeed), 2);
        audioRef.current.playbackRate = speed;
        setInternalPlaybackRate(speed);
        onSpeedChange?.(speed);
      },
      [disabled, onSpeedChange]
    );
    React.useEffect(() => {
      const audio = audioRef.current;
      if (!audio) return;
      const handleTimeUpdate = () => {
        setInternalCurrentTime(audio.currentTime);
      };
      const handleLoadedMetadata = () => {
        setDuration(audio.duration);
        setIsAudioLoading(false);
      };
      const handleEnded = () => {
        setInternalIsPlaying(false);
        onEnded?.();
      };
      const handleError = (e) => {
        setAudioError("Failed to load audio");
        setIsAudioLoading(false);
        onError?.(e);
      };
      audio.addEventListener("timeupdate", handleTimeUpdate);
      audio.addEventListener("loadedmetadata", handleLoadedMetadata);
      audio.addEventListener("ended", handleEnded);
      audio.addEventListener("error", handleError);
      return () => {
        audio.removeEventListener("timeupdate", handleTimeUpdate);
        audio.removeEventListener("loadedmetadata", handleLoadedMetadata);
        audio.removeEventListener("ended", handleEnded);
        audio.removeEventListener("error", handleError);
      };
    }, [onEnded, onError]);
    React.useEffect(() => {
      if (!enableKeyboardShortcuts) return;
      const handleKeyDown = (e) => {
        if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
          return;
        }
        switch (e.key) {
          case " ":
            e.preventDefault();
            handlePlayPause();
            break;
          case "ArrowLeft":
            e.preventDefault();
            handleSeek(currentTime - 10);
            break;
          case "ArrowRight":
            e.preventDefault();
            handleSeek(currentTime + 10);
            break;
          case "M":
          case "m":
            e.preventDefault();
            handleMuteToggle();
            break;
        }
      };
      document.addEventListener("keydown", handleKeyDown);
      return () => document.removeEventListener("keydown", handleKeyDown);
    }, [
      enableKeyboardShortcuts,
      handlePlayPause,
      handleSeek,
      handleMuteToggle,
      currentTime
    ]);
    React.useEffect(() => {
      if (!audioRef.current) return;
      if (controlledCurrentTime !== void 0 && Math.abs(audioRef.current.currentTime - controlledCurrentTime) > 0.1) {
        audioRef.current.currentTime = controlledCurrentTime;
      }
      if (controlledVolume !== void 0 && Math.abs(audioRef.current.volume - controlledVolume) > 0.01) {
        audioRef.current.volume = controlledVolume;
        setIsMuted(controlledVolume === 0);
      }
      if (controlledPlaybackRate !== void 0 && Math.abs(audioRef.current.playbackRate - controlledPlaybackRate) > 0.01) {
        audioRef.current.playbackRate = controlledPlaybackRate;
      }
      if (controlledIsPlaying !== void 0) {
        if (controlledIsPlaying && audioRef.current.paused) {
          audioRef.current.play().catch(console.error);
        } else if (!controlledIsPlaying && !audioRef.current.paused) {
          audioRef.current.pause();
        }
      }
    }, [
      controlledCurrentTime,
      controlledVolume,
      controlledPlaybackRate,
      controlledIsPlaying
    ]);
    const playerLabel = React.useMemo(() => {
      const parts = ["Audio player"];
      if (title) parts.push(title);
      if (artist) parts.push(`by ${artist}`);
      return parts.join(" - ");
    }, [title, artist]);
    const playButtonLabel = React.useMemo(() => {
      const action = isPlaying ? "Pause" : "Play";
      if (title && artist) return `${action} ${title} by ${artist}`;
      if (title) return `${action} ${title}`;
      return action;
    }, [isPlaying, title, artist]);
    const showError = hasError && !isLoading;
    const showLoading = isLoading || isAudioLoading;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        role: "region",
        "aria-label": playerLabel,
        className: cn(
          "flex flex-col gap-2 min-w-[280px]",
          disabled && "opacity-50",
          className
        ),
        ...props,
        children: [
          /* @__PURE__ */ jsx("audio", { ref: audioRef, src, preload: "metadata" }),
          showError && /* @__PURE__ */ jsxs(
            "div",
            {
              role: "alert",
              className: "flex items-center gap-2 text-base text-negative",
              children: [
                /* @__PURE__ */ jsx(CircleAlert, { className: "h-4 w-4" }),
                /* @__PURE__ */ jsx("span", { children: error || audioError || "No audio source provided" })
              ]
            }
          ),
          showLoading && /* @__PURE__ */ jsxs(
            "div",
            {
              role: "status",
              "aria-label": "Loading audio",
              className: "flex items-center gap-2 text-base text-subtle",
              children: [
                /* @__PURE__ */ jsx(LoaderCircle, { className: "h-4 w-4 animate-spin" }),
                /* @__PURE__ */ jsx("span", { children: "Loading audio..." })
              ]
            }
          ),
          isBuffering && !showLoading && /* @__PURE__ */ jsxs(
            "div",
            {
              role: "status",
              "aria-label": "Buffering",
              className: "flex items-center gap-2 text-base text-subtle",
              children: [
                /* @__PURE__ */ jsx(LoaderCircle, { className: "h-4 w-4 animate-spin" }),
                /* @__PURE__ */ jsx("span", { children: "Buffering..." })
              ]
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                size: "sm",
                className: "rounded-full",
                icon: isPlaying ? /* @__PURE__ */ jsx(Pause, { className: "h-4 w-4 fill-current" }) : /* @__PURE__ */ jsx(Play, { className: "h-4 w-4 fill-current" }),
                onClick: handlePlayPause,
                disabled: !!(disabled || hasError),
                "aria-label": playButtonLabel
              }
            ),
            (title || artist) && /* @__PURE__ */ jsxs("div", { className: "min-w-0  ", children: [
              title && /* @__PURE__ */ jsx("div", { className: "text-base font-medium text-foreground truncate", children: title }),
              artist && /* @__PURE__ */ jsx("div", { className: "text-base text-subtle truncate", children: artist })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2", children: [
              /* @__PURE__ */ jsx("span", { className: "text-base tabular-nums text-subtle whitespace-nowrap", children: formatTime(currentTime) }),
              /* @__PURE__ */ jsx(
                Slider,
                {
                  value: [currentTime],
                  max: duration || 100,
                  step: 1,
                  onValueChange: ([value]) => handleSeek(value),
                  disabled: !!(disabled || hasError || duration === 0),
                  className: "min-w-0 flex-1",
                  "aria-label": "Seek audio position",
                  "aria-valuemin": 0,
                  "aria-valuemax": duration,
                  "aria-valuenow": currentTime
                }
              ),
              /* @__PURE__ */ jsx("span", { className: "text-base tabular-nums text-subtle whitespace-nowrap", children: formatTime(duration) }),
              showVolumeControl && /* @__PURE__ */ jsxs(Popover, { children: [
                /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "sm",
                    variant: "secondary",
                    className: "h-8 w-8 p-0",
                    disabled,
                    "aria-label": `Volume ${Math.round((isMuted ? 0 : volume) * 100)}%`,
                    children: (() => {
                      const VolumeIcon = getVolumeIcon(volume, isMuted);
                      return /* @__PURE__ */ jsx(VolumeIcon, { className: "h-4 w-4" });
                    })()
                  }
                ) }),
                /* @__PURE__ */ jsx(PopoverContent, { className: "w-32 p-3", align: "start", children: /* @__PURE__ */ jsx(
                  Slider,
                  {
                    value: [isMuted ? 0 : volume],
                    max: 1,
                    step: 0.1,
                    onValueChange: ([value]) => handleVolumeChange(value),
                    disabled,
                    className: "w-full",
                    "aria-label": "Volume",
                    "aria-valuemin": 0,
                    "aria-valuemax": 1,
                    "aria-valuenow": isMuted ? 0 : volume
                  }
                ) })
              ] }),
              showSpeedControl && /* @__PURE__ */ jsxs(Popover, { children: [
                /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "sm",
                    variant: "secondary",
                    className: "h-8 w-10 p-2",
                    disabled,
                    "aria-label": `Playback speed ${playbackRate}x`,
                    children: /* @__PURE__ */ jsxs("span", { className: "text-base font-medium", children: [
                      playbackRate,
                      "x"
                    ] })
                  }
                ) }),
                /* @__PURE__ */ jsx(PopoverContent, { className: "w-32 px-2", align: "start", children: /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1", children: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => /* @__PURE__ */ jsxs(
                  Button,
                  {
                    size: "sm",
                    variant: playbackRate === speed ? "default" : "secondary",
                    className: "h-7 justify-start text-base border-none",
                    onClick: () => handleSpeedChange(speed),
                    disabled,
                    children: [
                      speed,
                      "x"
                    ]
                  },
                  speed
                )) }) })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            "div",
            {
              className: "sr-only",
              role: "status",
              "aria-live": "polite",
              "aria-atomic": "true",
              children: isPlaying ? "Playing" : "Paused"
            }
          )
        ]
      }
    );
  }
);
AudioPlayer.displayName = "AudioPlayer";
export {
  AudioPlayer
};
