<script setup>
import { ref, provide, computed } from "vue";
import NavDesktop from "./NavDesktop.vue";
import NavMobile from "./NavMobile.vue";
import logo from "../../images/logo.png";
import axios from "axios";

const isOpen = ref(false);
const isMobileMenuOpen = ref(false);
const openDropdownIndex = ref(null);

const baseItems = [
  {
    label: "Manajemen Produk",
    subItems: [
      { label: "Brankas", route: "/brankas" },
      { label: "Nampan", route: "/nampan" },
      { label: "Produk", route: "/produk" },
      { label: "Kategori", route: "/kategori" },
      { label: "Sales", route: "/sales" },
    ]
  },
  { label: "Kasir", route: "/kasir" },
  { label: "Laporan", route: "/laporan" },
  { label: "Akun", route: "/akun" },
];

const role = localStorage.getItem("role");

const items = computed(() => {
  if (role === "owner") {
    return baseItems;
  }
  if (role === "kasir") {
    return baseItems.filter(item => !["Akun", "Laporan"].includes(item.label));
  }
  return baseItems;
});

const toggleDropdown = (index = null) => {
  if (index !== null) {
    openDropdownIndex.value = openDropdownIndex.value === index ? null : index;
  } else {
    isOpen.value = !isOpen.value;
  }
};

const toggleMobileMenu = () => {
  isMobileMenuOpen.value = !isMobileMenuOpen.value;
  isOpen.value = false;
  openDropdownIndex.value = null;
};

const closeMobileMenu = () => {
  isMobileMenuOpen.value = false;
  isOpen.value = false;
  openDropdownIndex.value = null;
};

const logout = async () => {
  try {
    await axios.post("/api/logout", null, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    });
    localStorage.removeItem("token");
    localStorage.removeItem("role");

    window.location.href = "/";
  } catch (error) {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem("token");
      localStorage.removeItem("role");
      window.location.href = "/";
    } else {
      console.error("Logout failed:", error);
    }
  }
  closeMobileMenu();
};

// Provide shared data to child components
provide("navigationData", {
  logo,
  items,
  isOpen,
  isMobileMenuOpen,
  openDropdownIndex,
  toggleDropdown,
  toggleMobileMenu,
  closeMobileMenu,
  logout
});
</script>

<template>
  <div class="relative">
    <!-- Desktop Navigation -->
    <NavDesktop />

    <!-- Mobile Navigation -->
    <NavMobile />

    <!-- Click Outside Handler for Desktop Dropdown -->
    <div v-if="openDropdownIndex !== null && !isMobileMenuOpen" @click="openDropdownIndex = null"
      class="fixed inset-0 z-10"></div>
  </div>
</template>
