<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from "vue";
import { load } from "@tauri-apps/plugin-store";
import { open, save } from "@tauri-apps/plugin-dialog";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { Tag as TagIcon, FolderOpen, Settings, Play, Pause, Maximize2, X, RefreshCw, Plus, Trash2, ChevronDown, ChevronLeft, ChevronRight, Calendar } from "lucide-vue-next";

// --- Types ---
interface Tag { id: number; name: string; parent_id: number | null; color: string; }
interface DBEvent { id: number; date: string; start_minute: number; end_minute: number; main_tag_id: number; sub_tag_id: number | null; content: string; }
interface TimelineItem { time: string; path: string; isNextDay?: boolean; }

const TOTAL_MINUTES = 24 * 60;
const TIME_OFFSET_MINUTES = 3 * 60;

// --- State ---
const isSetupComplete = ref(false);
const savePath = ref("");
const dbPath = ref("");
const isPaused = ref(false);
const currentDate = ref(new Date().toISOString().split("T")[0]);
const timelineImages = ref<TimelineItem[]>([]);
const selectedImage = ref<TimelineItem | null>(null);
const lockedImage = ref<TimelineItem | null>(null);
const previewSrc = ref("");
const isFullscreen = ref(false);
const isSettingsOpen = ref(false);
const isTagManagerOpen = ref(false);
const isEventModalOpen = ref(false);

const toast = ref({ message: "", type: "success", visible: false });
const showToast = (message: string, type = "success") => {
  toast.value = { message, type, visible: true };
  setTimeout(() => { toast.value.visible = false; }, 3000);
};

const mergeScreens = ref(false);
const retainDays = ref(30);
const captureInterval = ref(30);
const timelineZoom = ref(1.5);

const tags = ref<Tag[]>([]);
const dayEvents = ref<DBEvent[]>([]);
const isDragging = ref(false);
const dragStartMin = ref<number | null>(null);
const dragEndMin = ref<number | null>(null);

const editingEvent = ref<DBEvent>({ id: 0, date: "", start_minute: 0, end_minute: 0, main_tag_id: 0, sub_tag_id: null, content: "" });
const hoveredTime = ref<string | null>(null);
const timelineRef = ref<HTMLElement | null>(null);

const rulerHeight = computed(() => TOTAL_MINUTES * timelineZoom.value);
const mainTags = computed(() => tags.value.filter(t => t.parent_id === null));
const getSubTags = (parentId: number) => tags.value.filter(t => t.parent_id === parentId);
const getTagColor = (tagId: number) => tags.value.find(t => t.id === tagId)?.color || "#007AFF";
const getTagName = (tagId: number | null) => tags.value.find(t => t.id === tagId)?.name || "-- 无 --";

let store: any = null;
let captureUnlisten: any = null;

// --- Custom Picker States ---
const calendarRef = ref<HTMLElement | null>(null);
const startTimePickerRef = ref<HTMLElement | null>(null);
const endTimePickerRef = ref<HTMLElement | null>(null);
const tagSelectRef = ref<HTMLElement | null>(null);

const isCalendarOpen = ref(false);
const calendarMonth = ref(new Date());
const isStartTimeOpen = ref(false);
const isEndTimeOpen = ref(false);

const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (isCalendarOpen.value && calendarRef.value && !calendarRef.value.contains(target)) {
    isCalendarOpen.value = false;
  }
  if (isStartTimeOpen.value && startTimePickerRef.value && !startTimePickerRef.value.contains(target)) {
    isStartTimeOpen.value = false;
  }
  if (isEndTimeOpen.value && endTimePickerRef.value && !endTimePickerRef.value.contains(target)) {
    isEndTimeOpen.value = false;
  }
  if (isTagSelectOpen.value && tagSelectRef.value && !tagSelectRef.value.contains(target)) {
    isTagSelectOpen.value = false;
  }
};

const openStartTimePicker = async () => {
  isStartTimeOpen.value = !isStartTimeOpen.value;
  isEndTimeOpen.value = false;
  if (isStartTimeOpen.value) {
    await nextTick();
    const activeItems = document.querySelectorAll('.z-\\[120\\] .bg-\\[\\#007AFF\\].text-white');
    activeItems.forEach(el => el.scrollIntoView({ block: 'center' }));
  }
};

const openEndTimePicker = async () => {
  isEndTimeOpen.value = !isEndTimeOpen.value;
  isStartTimeOpen.value = false;
  if (isEndTimeOpen.value) {
    await nextTick();
    const activeItems = document.querySelectorAll('.z-\\[120\\] .bg-\\[\\#007AFF\\].text-white');
    activeItems.forEach(el => el.scrollIntoView({ block: 'center' }));
  }
};

const calendarDays = computed(() => {
  const y = calendarMonth.value.getFullYear();
  const m = calendarMonth.value.getMonth();
  const firstDay = new Date(y, m, 1).getDay();
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const days = [];
  const padding = (firstDay + 6) % 7;
  for (let i = 0; i < padding; i++) days.push(null);
  for (let i = 1; i <= daysInMonth; i++) days.push(new Date(y, m, i));
  return days;
});

const selectCalendarDate = (date: Date) => {
  currentDate.value = date.toLocaleDateString('sv'); // sv locale gives YYYY-MM-DD
  isCalendarOpen.value = false;
  loadTimeline(true); loadEvents();
};

// --- Logic ---
onMounted(async () => {
  window.addEventListener('mousedown', handleClickOutside);
  store = await load("config.json");
  const path = await store.get("savePath");
  const dPath = await store.get("dbPath");
  if (path && dPath) {
    savePath.value = path as string;
    dbPath.value = dPath as string;
    isSetupComplete.value = true;
    await invoke("update_db_path", { path: dbPath.value });
    mergeScreens.value = (await store.get("mergeScreens")) as boolean || false;
    retainDays.value = (await store.get("retainDays")) as number || 30;
    captureInterval.value = (await store.get("captureInterval")) as number || 30;
    timelineZoom.value = (await store.get("timelineZoom")) as number || 1.5;
    await invoke("update_interval", { seconds: captureInterval.value });
    isPaused.value = await invoke("get_pause_state");
    await loadTimeline(true); await loadTags(); await loadEvents();
  }
  await listen<boolean>("pause-state-changed", (event) => { isPaused.value = event.payload; });
  captureUnlisten = await listen("refresh-timeline", () => { loadTimeline(); });
});

onUnmounted(() => { 
  window.removeEventListener('mousedown', handleClickOutside);
  if (captureUnlisten) captureUnlisten(); 
});

const selectFolder = async () => { const s = await open({ directory: true }); if (s) savePath.value = s as string; };
const selectDBFile = async () => { const s = await open({ filters: [{ name: "SQLite", extensions: ["db"] }] }); if (s) dbPath.value = s as string; };
const createDBFile = async () => { const s = await save({ filters: [{ name: "SQLite", extensions: ["db"] }] }); if (s) dbPath.value = s as string; };

const completeSetup = async () => {
  if (savePath.value && dbPath.value) {
    await store.set("savePath", savePath.value);
    await store.set("dbPath", dbPath.value);
    await store.save();
    await invoke("update_db_path", { path: dbPath.value });
    isSetupComplete.value = true;
    await loadTimeline(true); await loadTags(); await loadEvents();
  }
};

const loadTags = async () => { tags.value = await invoke("get_tags"); };
const loadEvents = async () => { dayEvents.value = await invoke("get_events", { date: currentDate.value }); };

const handleAddTag = async (name: string, parentId: number | null, color: string) => {
  try {
    await invoke("add_tag", { name, parentId, color });
    await loadTags();
    showToast("标签添加成功");
  } catch (e) {
    showToast("添加失败: " + e, "error");
  }
};

const handleDeleteTag = async (id: number) => {
  try {
    await invoke("delete_tag", { id });
    await loadTags();
    showToast("标签已删除");
  } catch (e: any) {
    if (e.toString().includes("FOREIGN KEY")) {
      showToast("该标签正在被使用，无法删除", "error");
    } else {
      showToast("删除失败: " + e, "error");
    }
  }
};

const saveEvent = async () => {
  try {
    await invoke("save_event", { event: editingEvent.value });
    isEventModalOpen.value = false;
    await loadEvents();
    showToast("事件已保存");
  } catch (e) {
    showToast("保存失败: " + e, "error");
  }
};

const deleteEvent = async (id: number) => {
  try {
    await invoke("delete_event", { id });
    await loadEvents();
    showToast("事件已删除");
  } catch (e) {
    showToast("删除失败: " + e, "error");
  }
};

const timeToLogicalMinutes = (timeStr: string, isNextDay = false) => {
  const [h, m] = timeStr.split(":").map(Number);
  let t = h * 60 + m; if (isNextDay) t += 1440; return t - TIME_OFFSET_MINUTES;
};

const logicalMinutesToTime = (min: number) => {
  let t = (min + TIME_OFFSET_MINUTES) % 1440;
  const h = Math.floor(t / 60); const m = Math.floor(t % 60);
  return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
};

const logicalMinutesFromTime = (timeStr: string) => {
  const [h, m] = timeStr.split(":").map(Number);
  let total = h * 60 + m;
  if (h < 3) total += 1440;
  return total - TIME_OFFSET_MINUTES;
};

const startTimeInput = computed({
  get: () => logicalMinutesToTime(editingEvent.value.start_minute),
  set: (val) => { editingEvent.value.start_minute = logicalMinutesFromTime(val); }
});

const endTimeInput = computed({
  get: () => logicalMinutesToTime(editingEvent.value.end_minute),
  set: (val) => { editingEvent.value.end_minute = logicalMinutesFromTime(val); }
});

const updatePreview = async (img: TimelineItem | null) => {
  if (!img || (selectedImage.value?.path === img.path && previewSrc.value)) return;
  selectedImage.value = img;
  const b64 = await invoke("get_image_base64", { path: img.path });
  previewSrc.value = `data:image/jpeg;base64,${b64}`;
};

const handleTimelineMouseDown = (e: MouseEvent) => {
  if (!timelineRef.value) return;
  const rect = timelineRef.value.getBoundingClientRect();
  const min = Math.floor((e.clientY - rect.top + timelineRef.value.scrollTop) / timelineZoom.value);
  isDragging.value = true; dragStartMin.value = min; dragEndMin.value = min;
};

const handleTimelineMouseMove = (e: MouseEvent) => {
  if (!timelineRef.value) return;
  const rect = timelineRef.value.getBoundingClientRect();
  const min = Math.floor((e.clientY - rect.top + timelineRef.value.scrollTop) / timelineZoom.value);
  if (min >= 0 && min < 1440) {
    hoveredTime.value = logicalMinutesToTime(min);
    if (isDragging.value) dragEndMin.value = min;
    else {
      const closest = timelineImages.value.reduce((p, c) => {
        const pd = Math.abs(timeToLogicalMinutes(p.time, p.isNextDay) - min);
        const cd = Math.abs(timeToLogicalMinutes(c.time, c.isNextDay) - min);
        return cd < pd ? c : p;
      }, timelineImages.value[0]);
      if (closest) updatePreview(closest);
    }
  }
};

const handleTimelineMouseUp = () => {
  if (isDragging.value) {
    isDragging.value = false;
    const start = Math.min(dragStartMin.value!, dragEndMin.value!);
    const end = Math.max(dragStartMin.value!, dragEndMin.value!);
    if (end - start >= 1) {
      editingEvent.value = { id: 0, date: currentDate.value, start_minute: start, end_minute: end, main_tag_id: mainTags.value[0]?.id || 0, sub_tag_id: null, content: "" };
      isEventModalOpen.value = true;
    } else {
        const closest = timelineImages.value.reduce((p, c) => {
            const pd = Math.abs(timeToLogicalMinutes(p.time, p.isNextDay) - start);
            const cd = Math.abs(timeToLogicalMinutes(c.time, c.isNextDay) - start);
            return cd < pd ? c : p;
        }, timelineImages.value[0]);
        if (closest) { lockedImage.value = closest; updatePreview(closest); }
    }
  }
};

const handleTimelineMouseLeave = () => {
  hoveredTime.value = null;
  if (!isDragging.value && lockedImage.value) updatePreview(lockedImage.value);
};

const handleTimelineWheel = (e: WheelEvent) => {
  if (e.ctrlKey) {
    e.preventDefault(); if (!timelineRef.value) return;
    const rect = timelineRef.value.getBoundingClientRect();
    const my = e.clientY - rect.top; const cy = my + timelineRef.value.scrollTop;
    const oh = rulerHeight.value; const delta = e.deltaY > 0 ? -0.2 : 0.2;
    timelineZoom.value = Math.min(Math.max(0.5, timelineZoom.value + delta), 15);
    timelineRef.value.scrollTop = (cy / oh) * rulerHeight.value - my;
    updateSettings();
  }
};

const updateSettings = async () => {
  await store.set("savePath", savePath.value);
  await store.set("dbPath", dbPath.value);
  await store.set("mergeScreens", mergeScreens.value); 
  await store.set("retainDays", retainDays.value);
  await store.set("captureInterval", captureInterval.value); 
  await store.set("timelineZoom", timelineZoom.value);
  await store.save();
  await invoke("update_db_path", { path: dbPath.value });
  await invoke("update_interval", { seconds: captureInterval.value });
};

const togglePauseState = async () => { isPaused.value = await invoke("toggle_pause"); };
const loadTimeline = async (autoScrollToCurrentTime = false) => { 
  if (savePath.value) {
    timelineImages.value = await invoke("get_timeline", { date: currentDate.value, baseDir: savePath.value }); 
    await nextTick();
    if (autoScrollToCurrentTime && timelineRef.value) {
      const now = new Date();
      const currentMin = now.getHours() * 60 + now.getMinutes();
      const logicalMin = (currentMin < TIME_OFFSET_MINUTES ? currentMin + 1440 : currentMin) - TIME_OFFSET_MINUTES;
      const targetY = logicalMin * timelineZoom.value;
      const containerHeight = timelineRef.value.clientHeight;
      timelineRef.value.scrollTop = Math.max(0, targetY - containerHeight / 2);
    }
  }
};

const newTagName = ref(""); const newTagParent = ref<number | null>(null); const newTagColor = ref("#007AFF");
const resetTagForm = () => { newTagName.value = ""; newTagParent.value = null; newTagColor.value = "#007AFF"; };

// --- Custom Select State ---
const isTagSelectOpen = ref(false);
</script>

<template>
  <div class="h-screen w-screen flex flex-col overflow-hidden text-[#1D1D1F] bg-[#FBFBFD]">
    
    <div v-if="!isSetupComplete" class="flex-1 flex items-center justify-center p-10">
      <div class="bg-white p-12 rounded-[32px] shadow-2xl max-w-lg text-center border border-[#E5E5E7]">
        <Settings :size="40" class="text-[#007AFF] mx-auto mb-8" />
        <h1 class="text-3xl font-bold mb-4">初始化 Chrono Snap</h1>
        <div class="space-y-6 text-left mb-10">
          <div class="space-y-2">
            <label class="text-xs font-bold text-[#86868B]">截图保存目录</label>
            <div class="flex gap-2">
              <input type="text" readonly :value="savePath" placeholder="请选择目录..." class="flex-1 bg-[#F2F2F7] rounded-xl px-4 py-2.5 text-sm outline-none" />
              <button @click="selectFolder" class="bg-white border border-[#E5E5E7] p-2.5 rounded-xl hover:border-[#007AFF] transition-all"><FolderOpen :size="18" /></button>
            </div>
          </div>
          <div class="space-y-2">
            <label class="text-xs font-bold text-[#86868B]">SQLite 数据库文件</label>
            <div class="flex gap-2">
              <input type="text" readonly :value="dbPath" placeholder="请选择或创建 .db 文件..." class="flex-1 bg-[#F2F2F7] rounded-xl px-4 py-2.5 text-sm outline-none" />
              <div class="flex gap-1">
                <button @click="selectDBFile" class="bg-white border border-[#E5E5E7] p-2.5 rounded-xl hover:border-[#007AFF]"><FolderOpen :size="18" /></button>
                <button @click="createDBFile" class="bg-white border border-[#E5E5E7] p-2.5 rounded-xl hover:border-[#007AFF]"><Plus :size="18" /></button>
              </div>
            </div>
          </div>
        </div>
        <button @click="completeSetup" :disabled="!savePath || !dbPath" class="bg-[#007AFF] text-white px-8 py-4 rounded-2xl font-semibold w-full disabled:opacity-50">开始使用</button>
      </div>
    </div>

    <div v-else class="flex flex-1 overflow-hidden">
      <div class="w-80 bg-[#F8FAFD] border-r border-[#E5E5E7] flex flex-col select-none relative">
        <div class="p-6 bg-[#F8FAFD]/80 backdrop-blur-md sticky top-0 z-50 border-b border-[#E5E5E7]/50">
          <div class="flex items-center justify-between mb-4"><h2 class="text-lg font-bold">历史活动</h2><button @click="loadTimeline(true); loadEvents()" class="p-2 hover:bg-white rounded-xl text-[#86868B]"><RefreshCw :size="18" /></button></div>
          <div ref="calendarRef" class="relative group">
             <button @click="isCalendarOpen = !isCalendarOpen" class="w-full bg-white border border-[#E5E5E7] rounded-xl pl-11 pr-4 py-2.5 text-sm font-bold text-left flex items-center hover:bg-[#F2F2F7] transition-all">
                <Calendar :size="16" class="absolute left-4 text-[#86868B]" />
                {{ currentDate }}
             </button>
             <div v-if="isCalendarOpen" class="absolute top-full left-0 right-0 mt-2 bg-white rounded-[24px] shadow-2xl border border-[#E5E5E7] z-[100] p-5 animate-in fade-in zoom-in-95 duration-200">
                <div class="flex items-center justify-between mb-4">
                  <button @click="calendarMonth = new Date(calendarMonth.getFullYear(), calendarMonth.getMonth()-1, 1)" class="p-2 hover:bg-[#F2F2F7] rounded-xl"><ChevronLeft :size="18"/></button>
                  <span class="text-sm font-black">{{ calendarMonth.getFullYear() }}年 {{ calendarMonth.getMonth()+1 }}月</span>
                  <button @click="calendarMonth = new Date(calendarMonth.getFullYear(), calendarMonth.getMonth()+1, 1)" class="p-2 hover:bg-[#F2F2F7] rounded-xl"><ChevronRight :size="18"/></button>
                </div>
                <div class="grid grid-cols-7 gap-1 text-center mb-2"><div v-for="d in ['一','二','三','四','五','六','日']" :key="d" class="text-[10px] font-bold text-[#86868B]">{{d}}</div></div>
                <div class="grid grid-cols-7 gap-1">
                  <div v-for="(date, i) in calendarDays" :key="i" class="aspect-square flex items-center justify-center">
                    <button v-if="date" @click="selectCalendarDate(date)" class="w-8 h-8 rounded-full text-xs font-medium transition-all" :class="date.toLocaleDateString('sv') === currentDate ? 'bg-[#007AFF] text-white font-bold' : 'hover:bg-[#F2F2F7] text-main'">{{ date.getDate() }}</button>
                  </div>
                </div>
             </div>
          </div>
        </div>

        <div ref="timelineRef" class="flex-1 overflow-y-auto no-scrollbar hover:cursor-crosshair relative" @mousedown="handleTimelineMouseDown" @mousemove="handleTimelineMouseMove" @mouseup="handleTimelineMouseUp" @mouseleave="handleTimelineMouseLeave" @wheel="handleTimelineWheel">
          <div :style="{ height: rulerHeight + 'px' }" class="relative ml-14 mr-4">
            <div v-for="h in 24" :key="h" class="absolute left-0 w-full border-t border-[#E5E5E7]/60" :style="{ top: (h-1) * 60 * timelineZoom + 'px' }">
              <span class="absolute -left-11 -top-2.5 text-[10px] font-bold text-[#86868B]">{{ String((h - 1 + 3) % 24).padStart(2, '0') }}:00</span>
            </div>
            <div v-for="ev in dayEvents" :key="ev.id" class="absolute left-0 w-[45%] opacity-80 border-l-4" :style="{ top: ev.start_minute * timelineZoom + 'px', height: (ev.end_minute - ev.start_minute) * timelineZoom + 'px', backgroundColor: getTagColor(ev.main_tag_id) + '22', borderColor: getTagColor(ev.main_tag_id) }" @click.stop="editingEvent = { ...ev }; isEventModalOpen = true"></div>
            <div v-for="img in timelineImages" :key="img.path" class="absolute left-[50%] right-2 h-1 bg-[#007AFF]/20 rounded-full" :class="[selectedImage?.path === img.path ? 'bg-[#007AFF]/60 h-2 z-10' : '', lockedImage?.path === img.path ? 'bg-[#007AFF] h-2.5 ring-2 ring-[#007AFF]/20 z-20' : '']" :style="{ top: timeToLogicalMinutes(img.time, img.isNextDay) * timelineZoom + 'px' }"></div>
            <div v-if="dragStartMin !== null && dragEndMin !== null" class="absolute left-0 w-full bg-[#007AFF]/10 border-y-2 border-[#007AFF] pointer-events-none z-30" :style="{ top: Math.min(dragStartMin, dragEndMin) * timelineZoom + 'px', height: Math.abs(dragEndMin - dragStartMin) * timelineZoom + 'px' }"></div>
            <div v-if="hoveredTime" class="absolute left-0 right-0 border-t-2 border-[#007AFF] z-40 pointer-events-none" :style="{ top: timeToLogicalMinutes(hoveredTime, hoveredTime < '03:00') * timelineZoom + 'px' }"><div class="absolute -left-12 -top-3 bg-[#007AFF] text-white text-[9px] px-1 py-0.5 rounded font-bold">{{ hoveredTime }}</div></div>
          </div>
        </div>

        <div class="p-4 border-t border-[#E5E5E7] bg-white/50 flex justify-around">
          <button @click="togglePauseState" class="p-3 rounded-2xl" :class="isPaused ? 'text-[#FF3B30]' : 'text-[#86868B]'"><Play v-if="isPaused" :size="22" /><Pause v-else :size="22" /></button>
          <button @click="isTagManagerOpen = true" class="p-3 rounded-2xl text-[#86868B]"><TagIcon :size="22" /></button>
          <button @click="isSettingsOpen = true" class="p-3 rounded-2xl text-[#86868B]"><Settings :size="22" /></button>
        </div>
      </div>

      <div class="flex-1 bg-[#FBFBFD] flex flex-col relative overflow-hidden">
        <div class="p-6 flex items-center justify-between border-b bg-white/80 backdrop-blur-md z-10">
          <div v-if="selectedImage" class="flex items-center gap-3"><span class="text-lg font-bold">{{ selectedImage.time }}</span><span class="text-xs font-bold px-2 py-0.5" :class="lockedImage?.path === selectedImage.path ? 'bg-[#007AFF] text-white' : 'bg-[#F2F2F7] text-[#86868B]'">{{ lockedImage?.path === selectedImage.path ? '已定格' : '预览中' }}</span></div>
          <div v-else class="text-[#86868B] font-medium">未选中活动</div>
          <button v-if="selectedImage" @click="isFullscreen = true" class="p-2.5 text-[#86868B]"><Maximize2 :size="20" /></button>
        </div>
        <div class="flex-1 flex items-center justify-center p-12 bg-[#F2F2F7]/30">
          <img v-if="previewSrc" :src="previewSrc" class="max-w-full max-h-full object-contain rounded-3xl shadow-2xl border" />
          <div v-else class="text-[#86868B] text-center"><Maximize2 :size="48" class="mx-auto mb-4 opacity-20" /><p>在时间轴上滑动或拖拽以记录</p></div>
        </div>
      </div>
    </div>

    <!-- Modals -->
    <div v-if="isEventModalOpen" class="fixed inset-0 z-[110] bg-black/40 backdrop-blur-sm flex items-center justify-center p-6" @click.self="isEventModalOpen = false">
      <div class="bg-white rounded-[40px] shadow-2xl w-full max-w-lg overflow-hidden flex flex-col">
        <div class="p-8 border-b flex justify-between items-center"><h2 class="text-2xl font-bold">{{ editingEvent.id ? '编辑事件' : '新增记录' }}</h2><button @click="isEventModalOpen = false; isStartTimeOpen = false; isEndTimeOpen = false"><X :size="24" /></button></div>
        <div class="p-10 space-y-8">
          <div class="flex gap-4">
            <!-- Start Time Custom Picker -->
            <div ref="startTimePickerRef" class="flex-1 space-y-1 relative">
              <label class="text-[10px] font-bold text-[#86868B]">开始时间</label>
              <button @click="openStartTimePicker" 
                class="w-full h-12 bg-[#F2F2F7] rounded-xl px-4 flex items-center justify-center gap-2 hover:bg-[#E5E5E7] transition-all border border-transparent focus:border-[#007AFF]/30">
                <!-- <Clock :size="14" class="text-[#86868B] block" /> -->
                <span class="text-sm font-bold leading-none">{{ startTimeInput }}</span>
              </button>
              <div v-if="isStartTimeOpen" class="absolute top-full left-0 right-0 mt-2 bg-white rounded-3xl shadow-2xl border border-[#E5E5E7] z-[120] p-4 animate-in fade-in slide-in-from-top-2 flex gap-4 h-64">
                 <div class="flex-1 overflow-y-auto no-scrollbar flex flex-col gap-1">
                    <div class="text-[9px] font-bold text-sec mb-2 sticky top-0 bg-white py-1 text-center border-b border-[#E5E5E7]/30">时</div>
                    <button v-for="h in 24" :key="h" 
                      @click="editingEvent.start_minute = logicalMinutesFromTime(`${String((h-1+3)%24).padStart(2,'0')}:${String(editingEvent.start_minute % 60).padStart(2,'0')}`)"
                      class="py-2 text-[11px] rounded-lg transition-colors w-full text-center flex items-center justify-center"
                      :class="Math.floor((editingEvent.start_minute + TIME_OFFSET_MINUTES) / 60) % 24 === (h-1+3)%24 ? 'bg-[#007AFF] text-white font-bold' : 'hover:bg-[#F2F2F7] text-main'"
                    >{{ String((h-1+3)%24).padStart(2,'0') }}</button>
                 </div>
                 <div class="w-px bg-[#E5E5E7] my-2"></div>
                 <div class="flex-1 overflow-y-auto no-scrollbar flex flex-col gap-1">
                    <div class="text-[9px] font-bold text-sec mb-2 sticky top-0 bg-white py-1 text-center border-b border-[#E5E5E7]/30">分</div>
                    <button v-for="m in 60" :key="m" 
                      @click="editingEvent.start_minute = Math.floor(editingEvent.start_minute / 60) * 60 + (m-1)"
                      class="py-2 text-[11px] rounded-lg transition-colors w-full text-center flex items-center justify-center"
                      :class="editingEvent.start_minute % 60 === (m-1) ? 'bg-[#007AFF] text-white font-bold' : 'hover:bg-[#F2F2F7] text-main'"
                    >{{ String(m-1).padStart(2,'0') }}</button>
                 </div>
              </div>
            </div>
            <!-- End Time Custom Picker -->
            <div ref="endTimePickerRef" class="flex-1 space-y-1 relative">
              <label class="text-[10px] font-bold text-[#86868B]">结束时间</label>
              <button @click="openEndTimePicker" 
                class="w-full h-12 bg-[#F2F2F7] rounded-xl px-4 flex items-center justify-center gap-2 hover:bg-[#E5E5E7] transition-all border border-transparent focus:border-[#007AFF]/30">
                <!-- <Clock :size="14" class="text-[#86868B] block" /> -->
                <span class="text-sm font-bold leading-none">{{ endTimeInput }}</span>
              </button>
              <div v-if="isEndTimeOpen" class="absolute top-full left-0 right-0 mt-2 bg-white rounded-3xl shadow-2xl border border-[#E5E5E7] z-[120] p-4 animate-in fade-in slide-in-from-top-2 flex gap-4 h-64">
                 <div class="flex-1 overflow-y-auto no-scrollbar flex flex-col gap-1 text-center">
                    <div class="text-[9px] font-bold text-sec mb-2 sticky top-0 bg-white py-1">时</div>
                    <button v-for="h in 24" :key="h" 
                      @click="editingEvent.end_minute = logicalMinutesFromTime(`${String((h-1+3)%24).padStart(2,'0')}:${String(editingEvent.end_minute % 60).padStart(2,'0')}`)"
                      class="py-2 text-xs rounded-lg transition-colors w-full text-center"
                      :class="Math.floor((editingEvent.end_minute + TIME_OFFSET_MINUTES) / 60) % 24 === (h-1+3)%24 ? 'bg-[#007AFF] text-white font-bold' : 'hover:bg-[#F2F2F7] text-main'"
                    >{{ String((h-1+3)%24).padStart(2,'0') }}</button>
                 </div>
                 <div class="w-px bg-[#E5E5E7] my-2"></div>
                 <div class="flex-1 overflow-y-auto no-scrollbar flex flex-col gap-1 text-center">
                    <div class="text-[9px] font-bold text-sec mb-2 sticky top-0 bg-white py-1">分</div>
                    <button v-for="m in 60" :key="m" 
                      @click="editingEvent.end_minute = Math.floor(editingEvent.end_minute / 60) * 60 + (m-1)"
                      class="py-2 text-xs rounded-lg transition-colors w-full text-center"
                      :class="editingEvent.end_minute % 60 === (m-1) ? 'bg-[#007AFF] text-white font-bold' : 'hover:bg-[#F2F2F7] text-main'"
                    >{{ String(m-1).padStart(2,'0') }}</button>
                 </div>
              </div>
            </div>
          </div>
          <div class="space-y-4">
            <div class="space-y-2"><label class="text-[10px] font-bold text-[#86868B]">主标签</label>
              <div class="grid grid-cols-4 gap-2"><button v-for="tag in mainTags" :key="tag.id" @click="editingEvent.main_tag_id = tag.id; editingEvent.sub_tag_id = null" class="px-2 py-2 rounded-xl text-[10px] font-bold border-2" :style="{ backgroundColor: editingEvent.main_tag_id === tag.id ? tag.color : 'transparent', borderColor: tag.color, color: editingEvent.main_tag_id === tag.id ? 'white' : tag.color }">{{ tag.name }}</button></div>
            </div>
            <div v-if="editingEvent.main_tag_id && getSubTags(editingEvent.main_tag_id).length" class="space-y-2"><label class="text-[10px] font-bold text-[#86868B]">副标签</label>
              <div class="flex flex-wrap gap-2"><button v-for="sub in getSubTags(editingEvent.main_tag_id)" :key="sub.id" @click="editingEvent.sub_tag_id = sub.id" class="px-3 py-1.5 rounded-lg text-[10px] font-medium" :class="editingEvent.sub_tag_id === sub.id ? 'bg-[#1D1D1F] text-white' : 'bg-[#F2F2F7] text-[#86868B]'">{{ sub.name }}</button></div>
            </div>
            <textarea v-model="editingEvent.content" placeholder="记录具体内容..." class="w-full bg-[#F2F2F7] rounded-2xl p-4 text-sm min-h-[100px] outline-none border border-transparent focus:bg-white focus:border-[#E5E5E7] transition-all"></textarea>
          </div>
          <div class="flex gap-4 pt-4">
             <button v-if="editingEvent.id" @click="deleteEvent(editingEvent.id); isEventModalOpen = false" class="text-[#FF3B30] font-bold px-4 py-2 flex items-center gap-2"><Trash2 :size="18" /> 删除</button>
             <button @click="saveEvent" class="flex-1 bg-[#007AFF] text-white py-4 rounded-2xl font-bold shadow-lg shadow-[#007AFF]/20">保存记录</button>
          </div>
        </div>
      </div>
    </div>

    <div v-if="isTagManagerOpen" class="fixed inset-0 z-[100] bg-black/40 backdrop-blur-sm flex items-center justify-center p-6" @click.self="isTagManagerOpen = false">
      <div class="bg-white rounded-[40px] shadow-2xl w-full max-w-2xl h-[80vh] overflow-hidden flex flex-col animate-in fade-in zoom-in duration-200">
        <div class="p-8 border-b flex justify-between items-center"><h2 class="text-2xl font-bold">标签管理</h2><button @click="isTagManagerOpen = false"><X :size="24" /></button></div>
        <div class="flex-1 overflow-y-auto p-10 flex gap-10">
          <div class="flex-1 space-y-6">
            <div v-for="mt in mainTags" :key="mt.id" class="space-y-2">
              <div class="flex items-center justify-between group p-2 hover:bg-[#F2F2F7] rounded-xl"><div class="flex items-center gap-3"><div class="w-4 h-4 rounded-full" :style="{ backgroundColor: mt.color }"></div><span class="font-bold">{{ mt.name }}</span></div><button @click="handleDeleteTag(mt.id)" class="text-[#FF3B30] opacity-0 group-hover:opacity-100"><Trash2 :size="16" /></button></div>
              <div class="ml-7 space-y-1"><div v-for="st in getSubTags(mt.id)" :key="st.id" class="flex items-center justify-between group p-1.5 hover:bg-[#F2F2F7] rounded-lg"><span class="text-sm">{{ st.name }}</span><button @click="handleDeleteTag(st.id)" class="text-[#FF3B30] opacity-0 group-hover:opacity-100"><Trash2 :size="14" /></button></div></div>
            </div>
          </div>
          <div class="w-64 bg-[#F2F2F7] p-6 rounded-3xl space-y-4">
            <h3 class="font-bold text-xs text-[#86868B] uppercase">添加标签</h3>
            <div class="space-y-1">
              <label class="text-[10px] font-bold text-[#86868B] ml-1">标签名称</label>
              <input v-model="newTagName" placeholder="输入名称..." class="w-full bg-white rounded-xl px-4 py-2.5 text-sm outline-none border border-transparent focus:border-[#007AFF] transition-all" />
            </div>
            <div ref="tagSelectRef" class="space-y-1 relative">
              <label class="text-[10px] font-bold text-[#86868B] ml-1">父级标签</label>
              <button @click="isTagSelectOpen = !isTagSelectOpen" class="w-full bg-white rounded-xl px-4 py-2.5 text-sm text-left flex justify-between items-center border border-transparent focus:border-[#007AFF] transition-all">
                <span>{{ getTagName(newTagParent) }}</span>
                <ChevronDown :size="14" class="text-[#86868B] transition-transform" :class="{ 'rotate-180': isTagSelectOpen }" />
              </button>
              <div v-if="isTagSelectOpen" class="absolute top-full left-0 right-0 mt-2 bg-white rounded-2xl shadow-xl border border-[#E5E5E7] z-[60] overflow-hidden py-2 animate-in fade-in zoom-in-95 duration-200">
                <div @click="newTagParent = null; isTagSelectOpen = false" class="px-4 py-2 text-sm hover:bg-[#F2F2F7] cursor-pointer" :class="{ 'text-[#007AFF] font-bold': newTagParent === null }">-- 无 --</div>
                <div v-for="t in mainTags" :key="t.id" @click="newTagParent = t.id; isTagSelectOpen = false" class="px-4 py-2 text-sm hover:bg-[#F2F2F7] cursor-pointer" :class="{ 'text-[#007AFF] font-bold': newTagParent === t.id }">{{ t.name }}</div>
              </div>
            </div>
            <div v-if="newTagParent === null" class="space-y-1">
              <label class="text-[10px] font-bold text-[#86868B] ml-1">主题颜色</label>
              <div class="flex flex-wrap gap-2"><button v-for="c in ['#007AFF', '#34C759', '#FF9500', '#FF3B30', '#AF52DE', '#5856D6']" :key="c" @click="newTagColor = c" class="w-5 h-5 rounded-full border-2 transition-all" :style="{ backgroundColor: c, borderColor: newTagColor === c ? '#1D1D1F' : 'transparent' }"></button></div>
            </div>
            <button @click="handleAddTag(newTagName, newTagParent, newTagColor); resetTagForm()" :disabled="!newTagName" class="w-full bg-[#007AFF] text-white py-3 rounded-xl font-bold shadow-lg shadow-[#007AFF]/20 active:scale-95 transition-all">创建</button>
          </div>
        </div>
      </div>
    </div>

    <div v-if="isSettingsOpen" class="fixed inset-0 z-[100] bg-black/40 backdrop-blur-sm flex items-center justify-center p-6" @click.self="isSettingsOpen = false">
      <div class="bg-white rounded-[40px] shadow-2xl w-full max-w-md overflow-hidden flex flex-col">
        <div class="p-8 border-b flex justify-between items-center"><h2 class="text-2xl font-bold">设置</h2><button @click="isSettingsOpen = false"><X :size="24" /></button></div>
        <div class="p-10 space-y-8">
          <div class="space-y-3"><label class="text-xs font-bold text-[#86868B]">截图保存位置</label><div class="flex gap-2"><input type="text" readonly :value="savePath" class="flex-1 bg-[#F2F2F7] rounded-xl px-4 py-2 text-sm outline-none" /><button @click="selectFolder(); updateSettings()" class="bg-white border p-2 rounded-xl hover:border-[#007AFF] transition-all"><FolderOpen :size="18" /></button></div></div>
          <div class="space-y-3"><label class="text-xs font-bold text-[#86868B]">SQLite 数据库文件</label><div class="flex gap-2"><input type="text" readonly :value="dbPath" class="flex-1 bg-[#F2F2F7] rounded-xl px-4 py-2 text-sm outline-none" /><div class="flex gap-1"><button @click="selectDBFile().then(updateSettings)" title="打开现有" class="bg-white border p-2 rounded-xl hover:border-[#007AFF] transition-all"><FolderOpen :size="18" /></button><button @click="createDBFile().then(updateSettings)" title="新建" class="bg-white border p-2 rounded-xl hover:border-[#007AFF] transition-all"><Plus :size="18" /></button></div></div></div>
          <div class="flex items-center justify-between p-4 bg-[#F2F2F7] rounded-3xl"><div class="space-y-0.5"><div class="font-bold">多屏合并</div><div class="text-[10px] text-[#86868B]">拼接所有屏幕</div></div><button @click="mergeScreens = !mergeScreens; updateSettings()" class="w-12 h-6 rounded-full relative transition-all" :class="mergeScreens ? 'bg-[#34C759]' : 'bg-[#E5E5E7]'"><div class="absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-all" :style="{ transform: mergeScreens ? 'translateX(24px)' : 'translateX(0)' }"></div></button></div>
          <div class="space-y-2"><div class="flex justify-between"><label class="text-xs font-bold">截图间隔</label><span class="text-xs font-bold text-[#007AFF]">{{ captureInterval }}s</span></div><input type="range" v-model.number="captureInterval" min="10" max="600" step="10" @change="updateSettings" class="w-full h-1 bg-[#E5E5E7] accent-[#007AFF]" /></div>
          <div class="space-y-2"><div class="flex justify-between"><label class="text-xs font-bold">清理策略</label><span class="text-xs font-bold text-[#007AFF]">{{ retainDays }}天</span></div><input type="range" v-model.number="retainDays" min="1" max="180" @change="updateSettings" class="w-full h-1 bg-[#E5E5E7] accent-[#007AFF]" /></div>
        </div>
      </div>
    </div>

    <div v-if="isFullscreen && previewSrc" class="fixed inset-0 z-[200] bg-black/95 flex items-center justify-center p-6 backdrop-blur-xl"><button @click="isFullscreen = false" class="absolute top-10 right-10 w-12 h-12 bg-white/10 rounded-full flex items-center justify-center"><X :size="32" class="text-white" /></button><img :src="previewSrc" class="max-w-full max-h-full object-contain shadow-2xl" /></div>

    <div v-if="toast.visible" class="fixed bottom-10 left-1/2 -translate-x-1/2 z-[300] animate-in fade-in slide-in-from-bottom-4 duration-300">
      <div class="px-6 py-3 rounded-2xl shadow-2xl backdrop-blur-md flex items-center gap-3 border border-white/20" :class="toast.type === 'error' ? 'bg-[#FF3B30] text-white' : 'bg-white/90 text-[#1D1D1F]'">
        <div v-if="toast.type === 'error'" class="w-5 h-5 rounded-full border-2 border-white flex items-center justify-center text-[12px] font-black">!</div>
        <div v-else class="w-5 h-5 rounded-full bg-[#34C759] flex items-center justify-center text-white text-[10px]">✓</div>
        <span class="text-sm font-bold">{{ toast.message }}</span>
      </div>
    </div>
  </div>
</template>

<style>
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
</style>
