<template>
  <div class="buddy-layout">
    <!-- Login -->
    <div v-if="!loggedIn" class="buddy-login">
      <div class="buddy-login-logo">🌙</div>
      <h1>睡眠打卡</h1>
      <p>和好友一起早睡</p>
      <div class="buddy-login-card">
        <input v-model="username" placeholder="用户名" @keydown.enter="$refs.pwdInput?.focus()">
        <input ref="pwdInput" v-model="pwd" type="password" placeholder="密码" @keydown.enter="isRegister ? doRegister() : doLogin()">
        <input v-if="isRegister" v-model="pwd2" type="password" placeholder="确认密码" @keydown.enter="doRegister">
        <button class="buddy-main-btn" @click="isRegister ? doRegister() : doLogin()">{{ isRegister ? '注册' : '登录' }}</button>
        <button class="buddy-toggle-btn" @click="isRegister = !isRegister">{{ isRegister ? '已有账号？登录' : '没有账号？注册' }}</button>
        <div class="buddy-error">{{ error }}</div>
      </div>
    </div>

    <!-- Main -->
    <div v-else class="buddy-main">
      <div class="buddy-header">
        <h2>🌙 睡眠打卡</h2>
        <div class="user-chip" @click="showMenu = !showMenu">
          {{ myName }} ▾
          <div v-if="showMenu" class="user-menu">
            <button @click="doLogout">退出登录</button>
          </div>
        </div>
      </div>

      <!-- Notifications -->
      <div v-for="n in notifications" :key="n.id" class="notif-bar">
        {{ n.message }}
      </div>

      <button class="sleep-btn" @click="goSleep">🌙 我去睡觉啦</button>

      <!-- Target -->
      <div class="target-card">
        <span>我的目标入睡时间</span>
        <span class="target-time">{{ myTarget }}</span>
        <button @click="setTarget">修改</button>
      </div>

      <!-- Record -->
      <div class="record-card">
        <h3>记录 / 修改入睡时间</h3>
        <div class="capture-row">
          <input v-model="sleepInput" placeholder="昨晚11点半 / 10:30" @keydown.enter.prevent="addRecord">
          <button @click="addRecord">记录</button>
        </div>
        <div class="buddy-hint">{{ hint }}</div>
      </div>

      <!-- Records list -->
      <div class="record-card">
        <h3>最近记录</h3>
        <div v-for="r in myRecords" :key="r.date" class="buddy-record">
          <span>{{ r.date }}</span>
          <span>{{ r.time }}</span>
          <button class="remove-btn" @click="deleteRecord(r.date)">✕</button>
        </div>
        <div v-if="myRecords.length === 0" class="empty-hint">暂无记录</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { api } from '../composables/useApi'

const loggedIn = ref(false)
const myName = ref('')
const isRegister = ref(false)
const username = ref('')
const pwd = ref('')
const pwd2 = ref('')
const error = ref('')
const showMenu = ref(false)
const sleepInput = ref('')
const hint = ref('')
const buddyData = ref({ users: {}, targets: {}, notifications: [] })
const notifications = ref([])
const myTarget = ref('22:00')

async function hashStr(s) {
  const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s))
  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('')
}

const myRecords = computed(() => {
  return (buddyData.value.users[myName.value] || [])
})

async function loadData() {
  buddyData.value = await api.get('/api/sleep-buddy')
  myTarget.value = buddyData.value.targets?.[myName.value] || '22:00'
  // Load notifications
  const res = await api.post('/api/sleep-buddy', { user: myName.value, action: 'get-notifications' })
  notifications.value = res.notifications || []
}

async function doLogin() {
  error.value = ''
  try {
    const hash = await hashStr(pwd.value)
    await api.post('/api/buddy-login', { username: username.value.trim(), hash })
    myName.value = username.value.trim()
    localStorage.setItem('buddy_session', JSON.stringify({ username: myName.value, exp: Date.now() + 30 * 86400000 }))
    loggedIn.value = true
    await loadData()
  } catch (e) {
    error.value = e.message
  }
}

async function doRegister() {
  error.value = ''
  if (pwd.value !== pwd2.value) { error.value = '密码不一致'; return }
  try {
    const hash = await hashStr(pwd.value)
    await api.post('/api/buddy-register', { username: username.value.trim(), hash })
    await doLogin()
  } catch (e) {
    error.value = e.message
  }
}

function doLogout() {
  localStorage.removeItem('buddy_session')
  loggedIn.value = false
  myName.value = ''
}

async function goSleep() {
  await api.post('/api/sleep-buddy', { user: myName.value, action: 'sleep-now' })
  hint.value = '晚安！已通知好友'
}

async function setTarget() {
  const t = prompt('设置目标入睡时间（如 22:00）', myTarget.value)
  if (!t) return
  await api.post('/api/sleep-buddy', { user: myName.value, action: 'set-target', target: t })
  myTarget.value = t
}

async function addRecord() {
  const text = sleepInput.value.trim()
  if (!text) return
  const timeMatch = text.match(/(\d{1,2}):(\d{2})/)
  let time
  if (timeMatch) {
    time = `${timeMatch[1].padStart(2, '0')}:${timeMatch[2]}`
  } else {
    const cn = text.match(/(\d{1,2})点半?/)
    if (cn) {
      const m = text.includes('半') ? '30' : '00'
      time = `${String(parseInt(cn[1])).padStart(2, '0')}:${m}`
    }
  }
  if (!time) { hint.value = '无法识别时间'; return }
  const now = new Date()
  const date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
  await api.post('/api/sleep-buddy', { user: myName.value, action: 'record', record: { date, time } })
  sleepInput.value = ''
  hint.value = `已记录 ${date} ${time}`
  await loadData()
}

async function deleteRecord(date) {
  await api.post('/api/sleep-buddy', { user: myName.value, action: 'delete-record', date })
  await loadData()
}

onMounted(() => {
  const saved = JSON.parse(localStorage.getItem('buddy_session') || 'null')
  if (saved && Date.now() < saved.exp) {
    myName.value = saved.username
    loggedIn.value = true
    loadData()
  }
})
</script>
