<template>
  <q-layout view="hHh LpR fFf">
    <q-header class="bg-transparent text-white">
      <q-toolbar class="q-px-none">
        <q-toolbar-title>
          <with-logo-button @click="toggleLeftDrawer"></with-logo-button>
          <div
            class="rectangle"
            :style="{
              background: currentColor.innerColor,
              opacity: leftDrawerOpen ? '0.9' : '0',
            }"
          ></div>
          <template
            v-for="(item, idx) of mainActionButtons"
            :key="item.name + idx"
          >
            <MainActionsButton
              :item="item"
              :bottom-line-color="currentColor"
              :current="idx === currentTab"
              :mini="($q.screen.lt.lg && idx !== currentTab) || $q.screen.lt.md"
              :style="idx > 0 ? 'margin-left: -9px' : 'margin-left: 4px'"
              @click="setCurrentTab(item, idx)"
            ></MainActionsButton>
          </template>
          <SpaceWithBottomLine
            :item="currentColor"
            :color="currentColor"
            v-if="$q.screen.gt.md"
            style="margin-left: -9px"
          ></SpaceWithBottomLine>
          <template
            v-for="(item, idx) of leftGroupButtons"
            :key="item.name + idx"
          >
            <HeaderButton
              :item="item"
              :color="currentColor"
              :last="leftGroupButtons.length === idx + 1"
              style="margin-left: -9px"
              v-if="$q.screen.gt.xs"
              @click="setCurrentButton(item, idx)"
            ></HeaderButton>
          </template>
        </q-toolbar-title>
        <template
          v-for="(item, idx) of rightGroupButtons"
          :key="item.name + idx"
        >
          <HeaderButton
            :item="item"
            :color="usernameColor"
            :last="rightGroupButtons.length === idx + 1"
            :style="idx > 0 ? 'margin-left: -9px' : 'margin-left: 4px'"
            v-if="$q.screen.gt.xs"
          ></HeaderButton>
        </template>
        <UsernameButton
          v-if="isLoggedIn"
          style="margin-left: 5px"
          :item="usernameButton"
          :color="usernameColor"
          :mini="$q.screen.lt.md"
          @click="toggleRightDrawer"
        ></UsernameButton>
        <UsernameButton
          v-else
          style="margin-left: 5px"
          :item="{
            name: 'Войти',
            icon: 'userIcon.svg',
            tooltip: 'Нажмите для входа',
          }"
          :color="usernameColor"
          :mini="$q.screen.lt.md"
          @click="showLoginForm = true"
        ></UsernameButton>
      </q-toolbar>
    </q-header>

    <q-drawer
      v-model="leftDrawerOpen"
      side="left"
      behavior="desktop"
      :width="48"
      class="left-drawer"
      :style="{ background: currentColor.innerColor }"
    >
      <q-scroll-area
        :style="`height: calc(100vh - 54px - ${
          leftMenuTopGroupButtons.length * 48
        }px - ${leftMenuBottomGroupButtons.length * 5 + 5}px )`"
      >
        <q-list class="flex col" style="gap: 4px">
          <template
            v-for="(item, idx) of leftMenuTopGroupButtons"
            :key="item.name + idx"
          >
            <LeftMenuButton :item="item" :color="currentColor"></LeftMenuButton>
          </template>
        </q-list>
      </q-scroll-area>
      <q-list class="flex col" style="gap: 4px">
        <template
          v-for="(item, idx) of leftMenuBottomGroupButtons"
          :key="item.name + idx"
        >
          <LeftMenuButton :item="item" :color="currentColor"></LeftMenuButton>
        </template>
      </q-list>
    </q-drawer>

    <q-drawer
      v-model="rightDrawerOpen"
      side="right"
      :width="242"
      overlay
      behavior="desktop"
      class="right-drawer"
      :style="{ background: currentColor.innerColor }"
    >
      <q-list class="text-white right-drawer-list">
        <template
          v-for="(item, idx) of leftGroupButtons"
          :key="item.name + idx"
        >
          <RightMenuButton :item="item" :color="currentColor"></RightMenuButton>
        </template>
      </q-list>
      <q-separator />

      <q-list class="text-white right-drawer-list">
        <template
          v-for="(item, idx) of rightGroupButtons"
          :key="item.name + idx"
        >
          <RightMenuButton
            :item="item"
            :color="usernameColor"
          ></RightMenuButton>
        </template>
      </q-list>
      <q-list class="text-white right-drawer-list">
        <RightMenuButton
          v-if="isLoggedIn"
          :item="{
            name: 'Выход',
            icon: 'logout',
            tooltip: 'Выход',
            action: logoutButton,
          }"
          :color="usernameColor"
        ></RightMenuButton>
        <RightMenuButton
          v-else
          :item="{
            name: 'Войти',
            icon: 'simpleCircleIcon.svg',
            tooltip: 'Нажмите для входа',
            action: () => ((showLoginForm = true), (rightDrawerOpen = false)),
          }"
          :color="usernameColor"
        ></RightMenuButton>
      </q-list>
    </q-drawer>

    <q-page-container class="page-container-background flex flex-center">
      <router-view class="page-style" />
    </q-page-container>
  </q-layout>
  <q-dialog v-model="showLoginForm" persistent>
    <sign-in-dialog></sign-in-dialog>
  </q-dialog>
</template>

<script>
import { ref } from "vue";
import WithLogoButton from "../components/buttons/WithLogoButton.vue";
import UsernameButton from "../components/buttons/UsernameButton.vue";
import MainActionsButton from "../components/buttons/MainActionsButton.vue";
import HeaderButton from "src/components/buttons/HeaderButton.vue";
import SpaceWithBottomLine from "../components/buttons/SpaceWithBottomLine.vue";
import LeftMenuButton from "src/components/buttons/LeftMenuButton.vue";
import RightMenuButton from "src/components/buttons/RightMenuButton.vue";
import { useAuthStore } from "src/stores/auth";
import { mapState, mapWritableState, mapActions } from "pinia";
import SignInDialog from "src/components/signInDialog.vue";
import { useUiStore } from "src/stores/UI";
import { sendYMgoal } from "src/utils/yandex_metrika_utils";

export default {
  setup() {
    const mainActionButtons = ref([
      {
        name: "Знания",
        innerColor: "#5F8CEA",
        outerColor: "#6666FF",
        color: "blue",
        icon: "iconKnowledge.svg",
        tooltip: "Знания",
        action: "/",
        buttons: [
          {
            name: "Стартовая страница",
            icon: "rocket",
            tooltip: "Стартовая страница1",
            action: "/",
            subbuttons: [
              {
                name: "Информация",
                icon: "iconInfo.svg",
                tooltip: "Информация1",
                action: "/",
              },
            ],
          },
        ],
      },
      {
        name: "Действия",
        innerColor: "#006868",
        outerColor: "#004F4F",
        color: "green",
        icon: "iconActions.svg",
        tooltip: "Действия",
        action: "/actions",

        buttons: [
          {
            name: "Стартовая страница",
            icon: "rocket",
            tooltip: "Стартовая страница2",
            action: "/actions",
            subbuttons: [
              {
                name: "Информация",
                icon: "iconInfo.svg",
                tooltip: "Информация2",
                action: "/actions",
              },
            ],
          },
        ],
      },
      {
        name: "Вселенные",
        innerColor: "#502542",
        outerColor: "#340F28",
        color: "red",
        icon: "iconUniverses.svg",
        tooltip: "Вселенные",
        action: "/universes",

        buttons: [
          {
            name: "Стартовая страница",
            icon: "rocket",
            tooltip: "Стартовая страница3",
            action: "/universes",
            subbuttons: [
              {
                name: "Информация",
                icon: "iconInfo.svg",
                tooltip: "Информация3",
                action: "/universes",
              },
            ],
          },
        ],
      },
    ]);
    const usernameColor = ref({
      innerColor: "#8282BF",
      outerColor: "#4A4AFF",
      color: "bluegray",
    });
    let currentTab = ref(0);
    let currentButton = ref(0);

    const rightGroupButtonsSet = ref([
      {
        name: "Профиль",
        icon: "psychology",
        tooltip: "Профиль",
        action: "/profile",
        authOnly: true,
      },
      // {
      //   name: "Button2",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button2",
      // },
      // {
      //   name: "Button3",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button3",
      // },
    ]);

    const leftMenuBottomGroupButtons = ref([
      // {
      //   name: "Button1",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button1",
      // },
      // {
      //   name: "Button2",
      //   icon: "simpleCircleIcon.svg",
      //   tooltip: "Button2",
      // },
    ]);
    const rightDrawerOpen = ref(false);
    return {
      rightDrawerOpen,
      toggleRightDrawer() {
        rightDrawerOpen.value = !rightDrawerOpen.value;
      },
      mainActionButtons,
      usernameColor,

      rightGroupButtonsSet,

      leftMenuBottomGroupButtons,
      currentTab,
      currentButton,
    };
  },
  data() {
    return {
      confirm: true,
    };
  },
  components: {
    WithLogoButton,
    UsernameButton,
    MainActionsButton,
    HeaderButton,
    SpaceWithBottomLine,
    LeftMenuButton,
    RightMenuButton,
    SignInDialog,
  },
  methods: {
    ...mapActions(useAuthStore, ["getLocalStorage"]),
    ...mapActions(useAuthStore, ["getMe"]),
    ...mapActions(useAuthStore, ["logout"]),
    ...mapActions(useUiStore, ["getLocalStoredUi", "setLocalStoredUi"]),
    toggleLeftDrawer() {
      this.leftDrawerOpen = !this.leftDrawerOpen;
    },
    setCurrentTab(item, index) {
      const { innerColor, outerColor, color } = item;
      this.currentColor = { innerColor, outerColor, color };
      this.currentTab = index;
    },
    setCurrentButton(item, index) {
      this.currentButton = index;
    },
    logoutButton() {
      this.rightDrawerOpen = false;
      this.logout()
        .then(() => {
          sendYMgoal(this.$route.path, "logout", "button");
          this.$router.push("/");
        })
        .catch(() => {});
    },
  },
  computed: {
    ...mapState(useAuthStore, ["user"]),
    ...mapState(useAuthStore, { name: "getUserName" }),
    ...mapState(useAuthStore, { email: "getUserEmail" }),
    ...mapState(useAuthStore, ["isLoggedIn"]),
    ...mapWritableState(useUiStore, ["showLoginForm"]),
    ...mapState(useUiStore, ["localStoredUi"]),

    title: function () {
      return this.$route?.meta?.pageName;
    },
    usernameButton: function () {
      return {
        name: this.name,
        icon: "userIcon.svg",
        tooltip: this.email,
      };
    },
    leftDrawerOpen: {
      get: function () {
        return this.localStoredUi?.leftDrawerOpen ?? true;
      },
      set: function (payload) {
        this.setLocalStoredUi({ leftDrawerOpen: payload });
      },
    },
    leftGroupButtons() {
      return this.mainActionButtons[this.currentTab]?.buttons ?? [];
    },
    leftMenuTopGroupButtons() {
      return (
        this.mainActionButtons[this.currentTab]?.buttons[this.currentButton]
          .subbuttons ?? []
      );
    },
    rightGroupButtons() {
      return this.rightGroupButtonsSet.filter((item) => {
        if (item.authOnly && this.isLoggedIn) {
          return true;
        }
        if (!item.authOnly) {
          return true;
        }
        return false;
      });
    },
    currentColor() {
      const { innerColor, outerColor, color } =
        this.mainActionButtons[this.currentTab];
      return { innerColor, outerColor, color };
    },
  },
  mounted() {
    this.getLocalStoredUi();
    this.getLocalStorage()
      .then(() => this.getMe())
      .catch(() => {
        if (this.$route.meta.requiresAuth) {
          this.$router.push("/");
        }
      });
  },
  watch: {
    "$route.path": {
      handler(cur, old) {
        if (cur) {
          switch (cur) {
            case "/":
              this.currentTab = 0;
              break;
            case "/actions":
              this.currentTab = 1;
              break;
            case "/universes":
              this.currentTab = 2;
              break;
            default:
              this.currentTab = 0;
              break;
          }
        }
      },
      immediate: true,
    },
  },
};
</script>
<style>
.page-container-background {
  background-image: url(~assets/background1.jpg);
  background-color: #cccccc;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
  background-size: cover;
  z-index: 0;
}
.page-container-background:after {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.rectangle {
  height: 18px;
  width: 18px;
  position: absolute;
  top: 51px;
  left: 50px;
  transition: all 1s;
  transform: translate(-50%, -50%) rotate(45deg);
  user-select: none;
}
.left-drawer {
  opacity: 0.9;
  margin-top: 3px;
  height: calc(100vh - 53px) !important;
  clip-path: polygon(0 0, calc(100% - 13px) 0, 100% 13px, 100% 100%, 0 100%);
}
.right-drawer {
  opacity: 0.97;
  margin-top: 3px;
  height: calc(100vh - 53px) !important;
  clip-path: polygon(13px 0, 100% 0, 100% 100%, 0 100%, 0 13px);
}
.right-drawer-list {
  gap: 5px;
  display: grid;
  padding: 10px;
}
.q-drawer--left,
.q-drawer--right {
  background-color: unset;
}
</style>
<style scoped>
.page-style {
  z-index: 1;
  max-width: 820px;
  width: 100%;
  padding: 20px;
}
@media (max-width: 400px) {
  .page-style {
    padding: 20px 5px;
  }
}
</style>
