<script setup lang="ts">
import { computed, ref, Ref, nextTick, onMounted, watch, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import {
  GrSidebar,
  GrSideHeader,
  GrSideItem,
  GrSideItemDrop,
  GrButton,
  GrAvatar,
  GrDropDown,
  GrDropDownTrigger,
  GrDropdownMenuGroup,
  GrDropDownContent,
  GrDropDownItem,
  GrDropDownSeparator,
  GrParagraph,
} from "@/components";
import {
  iconSideDashboard,
  iconSideSales,
  iconSideProducts,
  iconSideFinancial,
  iconSideMarketing,
  iconSideReports,
  iconSideSystem,
  iconDropDownAccount,
  iconDropDownMySales,
  iconDropDownExit,
} from "@/components/sidebar/icons";

interface IPropsItem {
  name: string;
  route: string;
  active: boolean;
  item: string;
}

type ActiveItems = {
  [key: string]: boolean;
};

interface HeaderElementRef {
  header: HTMLElement | undefined;
}

const router = useRoute();

const headerHeight = ref<number>(0);
const headerClientHeight = ref<number>(0);
const headerMarginTop = ref<number>(0);
const headerMarginBottom = ref<number>(0);

const GrSideHeaderRef = ref<InstanceType<typeof GrSideHeader> | null>(null);
const GrSidebarRef = ref<InstanceType<typeof GrSidebar> | null>(null);

const hoverInSideBar = ref<boolean>(false);
const hovered = ref<boolean>(false);
const activeSidebar = ref<boolean>(false);
const browsingByKey = ref(<boolean>false);

const avatarSrc = ref<string | undefined>();

import("@/assets/icons/user-greenn.svg").then((module) => {
  avatarSrc.value = module.default;
});

const activeItems = ref<ActiveItems>({
  Vendas: false,
  Produtos: false,
  Financeiro: false,
  Marketing: false,
  Sistema: false,
});

const openItems = ref<ActiveItems>({
  Vendas: false,
  Produtos: false,
  Financeiro: false,
  Marketing: false,
  Sistema: false,
});

const routesSales = ref<IPropsItem[]>([
  { name: "Minhas vendas", route: "Minhas-vendas", active: false, item: "Vendas" },
  { name: "Assinaturas", route: "Assinaturas", active: false, item: "Vendas" },
  { name: "Afiliados", route: "Afiliados", active: false, item: "Vendas" },
  { name: "Clientes", route: "Clientes", active: false, item: "Vendas" },
  { name: "Reclamações", route: "Reclamações", active: false, item: "Vendas" },
]);

const routesProducts = ref<IPropsItem[]>([
  { name: "Novo produto", route: "Novo-produto", active: false, item: "Produtos" },
  { name: "Meus produtos", route: "Meus-produtos", active: false, item: "Produtos" },
  { name: "Área de membros", route: "Área-de-membros", active: false, item: "Produtos" },
  { name: "Cupons", route: "Cupons", active: false, item: "Produtos" },
  { name: "Links", route: "Links", active: false, item: "Produtos" },
  { name: "Checkouts", route: "Checkouts", active: false, item: "Produtos" },
  { name: "Afiliações", route: "Afiliações", active: false, item: "Produtos" },
]);

const routesFinancial = ref<IPropsItem[]>([
  { name: "Extrato", route: "Extrato", active: false, item: "Financeiro" },
  { name: "Sacar dinheiro", route: "Sacar-dinheiro", active: false, item: "Financeiro" },
  { name: "Meus Saques", route: "Meus-Saques", active: false, item: "Financeiro" },
  { name: "Antecipações", route: "Antecipações", active: false, item: "Financeiro" },
  { name: "Contas bancárias", route: "Contas-bancárias", active: false, item: "Financeiro" },
  { name: "Emissões de NF", route: "Emissões-de-NF", active: false, item: "Financeiro" },
]);

const routesMarketing = ref<IPropsItem[]>([
  { name: "Visão Geral", route: "Visão-Geral", active: false, item: "Marketing" },
  { name: "Criação de páginas", route: "Criação-de-páginas", active: false, item: "Marketing" },
  { name: "E-mail marketing", route: "E-mail-marketing", active: false, item: "Marketing" },
]);

const routesSystem = ref<IPropsItem[]>([
  { name: "Controle de acesso", route: "Controle-de-acesso", active: false, item: "Sistema" },
  { name: "Tokens e Api Key", route: "Tokens-e-Api-Key", active: false, item: "Sistema" },
]);

const allRoutes = ref<IPropsItem[]>([
  ...routesSales.value,
  ...routesProducts.value,
  ...routesFinancial.value,
  ...routesMarketing.value,
  ...routesSystem.value,
]);

const activeDashboard = computed<boolean>(() => router.name === "Dashboard-sidebar");
const activeRelatorio = computed<boolean>(() => router.name === "Relatorio");

const headerElement = computed<HTMLElement | undefined>(() => (GrSideHeaderRef.value as HeaderElementRef)?.header);

const totalHeight = computed<number>(() => {
  const height = Math.max(headerHeight.value, headerClientHeight.value);
  return height + headerMarginTop.value + headerMarginBottom.value;
});

const distanceFromTop = computed<string>(() => {
  return `${totalHeight.value}px`;
});

watch(totalHeight, async () => {
  requestAnimationFrame(updateHeaderMeasurements);
});

watch(
  activeSidebar,
  (newVal) => {
    if (!newVal) {
      closeSideMenu();
    }
  },
  { deep: true }
);

watch(
  openItems,
  (newVal) => {
    const existOpenItemKey = Object.keys(newVal).find((key) => newVal[key as keyof ActiveItems]);
    if (existOpenItemKey && hovered.value === false) {
      openItems.value[existOpenItemKey as keyof ActiveItems] = false;
    }
  },
  { deep: true }
);

/**
 * Define o estado ativo de um subitem.
 *
 * @param subItem - O sub-item a ser definido como ativo.
 */
function setSubItemActive(subItem: IPropsItem) {
  // Se o nome da rota corresponder ao nome do subItem. Caso contrário, define como false.
  allRoutes.value.forEach((route) => {
    route.active = route.name === subItem.name;
  });

  // Define todos os itens do menu como false
  assignValueInArray(activeItems, false);

  // Define todos os itens do sub-menu como false e envia qual está ativo
  assignValueInArray(openItems, false, false, subItem.item);

  // Verifica se o subItem pertence a algum grupo. Se sim, define como ativo.
  if (routesSales.value.some((route) => route.name === subItem.name)) {
    activeItems.value.Vendas = true;
  } else if (routesProducts.value.some((route) => route.name === subItem.name)) {
    activeItems.value.Produtos = true;
  } else if (routesFinancial.value.some((route) => route.name === subItem.name)) {
    activeItems.value.Financeiro = true;
  } else if (routesMarketing.value.some((route) => route.name === subItem.name)) {
    activeItems.value.Marketing = true;
  } else if (routesSystem.value.some((route) => route.name === subItem.name)) {
    activeItems.value.Sistema = true;
  }

  // Se o usuário estava navegando por meio do teclado, redefine esses estados.
  if (browsingByKey.value) {
    browsingByKey.value = false;
    // Verifica se o cursor esta na side
    if (!hoverInSideBar.value) {
      hovered.value = false;
      activeSidebar.value = false;

      // Define todos os itens do sub-menu como false.
      assignValueInArray(openItems, false);
    }
  }
}

/**
 * Define o estado ativo de um item de menu.
 *
 * @param selectedMenu - O item do menu a ser definido como ativo.
 * @param navigateForKey - Se a navegação foi acionada pelo pressionamento de uma tecla.
 */
async function setItemActive(selectedMenu: string, navigateForKey?: boolean) {
  if (navigateForKey) {
    browsingByKey.value = true;
    hovered.value = true;
    activeSidebar.value = true;
  }

  // Coletar todos os itens de rotas ativas
  const activeSubRouteItems = new Set(allRoutes.value.filter((route) => route.active).map((route) => route.item));

  // Identificar itens que estão ativos, mas não possuem sub-rotas ativas
  const notActiveSubRouteItems = Object.keys(activeItems.value).filter((key) => {
    return activeItems.value[key] && !activeSubRouteItems.has(key);
  });

  // Se o item selecionado já está ativo e possui sub-rotas ativas, não fazer nada
  if (activeSubRouteItems.has(selectedMenu)) {
    openItems.value[selectedMenu] = true;
    return;
  }

  // Desativar itens que não possuem sub-rotas ativas
  for (const key of notActiveSubRouteItems) {
    activeItems.value[key] = false;
    openItems.value[key] = false;
  }

  // Alternar o estado do item selecionado
  const isSelectedMenuActive = activeItems.value[selectedMenu];
  activeItems.value[selectedMenu] = !isSelectedMenuActive;
  openItems.value[selectedMenu] = !isSelectedMenuActive;

  // Se o item selecionado estiver na lista de notActiveSubRouteItems, desativá-lo
  if (notActiveSubRouteItems.includes(selectedMenu)) {
    activeItems.value[selectedMenu] = false;
    openItems.value[selectedMenu] = false;
  }
}

/**
 * Atribui valores aos itens em um objeto Ref<ActiveItems>.
 *
 * @param array - O objeto Ref<ActiveItems> cujos valores serão atribuídos.
 * @param value - O valor booleano a ser atribuído aos itens.
 * @param hasIndice - Opcional. Se verdadeiro, só alterará os valores das chaves que não estão em activeRouteItems.
 * @param name - Opcional. O nome da chave específica que, se fornecida e encontrada, será definida como true.
 */
function assignValueInArray(array: Ref<ActiveItems>, value: boolean, hasIndice?: boolean, name: string | null = null) {
  // Conjunto de itens de rota ativa
  const activeRouteItems = new Set(allRoutes.value.filter((route) => route.active).map((route) => route.item));
  // Itera sobre as chaves do objeto recebido
  for (const key in array.value) {
    // Verifica se a chave é propriedade do objeto array.value
    if (Object.prototype.hasOwnProperty.call(array.value, key)) {
      // Se hasIndice for verdadeiro, só altera os valores das chaves que não estão em activeRouteItems
      if (hasIndice) {
        if (!activeRouteItems.has(key)) {
          array.value[key] = false;
        } else {
          array.value[key] = true;
        }
      } else {
        // Atribui o valor especificado a todas as chaves
        array.value[key] = value;
        // Se um nome for fornecido e a chave corresponder ao nome, define essa chave como true
        if (name && key === name) {
          array.value[key] = true;
        }
      }
    }
  }
}

function closeSideMenu() {
  hovered.value = false;
  // Define todos os itens do menu como false.
  assignValueInArray(openItems, false);
  // Define todos os itens do sub-menu como false, exeto o valore que não está ativo.
  assignValueInArray(activeItems, false, true);

  if (hoverInSideBar.value && window.innerWidth >= 768) {
    activeSidebar.value = false;
  }
}

function openSideMenu() {
  hovered.value = true;
  // Define apenas o que tem sub-menu ativo.
  assignValueInArray(openItems, true, true);
}

function toogleSide() {
  if (activeSidebar.value === true) {
    hoverInSideBar.value = false;
    activeSidebar.value = false;
    closeSideMenu();
    return;
  }
  hoverInSideBar.value = true;
  activeSidebar.value = true;
  openSideMenu();
}

/**
 * Inicializa o estado ativo dos itens de menu com base na rota atual.
 */
function initializeActiveState() {
  const currentRoute = router.name;

  allRoutes.value.forEach((route) => {
    if (route.route === currentRoute) {
      setItemActive(route.item, false);
      setSubItemActive(route);
      assignValueInArray(openItems, false);
      route.active = true;
    }
  });
}

function getComputedStyleValue(element: HTMLElement, property: string) {
  const computedStyle = window.getComputedStyle(element);
  return parseFloat(computedStyle.getPropertyValue(property)) || 0;
}

function updateHeaderMeasurements() {
  const element = headerElement.value;
  if (element) {
    headerHeight.value = element.getBoundingClientRect().height;
    headerClientHeight.value = element.clientHeight;
    headerMarginTop.value = getComputedStyleValue(element, "margin-top");
    headerMarginBottom.value = getComputedStyleValue(element, "margin-bottom");
  }
}

function handleMouseMove(event: MouseEvent) {
  const sidebarElement = GrSidebarRef.value as HTMLElement | null;

  if (sidebarElement && isEventInSideSidebar(event, sidebarElement)) {
    hoverInSideBar.value = true;
  } else {
    hoverInSideBar.value = false;

    if (browsingByKey.value) {
      browsingByKey.value = false;
      hovered.value = false;
      activeSidebar.value = false;

      for (const key in openItems.value) {
        if (Object.prototype.hasOwnProperty.call(openItems.value, key)) {
          if (openItems.value[key]) {
            openItems.value[key] = false;
          }
        }
      }
    }
  }
}

function isEventInSideSidebar(event: MouseEvent, sidebarElement: HTMLElement | null): boolean {
  let target = event.target as HTMLElement | null;
  while (target) {
    if (target === sidebarElement) {
      return true;
    }
    target = target.parentElement;
  }
  return false;
}

const isMobile = ref<boolean>(false);
function checkIfMobile() {
  isMobile.value = window.matchMedia("(max-width: 768px)").matches;
}
onUnmounted(() => {
  window.removeEventListener("resize", checkIfMobile);
});

onMounted(async () => {
  await nextTick();
  requestAnimationFrame(updateHeaderMeasurements);
  initializeActiveState();
  window.addEventListener("mousemove", handleMouseMove);
  checkIfMobile();
  window.addEventListener("resize", checkIfMobile);
});
</script>
<template>
  <GrSidebar>
    <GrSideHeader ref="GrSideHeaderRef">
      <template v-slot:left>
        <GrButton variant="alternative" class="mobile-menu-toggle" @click="toogleSide()">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 256 256">
            <path
              d="M228,128a12,12,0,0,1-12,12H40a12,12,0,0,1,0-24H216A12,12,0,0,1,228,128ZM40,76H216a12,12,0,0,0,0-24H40a12,12,0,0,0,0,24ZM216,180H40a12,12,0,0,0,0,24H216a12,12,0,0,0,0-24Z"
            />
          </svg>
        </GrButton>
        <GrDropDown>
          <GrDropDownTrigger>
            <GrButton variant="alternative" class="apps-toggle-button">
              <svg width="18" height="18" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M4.80769 8.61539C6.91062 8.61539 8.61539 6.91062 8.61539 4.80769C8.61539 2.70477 6.91062 1 4.80769 1C2.70477 1 1 2.70477 1 4.80769C1 6.91062 2.70477 8.61539 4.80769 8.61539ZM15.1923 8.61539C17.2953 8.61539 19 6.91062 19 4.80769C19 2.70477 17.2953 1 15.1923 1C13.0894 1 11.3846 2.70477 11.3846 4.80769C11.3846 6.91062 13.0894 8.61539 15.1923 8.61539ZM4.80769 19C6.91062 19 8.61539 17.2953 8.61539 15.1923C8.61539 13.0894 6.91062 11.3846 4.80769 11.3846C2.70477 11.3846 1 13.0894 1 15.1923C1 17.2953 2.70477 19 4.80769 19ZM15.1923 19C17.2953 19 19 17.2953 19 15.1923C19 13.0894 17.2953 11.3846 15.1923 11.3846C13.0894 11.3846 11.3846 13.0894 11.3846 15.1923C11.3846 17.2953 13.0894 19 15.1923 19Z"
                  stroke-width="1.7"
                  stroke-linecap="round"
                />
              </svg>
            </GrButton>
          </GrDropDownTrigger>
          <GrDropDownContent align="right" size="lg">
            <div class="container-apps">
              <GrParagraph color="gray-400" font-size="sm" weight="semibold">Aplicativos</GrParagraph>
              <div class="apps">
                <div class="app">
                  <img src="@/assets/icons/greenn-app.svg" alt="app" />
                  <GrParagraph color="gray-400" font-size="sm" weight="normal">Greenn</GrParagraph>
                </div>
                <div class="app">
                  <img src="@/assets/icons/gdigital-app.svg" alt="app" />
                  <GrParagraph color="gray-400" font-size="sm" weight="normal">G Digital</GrParagraph>
                </div>
                <div class="app">
                  <img src="@/assets/icons/club-app.svg" alt="app" />
                  <GrParagraph color="gray-400" font-size="sm" weight="normal">Club</GrParagraph>
                </div>
              </div>
            </div>
            <GrDropDownSeparator />
            <div class="container-apps">
              <GrParagraph color="gray-400" font-size="sm" weight="semibold">Atalhos</GrParagraph>
              <div class="apps">
                <div class="app">
                  <img src="@/assets/icons/greenn-app.svg" alt="app" />
                  <GrParagraph color="gray-400" font-size="sm" weight="normal">Greenn</GrParagraph>
                </div>
                <div class="app">
                  <img src="@/assets/icons/gdigital-app.svg" alt="app" />
                  <GrParagraph color="gray-400" font-size="sm" weight="normal">G Digital</GrParagraph>
                </div>
                <div class="app">
                  <img src="@/assets/icons/club-app.svg" alt="app" />
                  <GrParagraph color="gray-400" font-size="sm" weight="normal">Club</GrParagraph>
                </div>
              </div>
            </div>
          </GrDropDownContent>
        </GrDropDown>
        <img src="@/assets/icons/greenn.svg" alt="Logo Greenn" class="logo-black" />
      </template>
      <template v-slot:right>
        <GrButton variant="alternative" class="mobile-apps-toggle">
          <svg width="22" height="22" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M4.80769 8.61539C6.91062 8.61539 8.61539 6.91062 8.61539 4.80769C8.61539 2.70477 6.91062 1 4.80769 1C2.70477 1 1 2.70477 1 4.80769C1 6.91062 2.70477 8.61539 4.80769 8.61539ZM15.1923 8.61539C17.2953 8.61539 19 6.91062 19 4.80769C19 2.70477 17.2953 1 15.1923 1C13.0894 1 11.3846 2.70477 11.3846 4.80769C11.3846 6.91062 13.0894 8.61539 15.1923 8.61539ZM4.80769 19C6.91062 19 8.61539 17.2953 8.61539 15.1923C8.61539 13.0894 6.91062 11.3846 4.80769 11.3846C2.70477 11.3846 1 13.0894 1 15.1923C1 17.2953 2.70477 19 4.80769 19ZM15.1923 19C17.2953 19 19 17.2953 19 15.1923C19 13.0894 17.2953 11.3846 15.1923 11.3846C13.0894 11.3846 11.3846 13.0894 11.3846 15.1923C11.3846 17.2953 13.0894 19 15.1923 19Z"
              stroke-width="1.7"
              stroke-linecap="round"
            />
          </svg>
        </GrButton>
        <GrDropDown>
          <GrDropDownTrigger>
            <GrAvatar :src="avatarSrc" :size="isMobile ? 'sm' : 'md'" cursor="pointer" :placeholder="'Greenn'" />
          </GrDropDownTrigger>
          <GrDropDownContent align="left" size="lg">
            <div class="container-user">
              <div class="container-user-infos">
                <GrAvatar :src="avatarSrc" :size="'sm'" cursor="not-allowed" :placeholder="'Greenn'" />
                <div class="user-infos">
                  <GrParagraph color="gray-500" font-size="sm" weight="semibold"> Roberto Almeida </GrParagraph>
                  <GrParagraph color="gray-200" font-size="sm" weight="medium"> robertoalmeida@mail.com </GrParagraph>
                </div>
              </div>
              <svg xmlns="http://www.w3.org/2000/svg" width="11" height="17" viewBox="0 0 11 17" fill="none">
                <path
                  d="M10 5.5L5.5 1L1 5.5M1 11.5L5.5 16L10 11.5"
                  stroke="var(--gray-200)"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
            </div>
            <GrDropDownSeparator />
            <GrDropdownMenuGroup>
              <GrDropDownItem>
                <iconDropDownAccount :active="false" />
                <GrParagraph color="gray-200" font-size="sm" weight="medium"> Minha conta </GrParagraph>
              </GrDropDownItem>
              <GrDropDownItem>
                <iconDropDownMySales :active="false" />
                <GrParagraph color="gray-200" font-size="sm" weight="medium"> Minhas compras </GrParagraph>
              </GrDropDownItem>
              <GrDropDownItem>
                <iconDropDownExit :active="false" />
                <GrParagraph color="gray-200" font-size="sm" weight="medium"> Sair </GrParagraph>
              </GrDropDownItem>
            </GrDropdownMenuGroup>
          </GrDropDownContent>
        </GrDropDown>
      </template>
    </GrSideHeader>
    <section
      ref="GrSidebarRef"
      :class="{ activeSidebar: activeSidebar }"
      :style="{ top: distanceFromTop }"
      @mouseleave="closeSideMenu"
      @mouseenter="openSideMenu"
    >
      <GrSideItem
        name="Dashboard"
        route="Dashboard-sidebar"
        :active="activeDashboard"
        :hover="hovered"
        @click="
          setItemActive, setSubItemActive({ name: 'Dashboard', route: 'Dashboard', active: false, item: 'Dashboard' })
        "
      >
        <iconSideDashboard :active="activeDashboard" />
      </GrSideItem>
      <GrSideItemDrop
        name="Vendas"
        :active="activeItems.Vendas"
        :open="openItems.Vendas"
        :routes="routesSales"
        :hover="hovered"
        @changeItem="setItemActive"
        @changeSubItem="setSubItemActive"
      >
        <iconSideSales :active="activeItems.Vendas" :open="openItems.Vendas" />
      </GrSideItemDrop>
      <GrSideItemDrop
        name="Produtos"
        :active="activeItems.Produtos"
        :open="openItems.Produtos"
        :routes="routesProducts"
        :hover="hovered"
        @changeItem="setItemActive"
        @changeSubItem="setSubItemActive"
      >
        <iconSideProducts :active="activeItems.Produtos" :open="openItems.Produtos" />
      </GrSideItemDrop>
      <GrSideItemDrop
        name="Financeiro"
        :active="activeItems.Financeiro"
        :open="openItems.Financeiro"
        :routes="routesFinancial"
        :hover="hovered"
        @changeItem="setItemActive"
        @changeSubItem="setSubItemActive"
      >
        <iconSideFinancial :active="activeItems.Financeiro" :open="openItems.Financeiro" />
      </GrSideItemDrop>
      <GrSideItemDrop
        name="Marketing"
        :active="activeItems.Marketing"
        :open="openItems.Marketing"
        :routes="routesMarketing"
        :hover="hovered"
        @changeItem="setItemActive"
        @changeSubItem="setSubItemActive"
      >
        <iconSideMarketing :active="activeItems.Marketing" :open="openItems.Marketing" />
      </GrSideItemDrop>
      <GrSideItem
        name="Relatorio"
        route="Relatorio"
        :active="activeRelatorio"
        :hover="hovered"
        @click="
          setItemActive, setSubItemActive({ name: 'Relatorio', route: 'Relatorio', active: false, item: 'Relatorio' })
        "
      >
        <iconSideReports :active="activeRelatorio" />
      </GrSideItem>
      <GrSideItemDrop
        name="Sistema"
        :active="activeItems.Sistema"
        :open="openItems.Sistema"
        :routes="routesSystem"
        :hover="hovered"
        @changeItem="setItemActive"
        @changeSubItem="setSubItemActive"
      >
        <iconSideSystem :active="activeItems.Sistema" :open="openItems.Sistema" />
      </GrSideItemDrop>
    </section>
  </GrSidebar>
  <main>
    <div>
      <slot />
    </div>
  </main>
  <div class="hide-sidebar-mobile" @click="toogleSide()" />
</template>

<style scoped lang="scss">
.container-apps {
  padding: var(--spacing-1);
  width: var(--w-full);
  .apps {
    display: flex;
    align-items: center;
    justify-content: space-evenly;

    .app {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}
.container-user {
  padding: var(--spacing-2-5);
  display: flex;
  align-items: center;
  width: var(--w-full);
  justify-content: space-between;

  .container-user-infos {
    display: flex;
    align-items: center;
    gap: var(--spacing-2-5);
    .user-infos {
      display: flex;
      flex-direction: column;
    }
  }
}
.mobile-menu-toggle {
  display: none;
  padding: 0;
  aspect-ratio: 1;
  margin-right: var(--spacing-3);
  background-color: transparent !important;
  user-select: none;
  svg {
    fill: var(--primary-500);
  }
  @media (max-width: 768px) {
    display: flex;
  }
}

.apps-toggle-button {
  padding: 0;
  aspect-ratio: 1;
  margin-right: var(--spacing-3);
  border-radius: 50%;
  svg {
    stroke: var(--primary-500);
  }
  @media (max-width: 768px) {
    display: none;
  }
}

.mobile-apps-toggle {
  display: none;
  padding: 0;
  aspect-ratio: 1;
  margin-right: var(--spacing-3);
  background-color: transparent;
  user-select: none;
  &:focus {
    background-color: var(--primary-50);
  }
  svg {
    stroke: var(--primary-500);
    fill: transparent;
  }
  @media (max-width: 768px) {
    display: flex;
  }
}

.logo-black {
  display: none;
  height: 30px;
  @media (max-width: 768px) {
    display: block;
  }
}

#app:has(.activeSidebar) {
  .mobile-menu-toggle {
    background-color: var(--primary-50) !important;
  }
  .hide-sidebar-mobile {
    @media (max-width: 768px) {
      display: block;
    }
  }
}

.hide-sidebar-mobile {
  display: none;
  height: 100dvh;
  width: 100dvw;
  position: absolute;
  top: 0;
  left: 0;
}

section {
  position: fixed;
  top: 0;
  z-index: 999999;
  background: var(--gray-white);
  height: calc(100vh - 60px);
  width: var(--font-9xl);
  max-width: var(--font-11xl);
  transition: var(--transition);
  padding: var(--spacing-5);
  border-right: 1px solid var(--gray-50);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-3);
  overflow-y: scroll;
  overflow-x: hidden;

  &:hover,
  &.activeSidebar {
    width: var(--font-11xl);
  }
  @media (max-width: 768px) {
    width: var(--font-11xl);
    margin-left: calc(var(--font-11xl) * -1);
    &.activeSidebar {
      margin-left: 0;
    }
  }
}

main {
  position: relative;
  overflow: hidden;
  width: calc(100dvw - var(--font-9xl));
  height: calc(100dvh - v-bind(distanceFromTop));
  max-height: calc(100dvh - v-bind(distanceFromTop));
  overflow-y: auto;
  overflow-x: hidden;
  top: 0;
  left: 100px;
  padding: var(--spacing-0) var(--spacing-10);
  display: flex;
  justify-content: center;
  flex-direction: column;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  @media (max-width: 768px) {
    left: 0px;
    width: 100%;
  }
  > div {
    max-width: 1150px;
    width: 100%;
    height: 100%;
    margin: 0 auto;
  }
}
</style>
