<template>
  <div class="history-panel">
    <div class="history-header">
      <h3>📋 历史行程</h3>
      <button class="close-btn" @click="$emit('close')">✕</button>
    </div>

    <div v-if="loading" class="history-loading">加载中...</div>
    
    <div v-else-if="plans.length === 0" class="history-empty">
      <p>暂无历史行程</p>
      <p class="hint">完成行程规划后会自动保存</p>
    </div>

    <div v-else class="history-list">
      <div v-for="plan in plans" :key="plan.id" class="history-item" @click="loadPlan(plan)">
        <div class="history-item-header">
          <div class="history-name">{{ plan.name }}</div>
          <button class="delete-btn" @click.stop="deletePlan(plan.id)" title="删除">🗑️</button>
        </div>
        <div v-if="plan.description" class="history-desc">{{ plan.description }}</div>
        <div class="history-meta">
          <span>{{ formatDate(plan.created_at) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useItineraryStore } from '../stores/itinerary'
import { trackPlanLoad } from '../services/statsService'

const emit = defineEmits(['close', 'load'])

const authStore = useAuthStore()
const itineraryStore = useItineraryStore()

const plans = ref([])
const loading = ref(false)

onMounted(async () => {
  await loadPlans()
})

async function loadPlans() {
  loading.value = true
  try {
    const API_BASE = 'http://localhost:3001/api'
    let url, headers = {}
    
    if (authStore.isAuthenticated) {
      url = `${API_BASE}/plans`
      headers = { 'Authorization': `Bearer ${authStore.token}` }
    } else if (authStore.guestId) {
      url = `${API_BASE}/plans/guest/${authStore.guestId}`
    } else {
      plans.value = []
      return
    }
    
    const res = await fetch(url, { headers })
    const data = await res.json()
    plans.value = data.plans || []
  } catch (err) {
    console.error('加载历史行程失败:', err)
  } finally {
    loading.value = false
  }
}

async function loadPlan(plan) {
  loading.value = true
  try {
    const API_BASE = 'http://localhost:3001/api'
    let url, headers = {}
    
    if (authStore.isAuthenticated) {
      url = `${API_BASE}/plans/${plan.id}`
      headers = { 'Authorization': `Bearer ${authStore.token}` }
    } else if (authStore.guestId) {
      url = `${API_BASE}/plans/${plan.id}?guestId=${authStore.guestId}`
    }
    
    const res = await fetch(url, { headers })
    const data = await res.json()
    
    if (data.plan) {
      // 加载行程数据到 store
      const planData = data.plan.data
      if (planData.points) {
        itineraryStore.loadFromAI({ points: planData.points })
        trackPlanLoad(plan.id)
        emit('load', plan)
      }
    }
  } catch (err) {
    console.error('加载行程失败:', err)
    alert('加载行程失败')
  } finally {
    loading.value = false
  }
}

async function deletePlan(planId) {
  if (!confirm('确定要删除这个行程吗？')) return
  
  try {
    const API_BASE = 'http://localhost:3001/api'
    const res = await fetch(`${API_BASE}/plans/${planId}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${authStore.token}` }
    })
    
    if (res.ok) {
      plans.value = plans.value.filter(p => p.id !== planId)
    }
  } catch (err) {
    console.error('删除行程失败:', err)
  }
}

function formatDate(dateStr) {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.history-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 360px;
  height: 100vh;
  background: #fff;
  box-shadow: -4px 0 20px rgba(0,0,0,0.1);
  z-index: 9999;
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header h3 {
  font-size: 18px;
  color: #2d3436;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #636e72;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: #f5f7fa;
}

.history-loading,
.history-empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #b2bec3;
  gap: 8px;
}

.history-empty .hint {
  font-size: 12px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-item {
  padding: 16px;
  border-radius: 8px;
  background: #f5f7fa;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.history-item:hover {
  background: #e8e4ff;
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.history-name {
  font-weight: 600;
  color: #2d3436;
  font-size: 14px;
}

.delete-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  opacity: 0;
  transition: opacity 0.2s;
}

.history-item:hover .delete-btn {
  opacity: 1;
}

.history-desc {
  font-size: 12px;
  color: #636e72;
  margin-bottom: 8px;
  line-height: 1.4;
}

.history-meta {
  font-size: 11px;
  color: #b2bec3;
}
</style>
