import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { setupGuards } from './guards'

const routes: RouteRecordRaw[] = [
  // --- Marketing (public, no auth) ---
  {
    path: '/',
    name: 'landing',
    component: () => import('@/views/LandingView.vue'),
    meta: { public: true },
  },
  {
    path: '/docs',
    name: 'docs',
    component: () => import('@/views/DocsView.vue'),
    meta: { public: true },
  },
  {
    path: '/changelog',
    name: 'changelog',
    component: () => import('@/views/ChangelogView.vue'),
    meta: { public: true },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue'),
    meta: { public: true },
  },

  // --- App (authenticated) ---
  {
    path: '/app/',
    redirect: () => {
      const session = window.__SPECWRIGHT__
      const org = session?.org
      if (!org) {
        return '/login'
      }
      return `/app/${org}/`
    },
  },
  {
    path: '/app/:org/',
    name: 'dashboard',
    component: () => import('@/views/DashboardView.vue'),
  },
  {
    path: '/app/:org/welcome',
    name: 'welcome',
    component: () => import('@/views/WelcomeView.vue'),
  },
  {
    path: '/app/:org/tasks',
    name: 'tasks',
    component: () => import('@/views/TasksView.vue'),
  },
  {
    path: '/app/:org/search',
    name: 'search',
    component: () => import('@/views/SearchView.vue'),
  },
  {
    path: '/app/:org/repos/:owner/:repo',
    name: 'repo',
    component: () => import('@/views/RepoView.vue'),
  },
  {
    path: '/app/:org/specs/:owner/:repo/:path(.*)',
    name: 'spec',
    component: () => import('@/views/SpecView.vue'),
  },
  {
    path: '/app/:org/docs/:owner/:repo/:path(.*)',
    name: 'doc',
    component: () => import('@/views/DocView.vue'),
  },
  {
    path: '/app/:org/profile',
    name: 'profile',
    component: () => import('@/views/ProfileView.vue'),
  },
  {
    path: '/app/:org/editor',
    name: 'editor-list',
    component: () => import('@/views/EditorView.vue'),
  },
  {
    path: '/app/:org/editor/:owner/:repo/new',
    name: 'editor-new',
    component: () => import('@/views/EditorView.vue'),
  },
  {
    path: '/app/:org/editor/:owner/:repo/config',
    name: 'editor-config',
    component: () => import('@/views/EditorView.vue'),
  },
  {
    path: '/app/:org/editor/:owner/:repo/:path(.*)',
    name: 'editor-edit',
    component: () => import('@/views/EditorView.vue'),
  },
  {
    path: '/app/admin/indexing',
    name: 'admin-indexing',
    component: () => import('@/views/AdminIndexingView.vue'),
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to) {
    if (to.hash) {
      return { el: to.hash, behavior: 'smooth' }
    }
    return { top: 0 }
  },
})

setupGuards(router)

export default router
