<template>
  <div v-if="messages.length > 0" class="bookmark-rail">
    <div
      v-for="msg in userMessages"
      :key="msg.id"
      class="bookmark"
      :class="{ active: activeId === msg.id }"
      @click="$emit('scrollTo', msg.id)"
    >
      <div class="bookmark-dot"></div>
      <div class="bookmark-label">{{ preview(msg) }}</div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  messages: { type: Array, required: true },
  activeId: { type: String, default: null },
})

defineEmits(['scrollTo'])

const userMessages = computed(() => props.messages.filter(m => m.role === 'user'))

function preview(msg) {
  if (!msg.text) return '...'
  // Clean markdown characters
  const clean = msg.text.replace(/[#*`~>\-\[\]()]/g, '').replace(/\s+/g, ' ').trim()
  const MAX_LENGTH = 30
  return clean.length > MAX_LENGTH ? clean.slice(0, MAX_LENGTH) + '...' : clean
}
</script>

<style scoped>
.bookmark-rail {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  z-index: 100;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  width: 10px;
  height: 70vh;
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 4px 0;
  transition: width 0.25s ease;
  scrollbar-width: none;
  -ms-overflow-style: none;
  margin-right: 40px;
}

.bookmark-rail::-webkit-scrollbar {
  display: none;
}

.bookmark-rail:hover {
  width: 10vw;
  max-width: 160px;
}

.bookmark {
  position: relative;
  display: flex;
  align-items: center;
  padding: 5px 6px;
  cursor: pointer;
  border-radius: 0;
  white-space: nowrap;
  overflow: hidden;
  background: transparent;
  transition: background 0.15s;
}

.bookmark:hover {
  background: var(--bg-hover);
  border-radius: 6px 0 0 6px;
}

.bookmark.active {
  background: var(--bg-active);
  border-radius: 6px 0 0 6px;
}

.bookmark-dot {
  width: 5px;
  height: 5px;
  border-radius: 1.5px;
  flex-shrink: 0;
  background: #3b82f6;
  opacity: 0.35;
  transition: all 0.2s ease;
}

.bookmark.active .bookmark-dot,
.bookmark-rail:hover .bookmark-dot {
  opacity: 1;
  width: 6px;
  height: 6px;
}

.bookmark-label {
  margin-left: 8px;
  font-size: 12px;
  line-height: 1.4;
  color: var(--text-secondary);
  opacity: 0;
  transform: translateX(8px);
  transition: all 0.2s ease;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bookmark-rail:hover .bookmark-label {
  opacity: 1;
  transform: translateX(0);
}

.bookmark.active .bookmark-label {
  color: var(--text-primary);
}
</style>
