import { computed, onMounted, ref } from "vue";

import type { AppInfo, DemoPackSummary, PlayerView } from "@contracts";

import { getAppInfo, getDemoPackSummary, getDemoPlayerView } from "./bridge";

export function useDemo() {
  const appInfo = ref<AppInfo | null>(null);
  const pack = ref<DemoPackSummary | null>(null);
  const playerView = ref<PlayerView | null>(null);
  const loading = ref(true);
  const error = ref<string | null>(null);

  const latestBeat = computed(() => playerView.value?.beats.at(-1) ?? null);

  onMounted(async () => {
    try {
      [appInfo.value, pack.value, playerView.value] = await Promise.all([
        getAppInfo(),
        getDemoPackSummary(),
        getDemoPlayerView()
      ]);
    } catch (reason) {
      error.value = reason instanceof Error ? reason.message : String(reason);
    } finally {
      loading.value = false;
    }
  });

  return {
    appInfo,
    error,
    latestBeat,
    loading,
    pack,
    playerView
  };
}
