<template>
  <div class="docs-layout">
    <div class="section-header">
      <div>
        <h2 style="font-size: 18px; font-weight: 600; color: #444;">个人文档</h2>
        <p style="font-size: 12px; color: #aaa; margin-top: 2px;">随手记会自动识别内容，归档到对应文档</p>
      </div>
      <button class="btn btn-accent" @click="openAdd">+ 新建文档</button>
    </div>

    <div class="doc-grid">
      <div v-for="doc in store.docs" :key="doc.id" class="doc-card" @click="openDoc(doc)">
        <div class="doc-icon">{{ doc.icon }}</div>
        <div class="doc-name">{{ doc.name }}</div>
        <div class="doc-count">{{ (doc.entries || []).length }} 条</div>
      </div>
    </div>

    <!-- Doc detail overlay -->
    <div v-if="activeDoc" class="overlay open" @click.self="activeDoc = null">
      <div class="panel" style="width: 500px; max-height: 80vh; overflow-y: auto;">
        <div class="section-header">
          <h3>{{ activeDoc.icon }} {{ activeDoc.name }}</h3>
          <div>
            <button class="btn btn-close" @click="editDoc(activeDoc)">编辑</button>
            <button class="btn btn-close" style="color: #ef4444;" @click="removeDoc(activeDoc.id)">删除</button>
            <button class="btn btn-close" @click="activeDoc = null">关闭</button>
          </div>
        </div>
        <div v-for="entry in (activeDoc.entries || [])" :key="entry.id" class="doc-entry">
          <div class="doc-entry-text">{{ entry.text }}</div>
          <div class="doc-entry-meta">
            <span>{{ formatTime(entry.created_at) }}</span>
            <button class="remove-btn" @click="removeEntry(entry)">✕</button>
          </div>
        </div>
        <div v-if="(activeDoc.entries || []).length === 0" class="empty-hint">暂无条目</div>
      </div>
    </div>

    <!-- Add/Edit form -->
    <div v-if="showForm" class="overlay open" @click.self="showForm = false">
      <div class="panel edit-panel" style="width: 360px;">
        <h3>{{ editingDoc ? '编辑文档' : '新建文档' }}</h3>
        <label>文档名称</label>
        <input v-model="formName" placeholder="如：读书记录">
        <label>图标</label>
        <div class="emoji-row">
          <span
            v-for="e in emojis"
            :key="e"
            class="emoji-pick"
            :class="{ active: formIcon === e }"
            @click="formIcon = e"
          >{{ e }}</span>
        </div>
        <label>关键词</label>
        <input v-model="formKeywords" placeholder="逗号分隔，如：读完,看完">
        <label>提取规则</label>
        <select v-model="formRule">
          <option value="none">无 - 保存原文</option>
          <option value="sleep">睡眠时间</option>
          <option value="book">书名</option>
        </select>
        <div class="edit-actions">
          <button class="btn btn-close" @click="showForm = false">取消</button>
          <button class="btn btn-accent" @click="saveForm">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { usePlannerStore } from '../stores/planner'

const store = usePlannerStore()
const activeDoc = ref(null)
const showForm = ref(false)
const editingDoc = ref(null)
const formName = ref('')
const formIcon = ref('📄')
const formKeywords = ref('')
const formRule = ref('none')

const emojis = ['📄','📖','🌙','💊','💪','🎵','💡','✅','⏰','📌','🎯','📚']

function uid() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 7) }

function openDoc(doc) {
  activeDoc.value = doc
}

function openAdd() {
  editingDoc.value = null
  formName.value = ''
  formIcon.value = '📄'
  formKeywords.value = ''
  formRule.value = 'none'
  showForm.value = true
}

function editDoc(doc) {
  editingDoc.value = doc
  formName.value = doc.name
  formIcon.value = doc.icon
  formKeywords.value = doc.keywords
  formRule.value = doc.extract_rule
  showForm.value = true
}

async function saveForm() {
  if (!formName.value.trim()) return
  const data = {
    id: editingDoc.value ? editingDoc.value.id : uid(),
    name: formName.value.trim(),
    icon: formIcon.value,
    keywords: formKeywords.value,
    extract_rule: formRule.value,
  }
  if (editingDoc.value) {
    await store.updateDoc(data)
  } else {
    await store.addDoc(data)
  }
  showForm.value = false
}

async function removeDoc(id) {
  await store.deleteDoc(id)
  activeDoc.value = null
}

async function removeEntry(entry) {
  await store.deleteDocEntry(entry.id, activeDoc.value.id)
}

function formatTime(ts) {
  if (!ts) return ''
  const d = new Date(ts)
  return `${d.getMonth() + 1}/${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`
}
</script>
