<template>
  <div class="topbar">
    <div class="logo">万物收藏</div>
    <div class="search-wrap" ref="searchWrap">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" />
      </svg>
      <input
        ref="searchInput"
        type="text"
        placeholder="搜索收藏、标签、内容..."
        :value="searchQuery"
        @input="onInput"
        @keydown.enter="onEnter"
        @focus="showDropdown = true"
      />
      <!-- Dropdown -->
      <div v-if="showDropdown && (suggestions.length > 0 || history.length > 0)" class="search-dropdown">
        <!-- History -->
        <div v-if="!searchQuery.trim() && history.length > 0" class="dropdown-section">
          <div class="dropdown-head">最近搜索</div>
          <div
            v-for="(h, i) in history.slice(0, 8)"
            :key="i"
            class="dropdown-item"
            @mousedown.prevent="selectHistory(h)"
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            {{ h }}
          </div>
        </div>
        <!-- Suggestions -->
        <div v-if="searchQuery.trim() && suggestions.length > 0" class="dropdown-section">
          <div class="dropdown-head">建议</div>
          <div
            v-for="(s, i) in suggestions"
            :key="i"
            class="dropdown-item"
            @mousedown.prevent="selectSuggestion(s)"
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
            {{ s }}
          </div>
        </div>
      </div>
    </div>
    <div class="topbar-right">
      <button class="btn-add" @click="$emit('add')">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
          <path d="M12 5v14M5 12h14" />
        </svg>
        新增收藏
      </button>
      <div class="avatar">{{ user?.nickname?.[0] || user?.username?.[0] || '?' }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
defineProps<{ searchQuery: string; user: any }>();
const emit = defineEmits<{
  'update:searchQuery': [value: string];
  search: [];
  add: [];
}>();

const searchWrap = ref<HTMLElement>();
const searchInput = ref<HTMLInputElement>();
const showDropdown = ref(false);
const { suggestions, history, fetchSuggestions } = useSearch();

let debounceTimer: ReturnType<typeof setTimeout> | null = null;

function onInput(e: Event) {
  const val = (e.target as HTMLInputElement).value;
  emit('update:searchQuery', val);
  if (debounceTimer) clearTimeout(debounceTimer);
  if (val.trim()) {
    debounceTimer = setTimeout(() => fetchSuggestions(val), 250);
    showDropdown.value = true;
  } else {
    showDropdown.value = true;
  }
}

function onEnter() {
  showDropdown.value = false;
  emit('search');
}

function selectSuggestion(s: string) {
  emit('update:searchQuery', s);
  showDropdown.value = false;
  nextTick(() => emit('search'));
}

function selectHistory(h: string) {
  emit('update:searchQuery', h);
  showDropdown.value = false;
  nextTick(() => emit('search'));
}

// Click outside to close
onMounted(() => {
  document.addEventListener('click', onClickOutside);
});
onUnmounted(() => {
  document.removeEventListener('click', onClickOutside);
});
function onClickOutside(e: MouseEvent) {
  if (searchWrap.value && !searchWrap.value.contains(e.target as Node)) {
    showDropdown.value = false;
  }
}
</script>

<style scoped>
.topbar {
  height: 48px;
  background: var(--bg2);
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  padding: 0 16px;
  gap: 12px;
  flex-shrink: 0;
  z-index: 100;
}
.logo {
  font-family: var(--font-display);
  font-size: 16px;
  color: var(--accent);
  letter-spacing: 0.04em;
  white-space: nowrap;
  margin-right: 8px;
}
.search-wrap {
  flex: 1;
  max-width: 480px;
  position: relative;
}
.search-wrap svg {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0.4;
  z-index: 2;
}
.search-wrap input {
  width: 100%;
  background: var(--bg3);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 7px 12px 7px 34px;
  color: var(--text);
  font-family: var(--font-body);
  font-size: 13px;
  outline: none;
  transition: border-color 0.2s;
  position: relative;
  z-index: 10;
}
.search-wrap input::placeholder { color: var(--text3); }
.search-wrap input:focus { border-color: var(--border2); }

.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 4px;
  background: var(--bg2);
  border: 1px solid var(--border);
  border-radius: 8px;
  overflow: hidden;
  z-index: 200;
  box-shadow: 0 8px 24px rgba(0,0,0,0.4);
}
.dropdown-section { padding: 6px 0; }
.dropdown-head {
  padding: 6px 12px;
  font-size: 11px;
  color: var(--text3);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}
.dropdown-item {
  padding: 6px 12px;
  font-size: 13px;
  color: var(--text);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background 0.1s;
}
.dropdown-item:hover { background: var(--bg3); }
.dropdown-item svg { opacity: 0.35; flex-shrink: 0; position: static; transform: none; }

.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 8px; }
.btn-add {
  background: var(--accent);
  color: #1a1208;
  border: none;
  border-radius: 8px;
  padding: 7px 14px;
  font-family: var(--font-body);
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.2s, transform 0.1s;
}
.btn-add:hover { background: #d4b88a; }
.btn-add:active { transform: scale(0.97); }
.avatar {
  width: 30px; height: 30px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--teal), var(--blue));
  display: flex; align-items: center; justify-content: center;
  font-size: 12px; font-weight: 600; color: white; cursor: pointer;
}
</style>
