<template>
  <nav class="kole-anchor" :class="{ fixed }">
    <template v-for="(it, i) in items" :key="it.key">
      <button class="kole-anchor-item" :class="{ 'is-active': active === it.key }" @click="go(it.key)">{{ it.label }}</button>
      <div v-if="it.children" class="kole-anchor-sub">
        <button
          v-for="c in it.children" :key="c.key"
          class="kole-anchor-item" :class="{ 'is-active': active === c.key }"
          @click="go(c.key)"
        >{{ c.label }}</button>
      </div>
    </template>
  </nav>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const props = defineProps({
  items: { type: Array, required: true },   // [{ key, label, children? }]（key 对应页面元素 id）
  fixed: { type: Boolean, default: false },
  offset: { type: Number, default: 24 }       // 滚动偏移（避开吸顶高度）
});

const active = ref(props.items[0] ? props.items[0].key : '');
const allKeys = [];
(function collect(list) { list.forEach(i => { allKeys.push(i.key); if (i.children) collect(i.children); }); })(props.items);

function go(key) {
  const el = document.getElementById(key);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - props.offset, behavior: 'smooth' });
}
function onScroll() {
  const pos = window.scrollY + 80;
  let cur = allKeys[0];
  for (const k of allKeys) {
    const el = document.getElementById(k);
    if (el && el.offsetTop <= pos) cur = k;
  }
  active.value = cur;
}
onMounted(() => window.addEventListener('scroll', onScroll));
onBeforeUnmount(() => window.removeEventListener('scroll', onScroll));
</script>

<!-- 样式对齐 组件7.txt AnchorNav 规范 -->
<style scoped>
.kole-anchor { font-family: var(--font-family, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif); width: 160px; }
.kole-anchor.fixed { position: fixed; right: 24px; top: 80px; }
.kole-anchor-item { display: block; padding: 6px 12px; font-size: 13px; color: #6E6E6E; cursor: pointer; border-left: 2px solid #E8ECF1; line-height: 1.4; transition: color .15s, border-color .15s; background: none; border-top: none; border-right: none; border-bottom: none; text-align: left; width: 100%; }
.kole-anchor-item:hover { color: #2F54EB; }
.kole-anchor-item.is-active { color: #2F54EB; border-left-color: #2F54EB; font-weight: 500; }
.kole-anchor-sub { padding-left: 8px; }
.kole-anchor-sub .kole-anchor-item { border-left: none; padding-left: 20px; }
.kole-anchor-sub .kole-anchor-item.is-active { border-left: 2px solid #2F54EB; }
</style>
