<script setup>
import { useAuthStore } from "@/stores/authStore";
import { useSettingStore } from "@/stores/settingStore";
import AccountSettingsCacheManagement from "@/views/pages/account-settings/AccountSettingsCacheManagement.vue";
import AccountSettingsFacebook from "@/views/pages/account-settings/AccountSettingsFacebook.vue";
import AccountSettingsFooter from "@/views/pages/account-settings/AccountSettingsFooter.vue";
import AccountSettingsGeneral from "@/views/pages/account-settings/AccountSettingsGeneral.vue";
import AccountSettingsGoogleCaptcha from "@/views/pages/account-settings/AccountSettingsGoogleCaptcha.vue";
import AccountSettingsGoogleTag from "@/views/pages/account-settings/AccountSettingsGoogleTag.vue";
import AccountSettingsHeader from "@/views/pages/account-settings/AccountSettingsHeader.vue";
import AccountSettingsPayment from "@/views/pages/account-settings/AccountSettingsPayment.vue";
import AccountSettingsSignature from "@/views/pages/account-settings/AccountSettingsSignature.vue";
import AccountSettingsWhatsapp from "@/views/pages/account-settings/AccountSettingsWhatsapp.vue";
import { storeToRefs } from "pinia";
import { computed, nextTick, onBeforeMount, onMounted, onUnmounted, ref, watch } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const activeSection = ref("general");

const authStore = useAuthStore();
const { user: authUser } = storeToRefs(authStore);

const settingStore = useSettingStore();
const { setting, error, loading } = storeToRefs(settingStore);

// Create a ref to track observer
const observer = ref(null);

const allSidebarItems = [
  {
    title: "General Setting",
    id: "general",
    icon: "bx-cog",
  },
  // {
  //   title: "Security",
  //   id: "security",
  //   icon: "bx-lock-open",
  // },
  {
    title: "Header Settings",
    id: "header",
    icon: "bx-layout",
  },
  {
    title: "Footer Settings",
    id: "footer",
    icon: "bx-dock-bottom",
  },
  {
    title: "Payment Integration",
    id: "payment",
    icon: "bx-credit-card",
  },
  {
    title: "Email Signature",
    id: "signature",
    icon: "bx-pen",
  },
  {
    title: "WhatsApp Setting",
    id: "whatsapp",
    icon: "bxl-whatsapp",
  },
  {
    title: "Facebook",
    id: "facebook",
    icon: "bxl-facebook",
  },
  {
    title: "Social Links",
    id: "social-links",
    icon: "bx-share-alt",
  },
  {
    title: "Google Tag Manager",
    id: "google-tag",
    icon: "bx-code-alt",
  },
  {
    title: "Google Captcha",
    id: "google-captcha",
    icon: "bx-shield",
  },
];

// Computed property to check if user is super_admin
const isSuperAdmin = computed(() => {
  return authUser.value?.data?.role === "super_admin";
});

// Filter sidebar items: show General, Security, Header, Footer, Payment for all users
const sidebarItems = computed(() => {
  const base = [
    "general",
    // "security",
    "header",
    "footer",
    "payment",
    "signature",
  ];
  if (isSuperAdmin.value) {
    return allSidebarItems.filter((item) =>
      [
        "general",
        // "security",
        "header",
        "footer",
        "payment",
        "google-tag",
        "google-captcha",
        "signature",
      ].includes(item.id),
    );
  }
  // non-super_admin (franchisee admins) sees base + signature + WhatsApp + Facebook
  // super_admin sees base + signature + Google sections
  // Signature behavior: Super admin global signature cascades to franchisees, who can override
  return allSidebarItems.filter((item) =>
    [...base, "whatsapp", "facebook"].includes(item.id),
  );
});

const scrollToSection = (sectionId) => {
  activeSection.value = sectionId;
  const element = document.getElementById(sectionId);
  if (element) {
    element.scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
  }
};

// Function to setup intersection observer with improved configuration
const setupIntersectionObserver = () => {
  // Disconnect existing observer if it exists
  if (observer.value) {
    observer.value.disconnect();
  }

  // Track which sections are currently intersecting with their ratios
  const intersectingSections = new Map();

  observer.value = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        // Update the map with current intersection state
        if (entry.isIntersecting) {
          intersectingSections.set(entry.target.id, entry.intersectionRatio);
        } else {
          intersectingSections.delete(entry.target.id);
        }
      });

      // Find the section with highest intersection ratio
      if (intersectingSections.size > 0) {
        let maxRatio = 0;
        let mostVisibleSection = "";

        intersectingSections.forEach((ratio, id) => {
          if (ratio > maxRatio) {
            maxRatio = ratio;
            mostVisibleSection = id;
          }
        });

        if (mostVisibleSection) {
          activeSection.value = mostVisibleSection;
        }
      }
    },
    {
      // Multiple thresholds to catch sections at different visibility levels
      threshold: [0, 0.1, 0.25, 0.5, 0.75, 1],
      // Adjusted rootMargin for better detection
      rootMargin: "-20% 0px -60% 0px",
    },
  );

  // Observe all visible sections based on current sidebarItems
  sidebarItems.value.forEach((item) => {
    const element = document.getElementById(item.id);
    if (element) {
      observer.value.observe(element);
    }
  });
};

onBeforeMount(async () => {
  const returningFromStripe =
    route.query.stripe_onboarding === "1" ||
    route.query.stripe_onboarding === "true";

  if (returningFromStripe) {
    await settingStore.syncAfterStripeOnboarding();
  } else {
    await settingStore.getSetting();
  }
});

onMounted(async () => {
  const sectionFromQuery =
    typeof route.query.section === "string" ? route.query.section : "";

  if (
    sectionFromQuery &&
    sidebarItems.value.some((item) => item.id === sectionFromQuery)
  ) {
    activeSection.value = sectionFromQuery;
    await nextTick();
    setTimeout(() => scrollToSection(sectionFromQuery), 200);
  }

  await nextTick();
  setTimeout(() => {
    setupIntersectionObserver();
  }, 150);
});

// Watch for changes in isSuperAdmin to re-setup observer when role-dependent sections change
watch(
  isSuperAdmin,
  async () => {
    await nextTick();
    setTimeout(() => {
      setupIntersectionObserver();
    }, 150);
  },
  { flush: "post" },
);

onUnmounted(() => {
  if (observer.value) {
    observer.value.disconnect();
  }
});
</script>

<template>
  <div class="settings-container">
    <VRow>
      <!-- Sidebar Navigation -->
      <VCol cols="12" md="4" lg="3">
        <VCard class="sidebar-nav sticky-sidebar">
          <VList nav>
            <VListItem
              v-for="item in sidebarItems"
              :key="item.id"
              :class="{ 'v-list-item--active': activeSection === item.id }"
              @click="scrollToSection(item.id)"
              class="sidebar-item"
            >
              <template #prepend>
                <VIcon :icon="item.icon" size="20" />
              </template>

              <VListItemTitle class="sidebar-title">
                {{ item.title }}
              </VListItemTitle>

              <template #append>
                <VIcon icon="bx-chevron-right" size="16" />
              </template>
            </VListItem>
          </VList>
        </VCard>
      </VCol>

      <!-- Content Sections -->
      <VCol cols="12" md="8" lg="9">
        <div class="content-sections">
          <!-- General Section -->
          <section id="general" class="content-section">
            <AccountSettingsGeneral />
          </section>

          <!-- Cache Management Section -->
          <section id="cache" class="content-section">
            <AccountSettingsCacheManagement />
          </section>

          <!-- Security Section -->
          <!-- <section id="security" class="content-section">
            <AccountSettingsSecurity />
          </section> -->

          <!-- Header Section - Visible to all users -->
          <section id="header" class="content-section">
            <AccountSettingsHeader />
          </section>

          <!-- Footer Section - Visible to all users -->
          <section id="footer" class="content-section">
            <AccountSettingsFooter />
          </section>

          <!-- Payment Integration Section - Visible to all users -->
          <section id="payment" class="content-section">
            <AccountSettingsPayment />
          </section>

          <!-- Signature Section - Visible to all users (Super admin sets global, franchisees can override) -->
          <section id="signature" class="content-section">
            <AccountSettingsSignature />
          </section>

          <!-- Only render non-super_admin sections -->
          <template v-if="!isSuperAdmin">
            <section id="whatsapp" class="content-section">
              <AccountSettingsWhatsapp />
            </section>

            <section id="facebook" class="content-section">
              <AccountSettingsFacebook />
            </section>
          </template>

          <!-- Only super_admin sees Google sections -->
          <template v-if="isSuperAdmin">
            <section id="google-tag" class="content-section">
              <AccountSettingsGoogleTag />
            </section>

            <section id="google-captcha" class="content-section">
              <AccountSettingsGoogleCaptcha />
            </section>
          </template>
        </div>
      </VCol>
    </VRow>
  </div>
</template>

<style scoped>
.settings-container {
  min-height: 100vh;
}

.sticky-sidebar {
  position: sticky;
  top: 106px;
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.sidebar-nav {
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  min-width: 280px;
}

.sidebar-item {
  margin: 4px 8px;
  border-radius: 8px;
  transition: all 0.2s ease;
  cursor: pointer;
  min-height: 52px;
  padding: 8px 12px;
}

.sidebar-item:hover {
  background-color: rgba(var(--v-theme-primary), 0.1);
}

.sidebar-item.v-list-item--active {
  background-color: rgba(var(--v-theme-primary), 0.15);
  color: rgb(var(--v-theme-primary));
}

.sidebar-title {
  font-weight: 500;
  font-size: 0.95rem;
  white-space: nowrap;
  overflow: visible;
  text-overflow: unset;
  line-height: 1.3;
  word-wrap: break-word;
}

.content-section {
  scroll-margin-top: 80px;
  /* Add spacing between sections */
  margin-bottom: 0.75rem;
}

.content-sections {
  padding-left: 16px;
}

/* Responsive adjustments */
@media (max-width: 960px) {
  .sidebar-nav {
    min-width: unset;
  }

  .sidebar-title {
    font-size: 0.9rem;
  }

  .content-section {
    scroll-margin-top: 60px;
  }
}

/* Ensure sidebar has enough space for long text */
@media (min-width: 960px) {
  .sidebar-nav {
    width: 100%;
    max-width: 300px;
  }
}
</style>
