<template>
  <div class="collapse-navigation" :style="{ width: width }">
    <!-- <div class="nav-header" v-if="title">
      {{ title }}
    </div> -->
    <div class="nav-list">
      <div
        v-for="item in navItems"
        :key="item.name"
        class="nav-item"
        :class="{ active: currentItem === item.name }"
        @click="scrollToItem(item)"
      >
        <span class="nav-dot"></span>
        <span class="nav-text">{{ item.label || item.name }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from "vue";

const props = defineProps({
  // 导航项列表
  navItems: {
    type: Array,
    default: () => [],
  },
  // 当前激活的项
  activeItem: {
    type: [String, Array],
    default: "",
  },
  // 导航宽度
  width: {
    type: String,
    default: "200px",
  },
  // 导航标题
  title: {
    type: String,
    default: "快速导航",
  },
  // 滚动容器选择器（默认为 window）
  scrollContainer: {
    type: String,
    default: "",
  },
  // 偏移量（用于修正滚动位置）
  offset: {
    type: Number,
    default: 0,
  },
  // 折叠面板的 v-model 绑定值（用于自动展开折叠面板）
  collapseActiveNames: {
    type: Array,
    default: null,
  },
});

const emit = defineEmits([
  "update:activeItem",
  "navClick",
  "update:collapseActiveNames",
]);

const currentItem = ref("");
const scrollContainerEl = ref(null);

// 初始化滚动容器
const initScrollContainer = () => {
  if (props.scrollContainer) {
    scrollContainerEl.value = document.querySelector(props.scrollContainer);
  } else {
    scrollContainerEl.value = window;
  }
};

// 滚动到指定项
const scrollToItem = (item) => {
  const targetId = `collapse-${item.name}`;
  const targetElement = document.getElementById(targetId);

  console.log("CollapseNavigation - Scrolling to:", {
    targetId,
    item,
    found: !!targetElement,
    allIds: Array.from(document.querySelectorAll('[id^="collapse-"]')).map(
      (el) => el.id,
    ),
  });

  if (targetElement) {
    // 使用更简单的滚动方式
    targetElement.scrollIntoView({
      behavior: "smooth",
      block: "start",
      inline: "nearest",
    });

    // 如果有偏移量，再进行微调
    if (props.offset !== 0) {
      setTimeout(() => {
        const elementPosition = targetElement.getBoundingClientRect().top;
        const offsetPosition =
          elementPosition + window.pageYOffset - props.offset;

        window.scrollTo({
          top: offsetPosition,
          behavior: "smooth",
        });
      }, 100);
    }

    currentItem.value = item.name;
    emit("update:activeItem", item.name);
    emit("navClick", item);
  } else {
    console.error("CollapseNavigation - Target element not found:", targetId);
  }
};

// 检测当前可见的折叠面板
const detectCurrentItem = () => {
  const container = scrollContainerEl.value;
  const containerRect =
    container === window
      ? { top: 0, bottom: window.innerHeight }
      : container.getBoundingClientRect();

  let maxVisibility = 0;
  let bestItem = "";

  props.navItems.forEach((item) => {
    const targetId = `collapse-${item.name}`;
    const targetElement = document.getElementById(targetId);

    if (targetElement) {
      const rect = targetElement.getBoundingClientRect();
      const visibleTop = Math.max(rect.top, containerRect.top);
      const visibleBottom = Math.min(rect.bottom, containerRect.bottom);
      const visibleHeight = Math.max(0, visibleBottom - visibleTop);
      const visibility = visibleHeight / rect.height;

      if (visibility > maxVisibility && visibility > 0.3) {
        maxVisibility = visibility;
        bestItem = item.name;
      }
    }
  });

  if (bestItem && bestItem !== currentItem.value) {
    currentItem.value = bestItem;
    emit("update:activeItem", bestItem);
  }
};

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

const debouncedDetect = debounce(detectCurrentItem, 100);

// 监听滚动事件
const handleScroll = () => {
  debouncedDetect();
};

// 监听 activeItem 变化
watch(
  () => props.activeItem,
  (newVal) => {
    if (Array.isArray(newVal)) {
      currentItem.value = newVal[0] || "";
    } else {
      currentItem.value = newVal;
    }
  },
  { immediate: true },
);

onMounted(() => {
  initScrollContainer();
  if (scrollContainerEl.value) {
    scrollContainerEl.value.addEventListener("scroll", handleScroll, {
      passive: true,
    });
    // 延迟检测，等待 DOM 渲染完成
    setTimeout(detectCurrentItem, 300);
  }
});

onBeforeUnmount(() => {
  if (scrollContainerEl.value) {
    scrollContainerEl.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style lang="less" scoped>
.collapse-navigation {
  position: sticky;
  top: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 40px);
  overflow-y: auto;
  z-index: 100;

  .nav-header {
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    border-bottom: 1px solid #ebeef5;
    background: #f5f7fa;
  }

  .nav-list {
    padding: 8px 0;
  }

  .nav-item {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;

    &:hover {
      background: #f5f7fa;

      .nav-dot {
        background: #409eff;
        transform: scale(1.2);
      }
    }

    &.active {
      background: #ecf5ff;
      color: #409eff;
      font-weight: 500;

      .nav-dot {
        background: #409eff;
        transform: scale(1.3);
      }

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 3px;
        background: #409eff;
      }
    }

    .nav-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #c0c4cc;
      margin-right: 8px;
      transition: all 0.3s;
      flex-shrink: 0;
    }

    .nav-text {
      flex: 1;
      font-size: 13px;
      color: #606266;
      word-break: break-all;
    }
  }
}

// 滚动条样式
.collapse-navigation::-webkit-scrollbar {
  width: 4px;
}

.collapse-navigation::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 2px;
}

.collapse-navigation::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>
