// -----------------------------------------------------------------------------
// src/router/index.ts
// -----------------------------------------------------------------------------
import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
  type RouteRecordRaw,
} from 'vue-router'

import HomePage from '@/components/HomePage.vue'
import AgentLibraryPage from '@/components/AgentLibraryPage.vue'
import ConversationPage from '@/components/ConversationPage.vue'
import NewAgent from '@/components/NewAgent.vue'
import DashboardPage from '@/components/DashboardPage.vue'

// -----------------------------------------------------------------------------
// 1. Route table
// -----------------------------------------------------------------------------
const routes: RouteRecordRaw[] = [
  { path: '/', name: 'Home', component: HomePage },
  { path: '/agents', name: 'AgentLibrary', component: AgentLibraryPage },
  {
    path: '/conversations',
    name: 'Conversations',
    component: ConversationPage,
    props: (route) => ({
      submit: route.query.submit === 'true' || false,
    }),
  },
  { path: '/agents/new', name: 'NewAgent', component: NewAgent },
  { path: '/agents/:id/edit', name: 'EditAgent', component: NewAgent },
  { path: '/dashboard', name: 'Dashboard', component: DashboardPage },
]

// -----------------------------------------------------------------------------
// 2. Detect <base href="…"> that DSS injects
// -----------------------------------------------------------------------------
function getBase(): string {
  const href = document.querySelector('base')?.getAttribute('href') ?? '/'
  // Vue Router wants the base to **start and end** with a slash
  let base = href.startsWith('/') ? href : `/${href}`
  base = base.endsWith('/') ? base : `${base}/`
  return base
}

function pickHistory() {
  const base = getBase()
  return window.location.pathname.startsWith(base)
    ? createWebHistory(base)
    : createWebHashHistory(base) // fallback for DSS iframe
}

// -----------------------------------------------------------------------------
// 4. Create & export the router
// -----------------------------------------------------------------------------
export default createRouter({
  history: pickHistory(),
  routes,
  scrollBehavior() {
    // always scroll to top on navigation change
    return { top: 0 }
  },
})
