<template>
  <!-- Email Verification Banner -->
  <div
    v-if="$root.user && $root.user.role === 'unverified'"
    class="bg-amber-400/10 border-b border-amber-400/30 px-3 py-2 flex items-center justify-between gap-3"
  >
    <div class="flex items-center gap-2">
      <span class="ph ph-warning-circle text-amber-400 text-lg"></span>
      <span class="text-amber-200 text-sm">
        {{ $root.translations.navbar_verify_email_text }}
      </span>
    </div>
    <BaseButton
      type="secondary"
      size="small"
      class="h-7 text-xs whitespace-nowrap bg-amber-400/20 hover:bg-amber-400/30 text-amber-200 border-amber-400/30"
      :label="$root.translations.navbar_resend_email"
      :disabled="resendingVerification"
      @click="resendVerification"
    />
  </div>

  <nav
    :class="$route.path.includes('chat/') ? 'hidden md:flex' : 'flex'"
    class="items-center gap-2 border-b border-theme-900 justify-between p-2 pr-3 md:pr-4"
  >
    <div class="flex items-center gap-2">
      <img
        v-if="!isNonDefaultTheme"
        :srsgc="$root.serveImg('/media/logo/transparent.png')"
        :src="$root.serveImg('/api/logo.php')"
        @click="!$route.path.includes('home') ? $router.push('/home') : null"
        class="w-12 h-12 object-cover"
        ondragstart="return false;"
        alt=""
      />
      <ThemedLogo
        v-else
        class="w-12 h-12 cursor-pointer block"
        @click="!$route.path.includes('home') ? $router.push('/home') : null"
      />
      <router-link
        to="/"
        class="text-theme-100 text-xl text-center font-extrabold flex gap-1 items-center justify-center"
      >
        {{ pathName }}
        <div
          v-if="$root.get_plan() == 0 && this.$root.info.name == pathName"
          class="bg-brand-400 text-theme-900 px-2 text-xs rounded"
        >
          {{ $root.info.version }}
        </div>
        <div
          v-else-if="this.$root.info.name == pathName"
          class="bg-amber-400 text-theme-900 px-2 text-xs rounded"
        >
          {{ $root.user.subscription.plan_name.split(' ')[0] }}
        </div>
      </router-link>

      <!-- Tabs for PC -->
      <div
        v-if="isPC && $root.user && $root.user.settings && $root.user.settings.enable_tabs !== false"
        class="flex-grow ml-2 flex items-center justify-center"
      >
        <div class="flex items-center gap-1 py-1">
          <div
            v-for="(tab, index) in $root.tabs"
            :key="tab.path"
            @click="navigateTo(tab.path)"
            @dragstart="dragStart(index)"
            @dragover.prevent
            @drop="drop(index)"
            draggable="true"
            class="flex items-center gap-1 px-3 rounded-md cursor-pointer transition-all select-none duration-200 h-8"
            :class="tabButtonClasses(tab)"
          >
            <template v-if="tab.icon">
              <img
                v-if="!tab.iconError"
                class="w-5 h-5 rounded-md"
                :src="$root.baseUrl + tab.icon"
                @error="handleIconError(tab)"
              />
              <span
                v-else
                class="ph ph-image w-5 h-5 flex items-center justify-center text-lg"
              ></span>
            </template>
            <span class="text-sm whitespace-nowrap">
              {{ tab.title }}
            </span>
            <button
              @click.stop="closeTab(index)"
              class="ml-1 flex items-center justify-center text-theme-400 ph ph-x hover:text-white text-sm"
              style="line-height: 1"
            >
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="flex relative items-center gap-2">
      <BaseButton
        v-if="$root.user ? isPC : true"
        type="secondary"
        size="small"
        class="h-8"
        icon="ph-book-open"
        @click="$router.push('/documentation')"
      />

      <BaseButton
        v-if="$root.user"
        type="secondary"
        size="small"
        class="hidden 2xl:flex h-8"
        icon="ph-trophy"
        @click="openAchievementsModal('achievements', 'store')"
      />

      <!-- Alerts Button -->
      <BaseButton
        v-if="$root.user"
        type="secondary"
        size="small"
        class="h-8 relative"
        icon="ph-bell"
        @click="$root.openModal('notifications')"
      >
        <template v-if="unreadCount > 0" #badge>
          <span
            class="absolute -top-1 -right-1 bg-brand-400 text-theme-900 text-[10px] rounded-full h-4 w-4 flex items-center justify-center"
          >
            {{ unreadCount }}
          </span>
        </template>
      </BaseButton>

      <div
        v-if="!$root.user"
        class="flex gap-2 justify-end items-center"
      >
        <BaseButton
          :label="$root.translations.login"
          type="ghost"
          size="small"
          class="hidden sm:flex h-8"
          @click="$root.openModal('login')"
        />
        <BaseButton
          :label="$root.translations.register"
          type="primary"
          size="small"
          icon="ph-arrow-right"
          class="h-8"
          @click="$root.openModal('register')"
        />
      </div>

      <div
        v-else
        class="flex gap-2 justify-end items-center"
      >
        <BaseButton
          :label="isPC ? $root.translations.profile : ''"
          type="secondary"
          size="small"
          icon="ph-user"
          class="h-8"
          @click="handleProfileClick"
        />
      </div>
    </div>
  </nav>
</template>

<script>
import BaseButton from "../modules/BaseButton.vue";
import ThemedLogo from "./ThemedLogo.vue";

export default {
  components: {
    BaseButton,
    ThemedLogo,
  },
  name: "Navbar",
  data() {
    return {
      isPC: false,
      draggedIndex: null,
      unreadCount: 0,
      resendingVerification: false,
    };
  },
  created() {
    this.checkIfPC();
    window.addEventListener("resize", this.checkIfPC);
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$root.user && this.$root.user.settings && this.$root.user.settings.enable_tabs !== false) {
        this.loadTabs();
        this.addTab(this.$route);
      }
    });
    this.fetchNotifications();
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.checkIfPC);
  },
  watch: {
    $route(to, from) {
      console.log("Route changed from", from.name, "to", to.name);
      if (this.isPC && this.$root.user && this.$root.user.settings && this.$root.user.settings.enable_tabs !== false) this.addTab(to);
    },
    "$root.tabs": {
      handler() {
        if (this.$root.user && this.$root.user.settings && this.$root.user.settings.enable_tabs !== false) {
          this.saveTabs();
        }
      },
      deep: true,
    },
  },
  methods: {
    handleIconError(tab) {
      if (tab) {
        tab.iconError = true;
      }
    },
    checkIfPC() {
      this.isPC = window.innerWidth > 768;
    },
    goToStoreHome() {
      if (!this.$root?.requireStoreAccess?.({ promptLogin: !this.$root?.user })) {
        return;
      }

      if (this.$route.path !== "/store") {
        this.$router.push("/store");
      }
    },
    goToStoreTab(tab) {
      if (!this.$root?.requireStoreAccess?.({ promptLogin: !this.$root?.user })) {
        return;
      }

      this.$router.push({
        path: "/store",
        query: {
          tab,
        },
      });
    },
    openCreateStoreListingModal() {
      if (!this.$root?.requireStoreAccess?.({ promptLogin: !this.$root?.user })) {
        return;
      }

      this.$root.openModal("CreateStoreListingModal", {
        onViewListing: (listing) => {
          this.$router.push(`/store/${listing.id}`);
        },
      });
    },
    openAchievementsModal(initialTab = "overview", initialCategory = "all") {
      if (!this.$root.user) {
        this.$root.openModal("login");
        return;
      }

      this.$root.openModal("AchievementsModal", {
        initialTab,
        initialCategory,
      });
    },
    handleProfileClick() {
      this.$router.push("/dashboard");
    },
    async resendVerification() {
      this.resendingVerification = true;
      try {
        const response = await this.$root.handleRequest("resendVerificationEmail", {});
        if (response.status === 200) {
          this.$root.showToast("Verification email sent! Check your inbox.", "success");
        } else {
          this.$root.showToast(response.message || "Failed to resend verification email.", "error");
        }
      } catch (error) {
        console.error("Error resending verification:", error);
        this.$root.showToast("Failed to resend verification email.", "error");
      } finally {
        this.resendingVerification = false;
      }
    },
    async fetchNotifications() {
      try {
        let response = await this.$root.handleRequest(
          "getUserNotifications",
          {}
        );
        if (response.success) {
          this.unreadCount = response.data.unread_count;
        }
      } catch (error) {
        console.error("Error fetching notifications:", error);
      }
    },
    addTab(route) {
      if (!this.$root.tabs.some(tab => tab.path === route.path)) {
        if (this.$root.tabs.length >= 4) {
          let oldestTabIndex = 0;
          for (let i = 1; i < this.$root.tabs.length; i++) {
            if (
              this.$root.tabs[i].timestamp <
              this.$root.tabs[oldestTabIndex].timestamp
            ) {
              oldestTabIndex = i;
            }
          }
          this.$root.tabs.splice(oldestTabIndex, 1);
        }
        this.$root.tabs.push({
          name: route.name,
          path: route.path,
          title: this.getRouteTitle(route),
          icon: route.meta.icon,
          timestamp: Date.now(),
        });
      }
    },
    getRouteTitle(route) {
      if (route.path.includes("chat")) return this.$root.translations.chats;
      if (route.path.includes("characters")) return this.$root.translations.navbar_tab_your_characters;
      if (route.path.includes("studio")) return this.$root.translations.navbar_tab_image_studio;
      if (route.path.includes("dashboard")) return this.$root.translations.dashboard;
      if (route.path === "/store") return this.$root.translations.store;
      if (route.path.includes("/store/")) return this.$root.translations.navbar_tab_store_item;
      return this.$root.info.name;
    },
    closeTab(index) {
      this.$root.tabs.splice(index, 1);
      if (this.$root.tabs.length > 0) {
        const newIndex = Math.max(0, index - 1);
        this.$router.push({ name: this.$root.tabs[newIndex].name });
      } else {
        this.$router.push("/home");
      }
    },
    navigateTo(routePath) {
      this.$router.push(routePath);
    },
    dragStart(index) {
      this.draggedIndex = index;
    },
    drop(index) {
      const draggedTab = this.$root.tabs[this.draggedIndex];
      this.$root.tabs.splice(this.draggedIndex, 1);
      this.$root.tabs.splice(index, 0, draggedTab);
      this.draggedIndex = null;
    },
    saveTabs() {
      const tabsToSave = JSON.parse(JSON.stringify(this.$root.tabs));
      tabsToSave.forEach(tab => delete tab.iconError);
      localStorage.setItem("tabs", JSON.stringify(tabsToSave));
    },
    loadTabs() {
      const savedTabs = localStorage.getItem("tabs");
      if (savedTabs) {
        this.$root.tabs = JSON.parse(savedTabs);
      } else {
        this.$root.tabs = [];
      }
    },
    tabButtonClasses(tab) {
      const isActive = this.$route.path === tab.path;

      const gradientTypeClasses = {
        active:
          "border-t-2 border-b-2 border-t-theme-900 border-b-theme-950 shadow-theme-950/50 bg-gradient-to-b from-theme-920 to-theme-940 text-theme-300 active:bg-gradient-to-t active:border-t-theme-950 active:border-b-theme-900",
        inactive:
          "border-t-2 border-b-2 border-t-theme-900 border-b-theme-950 bg-gradient-to-b from-theme-900/40 to-theme-900/20 text-theme-400 hover:text-theme-200 hover:from-theme-900/60 hover:to-theme-900/40",
      };

      const flatTypeClasses = {
        active:
          "bg-theme-900 text-theme-200 active:bg-theme-800",
        inactive:
          "bg-theme-900/50 text-theme-400 hover:bg-theme-900/70 hover:text-theme-200",
      };

      const typeClasses = this.$root.newTheme
        ? flatTypeClasses
        : gradientTypeClasses;

      const base =
        "text-sm border-none";

      const stateClass = isActive
        ? typeClasses.active
        : typeClasses.inactive;

      return [base, stateClass].join(" ");
    },
  },
  computed: {
    canAccessStore() {
      return this.$root?.canAccessStore?.() === true;
    },
    isNonDefaultTheme() {
      const active = this.$root?.activeThemeId;
      const def = this.$root?.themeRegistry?.defaultTheme || window.__MIOC_CONFIG?.defaultTheme || 'midnight';
      return !!active && active !== def;
    },
    pathName() {
      if (this.$route.path.includes("chat")) return this.$root.translations.chats;
      if (this.$route.path.includes("characters")) return this.$root.translations.navbar_tab_your_characters;
      if (this.$route.path === "/store") return this.$root.translations.store;
      if (this.$route.path.includes("/store/")) return this.$root.translations.navbar_tab_store_item;
      return this.$root.info.name;
    },
    showStoreContextActions() {
      return ["/dashboard", "/store", "/profile/"].some((segment) =>
        this.$route.path.includes(segment)
      );
    },
  },
};
</script>

<style scoped>
.tabs-container {
}
</style>
