<script setup lang="ts">
import WaveSurfer from "wavesurfer.js";

const props = defineProps({
  audioUrl: { type: String, default: "" },
});

const waveform = ref<HTMLDivElement | null>(null);
const isPlaying = ref(false);
const isLoading = ref(true);

const ws = ref<WaveSurfer | null>(null);
let themeObserver: MutationObserver | null = null;

const emit = defineEmits<{
  (e: "play" | "pause"): void;
}>();

const getCssVar = (name: string) =>
  getComputedStyle(document.documentElement).getPropertyValue(name).trim();

const applyThemeColors = () => {
  if (!ws.value) return;
  const waveBgColor = getCssVar("--surface-background-reverse");
  if (waveBgColor) {
    ws.value.setOptions?.({ waveColor: waveBgColor });
  }
};

const playPause = () => {
  if (!ws.value) return;
  ws.value.playPause();
  isPlaying.value = !!ws.value.isPlaying?.();
  if (isPlaying.value) emit("play");
  else emit("pause");
};

const reset = () => {
  if (ws.value) {
    ws.value.stop();
    isPlaying.value = false;
  }
};

onMounted(() => {
  ws.value = WaveSurfer.create({
    container: waveform.value!,
    // Use CSS var so it follows light/dark theme
    waveColor: getComputedStyle(document.documentElement)
      .getPropertyValue("--surface-background-reverse")
      .trim(),
    progressColor: "oklch(0.7352 0.1277 211.3)",
    height: 100,
  });

  if (props.audioUrl) {
    ws.value.load(props.audioUrl);
  }

  ws.value.on("ready", () => {
    isLoading.value = false;
  });

  ws.value.on("finish", () => {
    isPlaying.value = false;
    emit("pause");
  });

  themeObserver = new MutationObserver(() => applyThemeColors());
  themeObserver.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ["class"],
  });
});

onBeforeUnmount(() => {
  ws.value?.destroy();
  themeObserver?.disconnect();
});

defineExpose({
  playPause,
  reset,
  isPlaying,
});
</script>

<template>
  <div class="relative">
    <div class="h-[100px] w-full">
      <Skeleton v-if="isLoading" class="h-full w-full" />
      <div ref="waveform" class="h-full w-full" />
    </div>
  </div>
</template>
