<script setup lang="ts">
import { computed } from "vue";

import type { Mentor } from "../../shared/api/mentor";

const props = defineProps<{
  mentors: Mentor[];
  selectedId: string;
  disabled: boolean;
}>();
const emit = defineEmits<{
  select: [mentor: Mentor];
  pin: [mentor: Mentor];
  move: [mentor: Mentor, delta: number];
  reorder: [sourceId: string, targetId: string];
}>();
const grade = defineModel<"all" | "A" | "B" | "C">("grade", { required: true });
const query = defineModel<string>("query", { required: true });
const filtered = computed(() => {
  const needle = query.value.trim().toLocaleLowerCase();
  return props.mentors.filter((mentor) => {
    if (grade.value !== "all" && mentor.grade !== grade.value) return false;
    const haystack = [mentor.name, mentor.description, mentor.tagline, ...mentor.focus].join(" ").toLocaleLowerCase();
    return !needle || haystack.includes(needle);
  });
});
</script>

<template>
  <aside class="card mentor-library" :aria-disabled="disabled">
    <header class="mentor-library-header">
      <div><h2>思维模型</h2><span class="muted">{{ filtered.length }} 位</span></div>
      <input v-model="query" class="input mentor-search" type="search" placeholder="搜索姓名、流派或标签" aria-label="搜索思维模型" />
      <div class="seg-control mentor-grade-filter">
        <button v-for="item in ['all', 'A', 'B', 'C']" :key="item" type="button" :class="{ active: grade === item }" @click="grade = item as typeof grade">{{ item === 'all' ? '全部' : `${item}级` }}</button>
      </div>
    </header>
    <div class="mentor-list">
      <article
        v-for="mentor in filtered"
        :key="mentor.id"
        class="mentor-item"
        :class="{ active: selectedId === mentor.id }"
        draggable="true"
        @click="emit('select', mentor)"
        @dragstart="($event.dataTransfer as DataTransfer).setData('text/plain', mentor.id)"
        @dragover.prevent
        @drop="emit('reorder', ($event.dataTransfer as DataTransfer).getData('text/plain'), mentor.id)"
      >
        <div class="mentor-item-main">
          <strong>{{ mentor.name }}</strong><span class="tag" :class="`mentor-grade-${mentor.grade.toLowerCase()}`">{{ mentor.grade }}</span>
          <span v-if="mentor.private" class="tag tag-admin">私有</span>
        </div>
        <p>{{ mentor.description || mentor.tagline }}</p>
        <div class="mentor-item-actions">
          <button class="icon-button" type="button" :title="mentor.pinned ? '取消置顶' : '置顶'" :aria-label="mentor.pinned ? '取消置顶' : '置顶'" @click.stop="emit('pin', mentor)">{{ mentor.pinned ? '★' : '☆' }}</button>
          <button class="icon-button" type="button" title="上移" aria-label="上移" @click.stop="emit('move', mentor, -1)">↑</button>
          <button class="icon-button" type="button" title="下移" aria-label="下移" @click.stop="emit('move', mentor, 1)">↓</button>
        </div>
      </article>
      <p v-if="!filtered.length" class="mentor-list-empty">没有匹配的思维模型</p>
    </div>
  </aside>
</template>
