<script lang="ts">
  import cookies from 'js-cookie';
  import Icon from "@iconify/svelte"
  import { get } from 'svelte/store';

  import { userStore, openWindowLogin } from "$lib/stores/use-user";
	import { SIDEBAR_MENUS } from "$lib/utils";
  import HFLogo from "$lib/assets/hf-logo.svg";

	import Menu from "./Menu.svelte";

  let isOpen = false;
  let user = get(userStore);

  const handleClick = () => {
    const app = document.getElementById("app");
    if (!app) return;
  
    app.classList[isOpen ? 'remove' : 'add']("overflow-hidden");
    isOpen = !isOpen;
  }

  const logout = async () => {
    cookies.remove("hf_access_token");
    window.location.href = "/";
  }
  // if (!e.data.code) return;
  //   if (e.data.type === "user-oauth" && e?.data?.code && !events.code) {
  //     events.code = e.data.code;
  //     loginFromCode(e.data.code);
  //   }
</script>

<button class="bg-transparent absolute top-10 right-8 cursor-pointer xl:hidden" on:click="{handleClick}">
  <Icon icon="{isOpen ? "mdi:hamburger-remove" : "mdi:hamburger-plus"}" class="w-7 h-7 text-white relative z-10" />
</button>
<aside class="bg-neutral-950 h-screen border-r border-neutral-800 w-full max-w-[344px] absolute -translate-x-full xl:translate-x-0 transition-all duration-200 xl:relative z-20 xl:z-0 flex flex-col justify-between" class:translate-x-0={isOpen}>
  <div class="w-full">
    <header class="text-white px-8 pb-8 pt-10 text-xl tracking-wider font-semibold">
      LoRA Studio
    </header>
    <div class="px-4">
      <ul class="grid grid-cols-1 gap-2">
        {#each SIDEBAR_MENUS as menu}
          <Menu href={menu.href}>
            <Icon icon={menu.icon} class="w-5 h-5" />
            {menu.label}
          </Menu>
          
        {/each}
      </ul>
      <hr class="border-neutral-800/50 mt-10 mx-4">
      <Menu href="https://huggingface.co/">
        <Icon icon="ph:question-fill" class="w-5 h-5" />
        Help
      </Menu>
    </div>
  </div>
  {#if user?.picture}
    <footer class="text-white text-center text-base pb-8 px-8 flex items-center justify-between gap-4">
      <div class="flex items-center justify-start gap-4">
        <img src={user.picture} alt="User avatar" class="w-10 h-10 rounded-full border-2 border-white inline-block" />
        <div class="w-full text-left">
          <p class="text-lg font-semibold">{user.name}</p>
          <p class="text-sm leading-none text-neutral-400">{user.preferred_username}</p>
        </div>
      </div>
      <button on:click={logout}>
        <Icon icon="solar:logout-2-bold" class="text-red-500 hover:text-red-400 w-7 h-7" />
      </button>
    </footer>
  {:else}
    <button
      class="text-white text-center text-base pb-8 px-8 flex items-center justify-center gap-2 cursor-pointer"
      on:click={openWindowLogin}  
    >
      <img src={HFLogo} alt="Hugging Face logo" class="w-8 h-8 inline-block" />
      <u>Sign in with Hugging Face</u>
    </button>
  {/if}
</aside>