<template>
  <div class="planning-layout">
    <!-- Sub tabs -->
    <div class="sub-tabs">
      <button class="sub-tab" :class="{ active: subTab === 'schedule' }" @click="subTab = 'schedule'">日程</button>
      <button class="sub-tab" :class="{ active: subTab === 'template' }" @click="subTab = 'template'">模板</button>
      <button class="sub-tab" :class="{ active: subTab === 'review' }" @click="subTab = 'review'">回顾</button>
    </div>

    <!-- 日程 -->
    <div v-if="subTab === 'schedule'" class="schedule-section">
      <div class="schedule-flex">
        <!-- 模块池 -->
        <div class="module-pool">
          <div class="pool-card">
            <h3>活动模块</h3>
            <div
              v-for="m in store.scheduleModules"
              :key="m.id"
              class="module-item"
              :style="{ background: m.color + '20', color: m.color }"
              draggable="true"
              @dragstart="dragModule = m"
            >
              <span class="emoji">{{ m.emoji }}</span>
              <span>{{ m.name }}</span>
              <button class="remove-btn" @click="store.deleteScheduleModule(m.id)">✕</button>
            </div>
            <div class="add-row">
              <input v-model="newModuleName" placeholder="添加新活动…" @keydown.enter.prevent="addModule">
              <button @click="addModule">+</button>
            </div>
            <div class="color-picker">
              <span
                v-for="c in colors"
                :key="c"
                class="color-dot"
                :class="{ active: newModuleColor === c }"
                :style="{ background: c }"
                @click="newModuleColor = c"
              ></span>
            </div>
          </div>
        </div>

        <!-- 时间线 -->
        <div class="timeline">
          <div class="date-nav">
            <button @click="changeDate(-1)">‹</button>
            <span class="date-label-main">{{ formatDateLabel(currentDate) }}</span>
            <button @click="changeDate(1)">›</button>
            <button class="btn btn-light" style="margin-left: auto;" @click="store.clearScheduleDay(dateKey(currentDate))">清空</button>
          </div>
          <div
            v-for="slot in timeSlots"
            :key="slot"
            class="time-slot"
          >
            <div class="time-label">{{ slot }}</div>
            <div
              class="slot-drop"
              :class="{ 'drag-over': dragOverSlot === slot }"
              @dragover.prevent="dragOverSlot = slot"
              @dragleave="dragOverSlot = null"
              @drop="dropModule(slot)"
            >
              <div
                v-for="item in getSlotItems(slot)"
                :key="item.module_id"
                class="placed-item"
                :style="{ background: getModuleColor(item.module_id) + '30', color: getModuleColor(item.module_id) }"
              >
                {{ getModuleEmoji(item.module_id) }} {{ getModuleName(item.module_id) }}
                <button class="remove-placed" @click="store.removeScheduleSlot(dateKey(currentDate), slot, item.module_id)">✕</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 模板 -->
    <div v-if="subTab === 'template'" class="template-section">
      <div class="day-tabs">
        <button
          v-for="(name, idx) in dayNames"
          :key="idx"
          class="day-btn"
          :class="{ active: selectedDay === idx }"
          @click="selectedDay = idx"
        >{{ name }}</button>
      </div>
      <div class="template-hint">
        模板内容在 weekly_template 数据中编辑
      </div>
    </div>

    <!-- 回顾 -->
    <div v-if="subTab === 'review'" class="review-section">
      <div class="section-header">
        <h3>本周回顾</h3>
      </div>
      <div class="review-form">
        <label>本周做得好的</label>
        <textarea v-model="reviewWins" rows="3" placeholder="列举本周成就…"></textarea>
        <label>需要改进的</label>
        <textarea v-model="reviewIssues" rows="3" placeholder="遇到的问题…"></textarea>
        <label>下周计划</label>
        <textarea v-model="reviewPlan" rows="3" placeholder="下周打算…"></textarea>
        <div class="edit-actions">
          <button class="btn btn-accent" @click="saveReview">保存回顾</button>
        </div>
      </div>

      <h4 style="margin: 20px 0 10px; color: #888; font-size: 14px; cursor: pointer;" @click="showHistory = !showHistory">
        历史回顾 {{ showHistory ? '⌄' : '›' }}
      </h4>
      <div v-if="showHistory">
        <div v-for="r in store.reviews" :key="r.week" class="review-card">
          <strong>{{ r.week }}</strong>
          <pre class="review-content">{{ r.data }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

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

const store = usePlannerStore()
const subTab = ref('schedule')
const currentDate = ref(new Date())
const dragModule = ref(null)
const dragOverSlot = ref(null)
const newModuleName = ref('')
const newModuleColor = ref('#667eea')
const selectedDay = ref(1)
const showHistory = ref(false)
const reviewWins = ref('')
const reviewIssues = ref('')
const reviewPlan = ref('')

const colors = ['#667eea', '#764ba2', '#f59e0b', '#10b981', '#ef4444', '#3b82f6', '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16']
const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const timeSlots = computed(() => {
  const slots = []
  for (let h = 6; h <= 23; h++) {
    slots.push(`${String(h).padStart(2, '0')}:00`)
  }
  return slots
})

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

function dateKey(d) { return d.toISOString().slice(0, 10) }

function formatDateLabel(d) {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return `${d.getMonth() + 1}月${d.getDate()}日 ${days[d.getDay()]}`
}

function changeDate(delta) {
  const d = new Date(currentDate.value)
  d.setDate(d.getDate() + delta)
  currentDate.value = d
}

function getSlotItems(slot) {
  return store.scheduleSlots.filter(s => s.date === dateKey(currentDate.value) && s.time_slot === slot)
}

function getModuleColor(id) {
  return store.scheduleModules.find(m => m.id === id)?.color || '#667eea'
}
function getModuleEmoji(id) {
  return store.scheduleModules.find(m => m.id === id)?.emoji || '📌'
}
function getModuleName(id) {
  return store.scheduleModules.find(m => m.id === id)?.name || ''
}

async function dropModule(slot) {
  dragOverSlot.value = null
  if (!dragModule.value) return
  await store.addScheduleSlot({
    date: dateKey(currentDate.value),
    time_slot: slot,
    module_id: dragModule.value.id,
  })
  dragModule.value = null
}

async function addModule() {
  if (!newModuleName.value.trim()) return
  await store.addScheduleModule({
    id: uid(),
    name: newModuleName.value.trim(),
    emoji: '📌',
    color: newModuleColor.value,
    sort_order: store.scheduleModules.length,
  })
  newModuleName.value = ''
}

function getWeekKey() {
  const d = new Date()
  const year = d.getFullYear()
  const jan1 = new Date(year, 0, 1)
  const week = Math.ceil(((d - jan1) / 86400000 + jan1.getDay() + 1) / 7)
  return `${year}-W${String(week).padStart(2, '0')}`
}

async function saveReview() {
  const data = JSON.stringify({
    wins: reviewWins.value,
    issues: reviewIssues.value,
    plan: reviewPlan.value,
  })
  await store.saveReview({ week: getWeekKey(), data })
}
</script>
