<script>
  import { onMount, onDestroy } from 'svelte'
  import { isAuthenticated, authMode } from './store.js'
  import { currentRoute } from './router.js'
  import { api } from './api.js'
  import { initWS, destroyWS } from './wsStore.js'
  import Nav from './components/Nav.svelte'
  import BottomNav from './components/BottomNav.svelte'
  import Login from './pages/Login.svelte'
  import SetupWizard from './pages/SetupWizard.svelte'
  import Overview from './pages/Overview.svelte'
  import Agents from './pages/Agents.svelte'
  import Approvals from './pages/Approvals.svelte'
  import Sessions from './pages/Sessions.svelte'
  import Schedules from './pages/Schedules.svelte'
  import Skills from './pages/Skills.svelte'
  import Chat from './pages/Chat.svelte'
  import Tools from './pages/Tools.svelte'
  import Browser from './pages/Browser.svelte'
  import KV from './pages/KV.svelte'
  import ApiKeys from './pages/ApiKeys.svelte'
  import Costs from './pages/Costs.svelte'
  import ServerConfig from './pages/ServerConfig.svelte'
  import Providers from './pages/Providers.svelte'
  import Settings from './pages/Settings.svelte'
  import AuditLog from './pages/AuditLog.svelte'
  import Channels from './pages/Channels.svelte'
  import MoreMenu from './pages/MoreMenu.svelte'
  import './shared.css'

  // Top-level route segment only (e.g. 'agents' from 'agents/detail').
  let route = $derived($currentRoute.split('/')[0])

  let showWizard = $state(false)

  async function checkWizard() {
    if (localStorage.getItem('dk_wizard_state')) {
      showWizard = true
      return
    }
    try {
      const ob = await api.onboarding()
      if (!ob.wizard_completed) {
        showWizard = true
      }
    } catch { /* ignore — e.g. insufficient scope */ }
  }

  // On mount, check if we have a valid session cookie (e.g. after OIDC redirect)
  // and initialize the global WebSocket connection.
  onMount(async () => {
    try {
      const sess = await api.sessionCheck()
      if (sess.authenticated) {
        authMode.set('session')
      }
    } catch {
      // Session check failed — fall through to login.
    }
    initWS()
  })
  onDestroy(() => destroyWS())

  $effect(() => {
    if ($isAuthenticated) checkWizard()
  })
</script>

{#if !$isAuthenticated}
  <Login />
{:else if showWizard}
  <SetupWizard onComplete={() => { showWizard = false }} />
{:else}
  <div class="shell">
    <Nav active={route} />
    <main class="content">
      {#if route === 'overview' || route === ''}
        <Overview />
      {:else if route === 'agents'}
        <Agents />
      {:else if route === 'approvals'}
        <Approvals />
      {:else if route === 'sessions'}
        <Sessions />
      {:else if route === 'schedules'}
        <Schedules />
      {:else if route === 'skills'}
        <Skills />
      {:else if route === 'tools'}
        <Tools />
      {:else if route === 'browser'}
        <Browser />
      {:else if route === 'kv'}
        <KV />
      {:else if route === 'chat'}
        <Chat />
      {:else if route === 'server'}
        <ServerConfig />
      {:else if route === 'providers'}
        <Providers />
      {:else if route === 'costs'}
        <Costs />
      {:else if route === 'keys'}
        <ApiKeys />
      {:else if route === 'channels'}
        <Channels />
      {:else if route === 'audit'}
        <AuditLog />
      {:else if route === 'settings'}
        <Settings />
      {:else if route === 'more'}
        <MoreMenu />
      {:else}
        <p style="color: var(--text-muted)">Page not found.</p>
      {/if}
    </main>
    <BottomNav active={route} />
  </div>
{/if}

<style>
  :global(*, *::before, *::after) {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  :global(:root) {
    --bg:          #fffbf7;
    --surface:     #faf5eb;
    --border:      #e8dcc8;
    --text:        #3d2a1e;
    --text-muted:  #8a7a6a;
    --accent:      #c84e35;
    --accent-hover:#b5432c;
    --danger:      #c43a3a;
    --success:     #3d8f62;
    --warn:        #c87e30;
    --radius:      6px;
    --hover-overlay: rgba(0, 0, 0, 0.04);
    --overlay-bg:    rgba(0, 0, 0, 0.4);
    --bottom-nav-height: 60px;
    --safe-area-bottom: env(safe-area-inset-bottom, 0px);

    /* Sidebar tokens */
    --sidebar-bg:           #FDF8F0;
    --sidebar-text:         #3d3d3a;
    --sidebar-section-label: rgba(0, 0, 0, 0.4);
    --sidebar-border-accent: rgba(192, 68, 44, 0.15);
    --sidebar-active-bg:    rgba(192, 68, 44, 0.08);
    --sidebar-hover-bg:     rgba(0, 0, 0, 0.04);
    --sidebar-divider:      rgba(0, 0, 0, 0.08);
  }

  :global(:root.dark) {
    --bg:          #1a1210;
    --surface:     #241c18;
    --border:      #3a2e26;
    --text:        #e8ddd4;
    --text-muted:  #9a8a7a;
    --accent:      #e07a5a;
    --accent-hover:#eb9070;
    --danger:      #e05c6e;
    --success:     #4caf7d;
    --warn:        #f0a958;
    --hover-overlay: rgba(255, 255, 255, 0.03);
    --overlay-bg:    rgba(0, 0, 0, 0.6);

    /* Sidebar tokens */
    --sidebar-bg:           #1E1C19;
    --sidebar-text:         #d4d0c8;
    --sidebar-section-label: rgba(255, 255, 255, 0.35);
    --sidebar-border-accent: rgba(207, 100, 75, 0.25);
    --sidebar-active-bg:    rgba(207, 100, 75, 0.15);
    --sidebar-hover-bg:     rgba(255, 255, 255, 0.06);
    --sidebar-divider:      rgba(255, 255, 255, 0.08);
  }

  :global(body) {
    background: var(--bg);
    color: var(--text);
    font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
    font-size: 14px;
    line-height: 1.5;
  }

  :global(a) {
    color: var(--accent);
    text-decoration: none;
  }

  :global(a:hover) {
    color: var(--accent-hover);
  }

  .shell {
    display: flex;
    height: 100vh;
    overflow: hidden;
  }

  .content {
    flex: 1;
    overflow-y: auto;
    padding: 28px 32px;
  }

  @media (max-width: 768px) {
    .content {
      padding: 16px 16px calc(var(--bottom-nav-height) + var(--safe-area-bottom) + 16px);
    }
  }
</style>
