<script>
  import { onMount } from 'svelte';
  import {
    LayoutDashboard,
    Database,
    Printer,
    Users,
    ClipboardList,
    FlaskConical,
    CheckCircle2,
    Building2,
    UserCircle,
    LogOut,
    List,
    MapPin,
    Stethoscope,
    Briefcase,
    Hash,
    Globe,
    ChevronDown,
    TestTube,
    FileText,
    X,
    Link,
    LandPlot,
    Monitor,
    Activity,
    User,
    Server,
    Network,
    FileCode,
    History
  } from 'lucide-svelte';
  import { auth } from '$lib/stores/auth.js';
  import { goto } from '$app/navigation';
  import { browser } from '$app/environment';

  let { isOpen = $bindable(false) } = $props();

// Collapsible section states - default collapsed
  let laboratoryExpanded = $state(false);
  let organizationExpanded = $state(false);
  let labSetupExpanded = $state(false);
  let usersContactsExpanded = $state(false);
  let referenceDataExpanded = $state(false);

  let lastSaved = '';

  function getSectionStates() {
    return {
      laboratory: laboratoryExpanded,
      organization: organizationExpanded,
      labSetup: labSetupExpanded,
      usersContacts: usersContactsExpanded,
      referenceData: referenceDataExpanded,
    };
  }

  function persistSectionStates() {
    if (!browser) return;
    const json = JSON.stringify(getSectionStates());
    if (json === lastSaved) return;
    lastSaved = json;
    localStorage.setItem('sidebar_section_states', json);
  }

  onMount(() => {
    if (browser) {
      const savedStates = localStorage.getItem('sidebar_section_states');
      if (savedStates) {
        try {
          const parsed = JSON.parse(savedStates);
          laboratoryExpanded = parsed.laboratory ?? false;
          organizationExpanded = parsed.organization ?? false;
          labSetupExpanded = parsed.labSetup ?? false;
          usersContactsExpanded = parsed.usersContacts ?? false;
          referenceDataExpanded = parsed.referenceData ?? false;
        } catch {
          // Keep defaults if parsing fails
        }
      }
    }

    lastSaved = JSON.stringify(getSectionStates());
    persistSectionStates();
  });

  // Function to expand sidebar when clicking dropdown in collapsed mode
  function expandSidebar() {
    isOpen = true;
  }

  // Function to close sidebar (for mobile)
  function closeSidebar() {
    isOpen = false;
  }

  function handleLogout() {
    auth.logout();
    goto('/login');
  }

  function toggleLaboratory() {
    if (!isOpen) {
      expandSidebar();
    }
    laboratoryExpanded = !laboratoryExpanded;
    persistSectionStates();
  }

  function toggleOrganization() {
    if (!isOpen) {
      expandSidebar();
    }
    organizationExpanded = !organizationExpanded;
    persistSectionStates();
  }

  function toggleLabSetup() {
    if (!isOpen) {
      expandSidebar();
    }
    labSetupExpanded = !labSetupExpanded;
    persistSectionStates();
  }

  function toggleUsersContacts() {
    if (!isOpen) {
      expandSidebar();
    }
    usersContactsExpanded = !usersContactsExpanded;
    persistSectionStates();
  }

  function toggleReferenceData() {
    if (!isOpen) {
      expandSidebar();
    }
    referenceDataExpanded = !referenceDataExpanded;
    persistSectionStates();
  }
</script>

<!-- Mobile Overlay Backdrop -->
{#if isOpen}
  <button
    type="button"
    class="sidebar-backdrop lg:hidden"
    onclick={closeSidebar}
    aria-label="Close sidebar"
  ></button>
{/if}

<!-- Sidebar -->
<div 
  class="sidebar-container fixed lg:sticky left-0 top-0 h-screen max-h-screen z-40 bg-base-200 border-r border-base-300 transition-all duration-300 ease-out"
  class:sidebar-expanded={isOpen}
  class:sidebar-collapsed={!isOpen}
  class:sidebar-hidden-mobile={!isOpen}
>
  <div class="h-screen overflow-y-auto flex flex-col sidebar-content" class:expanded={isOpen} class:collapsed={!isOpen}>
    <!-- Mobile Close Button -->
    <div class="lg:hidden flex justify-end p-2">
      <button 
        onclick={closeSidebar}
        class="btn btn-sm btn-ghost btn-square"
        aria-label="Close sidebar"
      >
        <X size={20} />
      </button>
    </div>
    
    <div>
<!-- Navigation Menu -->
      <ul class="menu w-full gap-1" class:menu-collapsed={!isOpen}>
        {#if isOpen}
          <li class="menu-title uppercase font-bold text-xs text-secondary/70 mt-2">Operations</li>
        {/if}
        
        <!-- Dashboard -->
        <li>
          <a 
            href="/dashboard" 
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Dashboard' : ''}
          >
            <LayoutDashboard size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Dashboard</span>
            {/if}
          </a>
        </li>

        <!-- Laboratory -->
        <li class="nav-group" class:collapsed={!isOpen}>
          <button 
            onclick={toggleLaboratory}
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Laboratory' : ''}
          >
            <FlaskConical size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Laboratory</span>
              <span class="chevron" class:expanded={laboratoryExpanded}>
                <ChevronDown size={16} />
              </span>
            {/if}
          </button>
          
{#if isOpen && laboratoryExpanded}
            <ul class="submenu">
              <li><a href="/patients" class="submenu-link"><Users size={16} /> Patients</a></li>
              <li><a href="/visits" class="submenu-link"><Activity size={16} /> Visits</a></li>
              <li><a href="/orders" class="submenu-link"><ClipboardList size={16} /> Orders</a></li>
              <li><a href="/specimens" class="submenu-link"><FlaskConical size={16} /> Specimens</a></li>
              <li><a href="/results" class="submenu-link"><CheckCircle2 size={16} /> Results</a></li>
              <li><a href="/patient-results" class="submenu-link"><History size={16} /> Patient History</a></li>
            </ul>
          {/if}
        </li>

        {#if isOpen}
          <li class="menu-title uppercase font-bold text-xs text-secondary/70 mt-4">Analytics</li>
        {/if}

        <!-- Reports -->
        <li>
          <a 
            href="/reports" 
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Reports' : ''}
          >
            <Printer size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Reports</span>
            {/if}
          </a>
        </li>

        {#if isOpen}
          <li class="menu-title uppercase font-bold text-xs text-secondary/70 mt-4">Configuration</li>
        {/if}

        <!-- Organization -->
        <li class="nav-group" class:collapsed={!isOpen}>
          <button 
            onclick={toggleOrganization}
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Organization' : ''}
          >
            <Building2 size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Organization</span>
              <span class="chevron" class:expanded={organizationExpanded}>
                <ChevronDown size={16} />
              </span>
            {/if}
          </button>
          
          {#if isOpen && organizationExpanded}
            <ul class="submenu">
              <li><a href="/master-data/organization/account" class="submenu-link"><User size={16} /> Account</a></li>
              <li><a href="/master-data/organization/site" class="submenu-link"><LandPlot size={16} /> Site</a></li>
              <li><a href="/master-data/organization/department" class="submenu-link"><Users size={16} /> Department</a></li>
              <li><a href="/master-data/organization/discipline" class="submenu-link"><Building2 size={16} /> Discipline</a></li>
              <li><a href="/master-data/organization/workstation" class="submenu-link"><Monitor size={16} /> Workstation</a></li>
              <li><a href="/master-data/organization/instrument" class="submenu-link"><Activity size={16} /> Instrument</a></li>
              <li><a href="/master-data/organization/hostapp" class="submenu-link"><Server size={16} /> Host Application</a></li>
              <li><a href="/master-data/organization/hostcompara" class="submenu-link"><Network size={16} /> Host Connection</a></li>
              <li><a href="/master-data/organization/codingsys" class="submenu-link"><FileCode size={16} /> Coding System</a></li>
            </ul>
          {/if}
        </li>

        <!-- Lab Setup -->
        <li class="nav-group" class:collapsed={!isOpen}>
          <button 
            onclick={toggleLabSetup}
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Lab Setup' : ''}
          >
            <FlaskConical size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Lab Setup</span>
              <span class="chevron" class:expanded={labSetupExpanded}>
                <ChevronDown size={16} />
              </span>
            {/if}
          </button>
          
          {#if isOpen && labSetupExpanded}
            <ul class="submenu">
              <li><a href="/master-data/containers" class="submenu-link"><FlaskConical size={16} /> Containers</a></li>
              <li><a href="/master-data/tests" class="submenu-link"><TestTube size={16} /> Test Definitions</a></li>
              <li><a href="/master-data/testmap" class="submenu-link"><Link size={16} /> Test Mapping</a></li>
              <li><a href="/rules" class="submenu-link"><FileText size={16} /> Rules</a></li>
            </ul>
          {/if}
        </li>

        <!-- Users & Contacts -->
        <li class="nav-group" class:collapsed={!isOpen}>
          <button 
            onclick={toggleUsersContacts}
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Users & Contacts' : ''}
          >
            <Users size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Users & Contacts</span>
              <span class="chevron" class:expanded={usersContactsExpanded}>
                <ChevronDown size={16} />
              </span>
            {/if}
          </button>
          
          {#if isOpen && usersContactsExpanded}
            <ul class="submenu">
              <li><a href="/master-data/users" class="submenu-link"><UserCircle size={16} /> Users</a></li>
              <li><a href="/master-data/contacts" class="submenu-link"><Users size={16} /> Contacts</a></li>
              <li><a href="/master-data/specialties" class="submenu-link"><Stethoscope size={16} /> Specialties</a></li>
              <li><a href="/master-data/occupations" class="submenu-link"><Briefcase size={16} /> Occupations</a></li>
            </ul>
          {/if}
        </li>

        <!-- Reference Data -->
        <li class="nav-group" class:collapsed={!isOpen}>
          <button 
            onclick={toggleReferenceData}
            class="nav-link"
            class:centered={!isOpen}
            title={!isOpen ? 'Reference Data' : ''}
          >
            <Database size={20} class="text-secondary flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Reference Data</span>
              <span class="chevron" class:expanded={referenceDataExpanded}>
                <ChevronDown size={16} />
              </span>
            {/if}
          </button>
          
          {#if isOpen && referenceDataExpanded}
            <ul class="submenu">
              <li><a href="/master-data/valuesets" class="submenu-link"><List size={16} /> ValueSets</a></li>
              <li><a href="/master-data/locations" class="submenu-link"><MapPin size={16} /> Locations</a></li>
              <li><a href="/master-data/counters" class="submenu-link"><Hash size={16} /> Counters</a></li>
              <li><a href="/master-data/geography" class="submenu-link"><Globe size={16} /> Geography</a></li>
            </ul>
          {/if}
        </li>
        
        <!-- Logout -->
        {#if isOpen}
          <li class="mt-2 pt-2 border-t border-gray-200"></li>
        {/if}
        <li>
          <button 
            onclick={handleLogout} 
            class="nav-link text-red-500 hover:bg-red-50"
            class:centered={!isOpen}
            title={!isOpen ? 'Logout' : ''}
          >
            <LogOut size={20} class="flex-shrink-0" />
            {#if isOpen}
              <span class="nav-text">Logout</span>
            {/if}
          </button>
        </li>
      </ul>
    </div>
  </div>
</div>

<style>
  .sidebar-container {
    overflow: visible;
    transition: width 300ms ease-out, transform 300ms ease-out;
  }

  .sidebar-expanded {
    width: 16rem;
  }

  .sidebar-collapsed {
    width: 3.5rem;
  }

  /* Mobile: Hide sidebar completely when collapsed */
  @media (max-width: 1023px) {
    .sidebar-hidden-mobile {
      width: 0;
      transform: translateX(-100%);
      opacity: 0;
      pointer-events: none;
    }
    
    .sidebar-expanded {
      width: 16rem;
      transform: translateX(0);
      opacity: 1;
      pointer-events: auto;
    }
  }

  /* Mobile backdrop overlay */
  .sidebar-backdrop {
    position: fixed;
    inset: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 30;
    cursor: pointer;
  }

  .sidebar-content {
    transition: width 300ms ease-out;
  }

  .sidebar-content.expanded {
    width: 16rem;
  }

  .sidebar-content.collapsed {
    width: 3.5rem;
  }

  .nav-link {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.5rem 0.75rem;
    border-radius: 0.375rem;
    color: hsl(var(--bc));
    transition: background-color 0.2s;
    width: 100%;
    border: none !important;
    outline: none !important;
  }

  .nav-link:hover {
    background-color: hsl(var(--b3));
  }

  .nav-link.centered {
    justify-content: center;
    padding: 0.5rem;
    width: 2.5rem;
    height: 2.5rem;
    margin: 0 auto;
  }

  /* Fix for collapsed menu items - override DaisyUI .menu styles */
  :global(.menu-collapsed li) {
    display: flex !important;
    justify-content: center !important;
    align-items: center !important;
    width: 100% !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }

  :global(.menu-collapsed li > a),
  :global(.menu-collapsed li > button) {
    margin: 0 !important;
    border: none !important;
    box-sizing: border-box !important;
  }

  .nav-text {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
  }

  .chevron {
    flex-shrink: 0;
    transition: transform 0.2s;
  }

  .chevron.expanded {
    transform: rotate(180deg);
  }

  .nav-group {
    position: relative;
  }

.submenu {
    margin-left: 1.5rem;
    margin-top: 0.25rem;
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
    animation: slideDown 0.2s ease-out;
  }

  .submenu-link {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.375rem 0.5rem;
    font-size: 0.875rem;
    color: hsl(var(--bc) / 0.8);
    border-radius: 0.25rem;
    transition: all 0.15s;
  }

  .submenu-link:hover {
    background-color: hsl(var(--b3));
    color: hsl(var(--bc));
  }

  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-4px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
</style>
