<script setup>
import {onMounted, ref, watch, computed} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import * as bootstrap from 'bootstrap';
import {useAuthStore} from '@/stores/Auth.js';
import {useNotificationStore} from '@/stores/notifications.js';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const notificationStore = useNotificationStore();

/* ==== ЕДИНЫЙ СПИСОК МЕНЮ ================= */
const menu = [
  {                      /* одиночный пункт */
    label: 'Карта',
    to: {path: '/'},
  },

  {
    title: 'План-графики', children: [
      {label: 'План-график', to: '/schedule/list'},
      {label: 'Сгенерировать КПГ', to: '/gen-calendar', perm: 'generate-calendar-plan'},
    ]
  },
  {
    label: 'АРМ Менеджера',
    to: '/manager', perm: 'work-f3'
  },
  {
    title: 'ПУИДД', children: [
      {label: 'Список ПУИДД', to: '/point/list', perm: 'create-point'},
      {label: 'Реестр ПУИДД', to: '/points-registry'},
      {label: 'Карточки ПУИДД', to: '/district-card'},
      {label: 'Редактор ПУИДД', to: '/point-plan/list', perm: 'assign-an-operator'},

    ]
  },

  {
    title: 'Отчёты', children: [
      {label: 'Расчёт интенсивности', to: '/report-intens', perm: 'view-reports-intens'},
      {label: 'Акт КС-2', to: '/act-ks2', perm: 'create-act-ks2'},
      {label: 'Фотоотчет', to: '/photo-report', perm: 'create-photo-report'},
      {label: 'Схема ОДД', to: '/road-schema', perm: 'create-road-schema'},
      {label: 'Информационное письмо', to: '/info-letter', perm: 'create-info-letter'},
    ]
  },

  {
    title: 'Администрирование', children: [
      {label: 'Пользователи', to: '/users/list', perm: 'view-user'},
      {label: 'Учетчики', to: '/counters' , perm: 'view-counters'},
      {label: 'Разрешения', to: {name: 'permissions'}, perm: 'manage-permissions'},
      {label: 'Заявки', to: '/request/list', perm: 'view-requests'},
      {label: 'Назначение исполнителей', to: {name: 'assignment'}, perm: 'assign'},
      {label: 'Логи', to: '/logs', perm: 'view-logs'},
    ]
  },

  {                      /* одиночный пункт */
    label: 'Профиль',
    to: '/profile',
  },
];

/* отфильтровали по правам */
const visibleMenu = computed(() =>
    menu
        .map(item => {
          // если есть дети — фильтруем их
          if (item.children) {
            const children = item.children.filter(
                child => !child.perm || authStore.hasPermission(child.perm)
            );
            // если после фильтрации внутри остались элементы — возвращаем секцию
            return children.length
                ? { ...item, children }
                : null;
          }

          // для одиночного пункта проверяем perm
          if (!item.perm || authStore.hasPermission(item.perm)) {
            return item;
          }

          // нет прав — убираем
          return null;
        })
        .filter(Boolean)
);

// Collapse instance
const bsCollapse = ref(null);

onMounted(() => {
  // Fetch notifications
  if (authStore.isLoggedIn) {
    notificationStore.fetchNotifications();
  }
  // Initialize Bootstrap collapse
  const el = document.getElementById('navbarNav');
  bsCollapse.value = bootstrap.Collapse.getOrCreateInstance(el, {toggle: false});
});

// Close menu on route change
watch(
    () => route.fullPath,
    () => {
      if (bsCollapse.value) {
        bsCollapse.value.hide();
      }
    }
);

const logOut = () => {
  authStore.logout().then(() => {
    router.push({name: 'login'});
  });
};
</script>

<template>
  <div>
    <nav class="navbar navbar-expand-lg bg-body-tertiary">
      <div class="container-fluid">
        <a class="navbar-brand" href="#"></a>
        <button
            class="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarNav"
            aria-controls="navbarNav"
            aria-expanded="false"
            aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav d-flex gap-1">              <!-- ms-auto = прижать вправо -->

            <!-- ======= перебор секций/пунктов ======= -->
            <template v-for="section in visibleMenu" :key="section.label || section.title">

              <!-- одиночный пункт -->
              <li v-if="!section.children" class="nav-item">
                <router-link class="nav-link" :to="section.to">{{ section.label }}</router-link>
              </li>

              <!-- группа с выпадающим списком -->
              <li v-else class="nav-item dropdown">
                <a class="nav-link dropdown-toggle"
                   href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  {{ section.title }}
                </a>
                <ul class="dropdown-menu">
                  <li v-for="item in section.children" :key="item.label">
                    <router-link class="dropdown-item" :to="item.to">
                      {{ item.label }}
                    </router-link>
                  </li>
                </ul>
              </li>

            </template>

          </ul>
        </div>

        <div class="me-3 position-relative" style="cursor: pointer" @click="router.push('/notifications')">
          <span class="emoji-bell">🔔</span>
          <span
              v-if="notificationStore.unreadCount > 0"
              class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"
              style="font-size: 0.7rem"
          >
            {{ notificationStore.unreadCount }}
          </span>
        </div>

        <button type="button" @click="logOut" class="btn btn-primary w-10 py-2">Выход</button>
      </div>
    </nav>
    <router-view/>
  </div>
</template>

<style scoped>
.emoji-bell {
  font-size: 1.2rem;
  filter: grayscale(100%);
  opacity: 0.8;
  display: inline-block;
  line-height: 1;
}
</style>
