<template>
  <Providers>
    <Toaster richColors position="bottom-center" />
    <AppSidebar />
    <main class="flex flex-col grow overflow-auto h-screen">
      <Header v-model="viewMode" />
      <TopBar />

      <TraceViewer v-model="viewMode" />
    </main>
  </Providers>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { toast } from 'vue-sonner'

import { API } from '@/Api'
import { ViewMode } from '@/common/views'
import AppSidebar from '@/components/app-sidebar/AppSidebar.vue'
import TraceViewer from '@/components/trace-viewer/TraceViewer.vue'
import { Toaster } from '@/components/ui/sonner'
import Header from '@/components/Header.vue'
import TopBar from '@/components/topbar/TopBar.vue'
import { useTracesStore } from '@/stores/traces'
import { getLocalTraceItemName, getRawTraceFromLS, getTraceFromLS } from '@/utils/localStorage'
import { EXPLORE_TRACE_STORAGE_KEY, URL_EXPLORE_TRACE_PARAM_KEY } from '@/utils/config'
import { prepareTrace } from '@/utils/prepareTrace'

import Providers from './Providers.vue'

const viewMode = ref<ViewMode>(ViewMode.Tree)
const tracesStore = useTracesStore()

onMounted(async () => {
  // loading local trace
  const itemName = getLocalTraceItemName(window.location.href)
  tracesStore.localTrace = getTraceFromLS(itemName)

  // loading explore trace
  const urlObj = new URL(window.location.href)
  if (urlObj.searchParams.get(URL_EXPLORE_TRACE_PARAM_KEY) == 'true') {
    const exploreTraceLS = getRawTraceFromLS(EXPLORE_TRACE_STORAGE_KEY)
    const { trace, error } = prepareTrace(exploreTraceLS, 'Explore Trace')

    if (error) {
      console.error(error)
      toast.error("Couldn't retrieve trace.")
    } else {
      tracesStore.localTrace = trace
      if (trace?.id) {
        localStorage.setItem(getLocalTraceItemName(window.location.href), JSON.stringify(trace))
        tracesStore.selectedTraceId = trace?.id
      }
    }
  }

  // loading dataset traces
  try {
    tracesStore.datasetTraces = await API.listTraces()
    tracesStore.setupFilters()
  } catch (err) {
    console.error('Error loading traces:', err)
    toast.error("Couldn't retrieve traces from dataset.")
  } finally {
    tracesStore.isLoadingList = false
  }
})
</script>
