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

  let token: string | null = browser ? localStorage.getItem('token') : null;
  let user: { username: string; role: string } | null = token
    ? (() => { try { return JSON.parse(atob(token.split('.')[1])); } catch { return null; } })()
    : null;

  function logout() {
    if (browser) {
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
    }
    token = null;
    user = null;
  }

  $: pathname = browser ? window.location.pathname : '';
  $: isLogin = pathname === '/login';
</script>

<Toaster position="top-right" />

{#if !isLogin}
  <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="/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}
