<script>
  import { goto } from '$app/navigation';
  import { auth } from '$lib/stores/auth.js';
  import { logout as logoutApi } from '$lib/api/auth.js';
  import { onMount } from 'svelte';
  import { browser } from '$app/environment';
  import Sidebar from '$lib/components/Sidebar.svelte';
  import { Menu, BarChart3, User, Settings, LogOut } from 'lucide-svelte';

  let { children } = $props();
  let checking = $state(true);
  // Start closed on mobile, open on desktop
  let sidebarOpen = $state(true);

  onMount(async () => {
    // Check authentication via cookie
    const isAuthenticated = await auth.checkAuth();
    if (!isAuthenticated) {
      goto('/login');
    } else {
      checking = false;
    }

    // On mobile, start with sidebar closed
    if (browser && window.innerWidth < 1024) {
      sidebarOpen = false;
    }
  });

  function toggleSidebar() {
    sidebarOpen = !sidebarOpen;
  }

  async function handleLogout() {
    try {
      // Call server logout to clear the cookie
      await logoutApi();
    } catch (error) {
      console.error('Logout error:', error);
    }
    // Clear client-side auth state
    auth.logout();
    goto('/login');
  }
</script>

{#if checking}
  <div class="flex min-h-screen items-center justify-center">
    <span class="loading loading-spinner loading-lg text-primary"></span>
  </div>
{:else}
  <div class="min-h-screen bg-gradient-to-br from-base-200 via-base-100 to-emerald-50/20 flex">
    <!-- Sidebar - Fixed on mobile, sticky on desktop -->
    <div class="lg:sticky lg:top-0 lg:h-screen lg:self-start flex-shrink-0 overflow-visible w-0 lg:w-auto">
      <Sidebar bind:isOpen={sidebarOpen} />
    </div>
    
    <!-- Main Content -->
    <div class="main-content flex-1 flex flex-col min-h-screen transition-all duration-300">
      <!-- Header -->
      <div class="navbar bg-base-100 shadow-sm border-b border-base-300">
        <div class="flex-none">
          <button 
            class="btn btn-square btn-ghost text-gray-600 hover:bg-emerald-50 hover:text-emerald-600"
            onclick={toggleSidebar}
            aria-label="Toggle sidebar"
          >
            <Menu class="w-6 h-6" />
          </button>
        </div>
        <div class="flex-1">
          <a href="/dashboard" class="btn btn-ghost text-xl font-bold text-gray-800 hover:bg-gray-100">
            <BarChart3 class="w-6 h-6 mr-2 text-emerald-600" />
            CLQMS Dashboard
          </a>
        </div>
        <div class="flex-none gap-2">
          <div class="dropdown dropdown-end">
            <button tabindex="0" class="btn btn-ghost btn-circle avatar placeholder hover:bg-emerald-50">
              <div class="bg-emerald-100 text-emerald-700 rounded-full w-10 border-2 border-emerald-200 flex items-center justify-center">
                <span class="font-semibold">{$auth.user?.name?.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase() || 'U'}</span>
              </div>
            </button>
            <ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow-xl bg-base-100 rounded-box w-52 border border-emerald-200 mt-3">
              <li>
                <a href="/profile" class="hover:bg-emerald-50">
                  <User class="w-4 h-4 text-emerald-600" />
                  Profile
                </a>
              </li>
              <li>
                <a href="/settings" class="hover:bg-emerald-50">
                  <Settings class="w-4 h-4 text-emerald-600" />
                  Settings
                </a>
              </li>
              <div class="divider my-0"></div>
              <li>
                <button onclick={handleLogout} class="text-error hover:bg-red-50">
                  <LogOut class="w-4 h-4" />
                  Logout
                </button>
              </li>
            </ul>
          </div>
        </div>
      </div>

      <!-- Main content area -->
      <main class="flex-1 overflow-auto">
        {@render children()}
      </main>

      <!-- Footer -->
      <footer class="footer footer-center p-4 bg-base-200 text-base-content border-t border-base-300">
        <div class="flex items-center justify-center gap-2 text-sm">
          <span class="font-semibold text-emerald-600">CLQMS</span>
          <span class="text-gray-500">|</span>
          <span class="text-gray-600">Clinical Laboratory Quality Management System</span>
          <span class="text-gray-500">|</span>
          <span class="text-gray-500">&copy; 2026</span>
        </div>
      </footer>
    </div>
  </div>
{/if}
