<script lang="ts">
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import '../app.css';
  import { Toaster } from 'svelte-sonner';
  import { LayoutDashboard, Phone, Cable, Users, ArrowLeftRight } from 'lucide-svelte';

  let token: string | null = null;
  let user: { username: string; role: string } | null = null;

  function updateAuth() {
    token = typeof localStorage !== 'undefined' ? localStorage.getItem('token') : null;
    if (token) {
      try { user = JSON.parse(atob(token.split('.')[1])); } catch { user = null; }
    } else {
      user = null;
    }
  }

  function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    updateAuth();
    goto('/login');
  }

  let pathname = $derived($page.url.pathname);

  $effect(() => {
    $page.url.pathname;
    updateAuth();
  });
</script>

<Toaster position="top-right" />

{#if pathname !== '/login'}
  <div class="flex min-h-screen">
    <!-- Sidebar -->
    <aside class="w-64 border-r bg-card flex flex-col">
      <div class="p-4 border-b">
        <h1 class="text-lg font-bold text-primary">pulse-lets-go</h1>
        <p class="text-xs text-muted-foreground">Telephone Balancer</p>
      </div>

      <nav class="flex-1 p-3 space-y-1">
        <a href="/" class="flex items-center gap-2 px-3 py-2 rounded-md text-sm {pathname === '/' ? 'bg-primary text-primary-foreground' : 'hover:bg-secondary'}">
          <LayoutDashboard class="h-4 w-4" /> Дашборд
        </a>
        <a href="/nodes" class="flex items-center gap-2 px-3 py-2 rounded-md text-sm {pathname === '/nodes' ? 'bg-primary text-primary-foreground' : 'hover:bg-secondary'}">
          <Phone class="h-4 w-4" /> Ноды
        </a>
        <a href="/trunks" class="flex items-center gap-2 px-3 py-2 rounded-md text-sm {pathname === '/trunks' ? 'bg-primary text-primary-foreground' : 'hover:bg-secondary'}">
          <Cable class="h-4 w-4" /> Транки
        </a>
        <a href="/routing" class="flex items-center gap-2 px-3 py-2 rounded-md text-sm {pathname === '/routing' ? 'bg-primary text-primary-foreground' : 'hover:bg-secondary'}">
          <ArrowLeftRight class="h-4 w-4" /> Маршрутизация
        </a>
        <a href="/users" class="flex items-center gap-2 px-3 py-2 rounded-md text-sm {pathname === '/users' ? 'bg-primary text-primary-foreground' : 'hover:bg-secondary'}">
          <Users class="h-4 w-4" /> Пользователи
        </a>
      </nav>

      <div class="p-3 border-t text-sm text-muted-foreground">
        <span>{user?.username ?? '--'}</span>
        <span class="mx-1">({user?.role ?? '--'})</span>
        <button on:click={logout} class="ml-2 text-destructive hover:underline text-xs">Выйти</button>
      </div>
    </aside>

    <!-- Main content -->
    <main class="flex-1 p-6">
      <slot />
    </main>
  </div>
{:else}
  <slot />
{/if}
