import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '../stores/auth';

// Type du layout choisi par App.vue : 'bare' (login, sans coquille),
// 'shell' (sidebar + contenu centré), 'fullbleed' (terminal plein écran dans la coquille),
// 'ide' (vue Workspace plein écran SANS coquille : gère son propre layout 3 panneaux).
declare module 'vue-router' {
  interface RouteMeta {
    layout?: 'bare' | 'shell' | 'fullbleed' | 'ide';
  }
}

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', name: 'login', component: () => import('../views/LoginView.vue'), meta: { layout: 'bare' } },
    // Desktop : l'IDE est la vue par défaut. Mobile : supervision (dashboard + nav mobile),
    // l'IDE reste accessible via la nav mais dégrade en panneau unique.
    { path: '/', redirect: () => (typeof window !== 'undefined' && window.innerWidth < 768 ? { name: 'dashboard' } : { name: 'ide' }) },
    { path: '/dashboard', name: 'dashboard', component: () => import('../views/DashboardView.vue'), meta: { layout: 'shell' } },
    { path: '/sessions', name: 'sessions', component: () => import('../views/SessionsListView.vue'), meta: { layout: 'shell' } },
    { path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue'), meta: { layout: 'fullbleed' } },
    { path: '/ide', name: 'ide', component: () => import('../components/ide/IdeShell.vue'), meta: { layout: 'ide' } },
    { path: '/workspace/:repoId/:wt', name: 'workspace', component: () => import('../components/ide/IdeShell.vue'), meta: { layout: 'ide' } },
    { path: '/groups', name: 'groups', component: () => import('../views/GroupsListView.vue'), meta: { layout: 'shell' } },
    { path: '/groups/:id', name: 'group', component: () => import('../views/GroupView.vue'), meta: { layout: 'shell' } },
    { path: '/settings', name: 'settings', component: () => import('../views/SettingsView.vue'), meta: { layout: 'shell' } },
    { path: '/help', name: 'help', component: () => import('../views/HelpView.vue'), meta: { layout: 'shell' } },
    { path: '/:pathMatch(.*)*', redirect: '/' },
  ],
});

// Garde globale : tout sauf /login exige une session valide (GET /api/v1/auth/me, 401 → /login)
router.beforeEach(async (to) => {
  const auth = useAuthStore();
  if (auth.authenticated === null) await auth.check();
  if (to.name === 'login') return auth.authenticated ? { name: 'ide' } : true;
  return auth.authenticated ? true : { name: 'login', query: { redirect: to.fullPath } };
});
