<template>
  <dialog
    ref="burgerRef"
    :class="{'layout-burger--hide': isAuthPopupOpen}"
    class="layout-burger"
    @click="closeByBackdropClick"
  >
    <button
      :aria-label="$t('close')"
      class="layout-burger__close"
      type="button"
      @click="close"
    >
      <UiIcon
        class="layout-burger__close-icon"
        name="close"
        size="24"
      />
    </button>
    <div class="layout-burger__wrapper">
      <div class="layout-burger__buttons">
        <NuxtLink
          v-if="isAuthorized && data"
          :to="generateLink('/user/profile')"
          class="layout-burger__button"
        >
          <UiAvatar :size="40"/>
          <span class="layout-burger__button-text">{{ data.username }}</span>
        </NuxtLink>
        <button
          v-for="(btn, index) in burgerButtons"
          :key="`burger-btn-${index}`"
          class="layout-burger__button"
          type="button"
          @click="btn.action?.(); close()"
        >
          <span class="layout-burger__button-icon">
            <UiIcon
              :name="btn.icon"
              size="20"
            />
          </span>
          {{ t(btn.label) }}
        </button>
      </div>

      <nav class="layout-burger__nav">
        <div
          v-if="topItems.length > 0"
          class="layout-burger__menu"
        >
          <LayoutBurgerItem
            :items="topItems"
            :opened-childs="openedChilds"
            key-prefix="burger-top"
            @toggle="toggleChilds"
            @close="close"
          />
        </div>
        <div class="layout-burger__menu">
          <LayoutBurgerItem
            :items="restItems"
            :opened-childs="openedChilds"
            key-prefix="burger-item"
            @toggle="toggleChilds"
            @close="close"
          />
        </div>
      </nav>

      <LayoutNiche
        class="layout-burger__niche"
        icon-size="20"
      />

      <LayoutLanguage
        class="layout-burger__language"
        icon-size="20"
      />
    </div>
  </dialog>
</template>

<script setup lang="ts">
import { AuthSteps, onBackdropClick, checkDeviceWidth } from '../../runtime';
import type { IProfileData } from '../../types';
import { CSS_BREAKPOINTS } from '../../config/css-breakpoints';
import { AuthorizationApiService } from '../../services/api/authorization.service';

import { getNavigationItems } from '../../lib';

const { t } = useI18n();
const { generateLink } = useGenerateLink();
const navigationItems = getNavigationItems();
const topItems = navigationItems.filter(item => item.top);
const restItems = navigationItems.filter(item => !item.top);

const openedChilds = ref<string | null>(null);

function toggleChilds(title: string) {
  openedChilds.value = openedChilds.value === title ? null : title;
}

const emit = defineEmits<{
  (eventName: 'update:modelValue', value: boolean): void,
  (eventName: 'close'): void
}>();

const props = defineProps<{
  modelValue: boolean,
}>();

const { isAuthPopupOpen, openAuthPopup } = useAuthPopup();

const { isAuthorized } = useUser(AuthorizationApiService);

const burgerRef = ref();

const breakpoints = CSS_BREAKPOINTS;
const { isMobile } = checkDeviceWidth(breakpoints);

const { scrollLock, scrollUnlock } = useGlobalScrollLock();

watch(() => props.modelValue, (value) => {
  if (value) {
    if (isMobile.value) {
      burgerRef.value.showModal();
      scrollLock();
    } else {
      burgerRef.value.show();
    }
  } else {
    burgerRef.value.close();

    if (isMobile.value) {
      scrollUnlock();
    }
  }
});

function close() {
  emit('close');
  emit('update:modelValue', false);
}

function closeByBackdropClick(event: Event) {
  const target = event.target as HTMLDialogElement;
  onBackdropClick(target, close);
}

const data = computed(() => useState<IProfileData>('profileData').value);

function logOut() {
  useUser(AuthorizationApiService).signOut();
}

const burgerButtons = computed(() => [
  ...isAuthorized.value ? [
        {
          icon: 'logout',
          label: 'auth.logout',
          action: () => logOut(),
        }
      ] :
      [
        {
          icon: 'user',
          label: 'auth.sign_up',
          action: () => openAuthPopup(AuthSteps.Registration),
        },
        {
          icon: 'login',
          label: 'auth.log_in',
          action: () => openAuthPopup(AuthSteps.Login),
        },
      ],
  {
    icon: 'upload',
    label: 'upload'
  },
]);

const router = useRouter();
router.afterEach(() => {
  close();
});
</script>

<style lang="scss">
.layout-burger {
  --width: 280px;

  right: 0;
  left: auto;
  bottom: 0;
  margin: 0;
}

.layout-burger::backdrop {
  background-color: $burger-backdrop;
  touch-action: none;
}

.layout-burger__wrapper {
  position: relative;
  padding: 16px;
  height: 100vh;
  height: 100dvh;
  width: var(--width);
  z-index: $z-index-plus;
  background-color: $burger-bg;
  backdrop-filter: blur($blur-md);
  overflow: auto;
  border-left: 1px solid $burger-border;
}

.layout-burger__buttons {
  display: flex;
  justify-content: space-around;
  border-bottom: 1px solid $burger-buttons-border;
  padding-block: 16px;
  margin-bottom: 12px;
}

.layout-burger__button {
  @include font-xs;

  display: grid;
  justify-items: center;
  row-gap: 8px;
  color: $burger-button-text;
}

.layout-burger__button-text {
  $avatar-size: 40px;

  max-width: calc(#{$avatar-size} + 20px);
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.layout-burger__button-icon {
  $size: 40px;

  display: grid;
  place-content: center;
  width: $size;
  height: $size;
  background-color: $burger-button-icon-bg;
  border-radius: $radius-full;
}

.layout-burger__menu {
  display: grid;
  padding-bottom: 4px;
  margin-bottom: 12px;
  border-bottom: 1px solid $burger-menu-border;
}

.layout-burger__menu:last-child {
  padding-bottom: 12px;
  margin-bottom: 4px;
}

.layout-burger__niche {
  margin-bottom: 12px;
}

.layout-burger__close {
  position: fixed;
  top: 16px;
  right: calc(var(--width) + 12px);
  z-index: $z-index-plus;
  background-color: $burger-close-bg;
  padding: 8px;
  border-radius: $radius;
  color: $burger-close-text;
}
</style>
