<template>
  <view class="onboarding-page">
    <view class="bg-decoration">
      <view class="aurora-top"></view>
      <view class="aurora-bottom"></view>
    </view>
    
    <view class="content" :style="{ '--safe-area-top-rpx': safeAreaTop + 'rpx', '--safe-area-bottom-rpx': safeAreaBottom + 'rpx' }">
      <scroll-view class="step-content" scroll-y>
        <view class="step-inner">
          <view v-if="currentStep === 1" class="step animate-fade-in">
            <view class="step-header">
              <text class="step-title font-serif">系统初始化</text>
              <text class="step-subtitle">定义你在人生OS中的唯一代码</text>
            </view>
            
            <view class="form-grid">
              <view class="input-group">
                <text class="label">你的昵称</text>
                <input
                  class="glass-input"
                  placeholder="输入昵称"
                  v-model="formData.nickname"
                />
              </view>
              
              <view class="input-group">
                <text class="label">性别</text>
                <picker class="glass-picker" mode="selector" :range="genderOptions" :value="genderIndex" @change="onGenderChange">
                  <view class="picker-value">{{ formData.gender || '请选择' }}</view>
                </picker>
              </view>
              
              <view class="input-group">
                <text class="label">星座</text>
                <picker class="glass-picker" mode="selector" :range="zodiacOptions" :value="zodiacIndex" @change="onZodiacChange">
                  <view class="picker-value">{{ formData.zodiac || '请选择' }}</view>
                </picker>
              </view>
              
              <view class="input-group">
                <text class="label">MBTI人格</text>
                <picker class="glass-picker" mode="selector" :range="mbtiOptions" :value="mbtiIndex" @change="onMbtiChange">
                  <view class="picker-value">{{ formData.mbti || '请选择' }}</view>
                </picker>
              </view>
              
              <view class="input-group full-width">
                <text class="label">兴趣爱好</text>
                <input
                  class="glass-input"
                  placeholder="用逗号分隔，如：阅读，旅行，摄影"
                  v-model="hobbiesText"
                />
              </view>
            </view>
          </view>
          
          <view v-if="currentStep === 2" class="step animate-fade-in">
            <view class="step-header">
              <text class="step-title font-serif">回溯起源</text>
              <text class="step-subtitle">一段让你感到温暖的早期时光</text>
            </view>
            
            <view class="memory-form">
              <view class="input-group">
                <text class="label">日期</text>
                <picker class="glass-picker" mode="date" :value="formData.childhood.date" @change="onChildhoodDateChange">
                  <view class="picker-value">{{ formData.childhood.date || '请选择日期' }}</view>
                </picker>
              </view>
              
              <view class="input-group">
                <text class="label">回忆一段具体且温暖的午后...</text>
                <textarea
                  class="glass-textarea"
                  rows="4"
                  placeholder="描述那段时光..."
                  v-model="formData.childhood.text"
                />
              </view>
              
              <view class="hint-section">
                <view class="hint-title">
                  <text class="icon">✨</text>
                  <text>灵感气泡</text>
                </view>
                <view class="hint-tags">
                  <text
                    v-for="(hint, index) in childhoodHints"
                    :key="index"
                    class="hint-tag"
                    @click="addChildhoodHint(hint)"
                  >
                    {{ hint }}
                  </text>
                </view>
              </view>
            </view>
          </view>
          
          <view v-if="currentStep === 3" class="step animate-fade-in">
            <view class="step-header">
              <text class="step-title font-serif">悦然时刻</text>
              <text class="step-subtitle">一段感受到生命跃动的经历</text>
            </view>
            
            <view class="memory-form">
              <view class="input-group">
                <text class="label">日期</text>
                <picker class="glass-picker" mode="date" :value="formData.joy.date" @change="onJoyDateChange">
                  <view class="picker-value">{{ formData.joy.date || '请选择日期' }}</view>
                </picker>
              </view>
              
              <view class="input-group">
                <text class="label">想一个令你会心一笑的瞬间...</text>
                <textarea
                  class="glass-textarea"
                  rows="4"
                  placeholder="描述那个瞬间..."
                  v-model="formData.joy.text"
                />
              </view>
              
              <view class="hint-section">
                <view class="hint-title">
                  <text class="icon">✨</text>
                  <text>灵感气泡</text>
                </view>
                <view class="hint-tags">
                  <text
                    v-for="(hint, index) in joyHints"
                    :key="index"
                    class="hint-tag"
                    @click="addJoyHint(hint)"
                  >
                    {{ hint }}
                  </text>
                </view>
              </view>
            </view>
          </view>
          
          <view v-if="currentStep === 4" class="step animate-fade-in">
            <view class="step-header">
              <text class="step-title font-serif">破茧成蝶</text>
              <text class="step-subtitle">在宁静中默默积蓄力量的日子</text>
            </view>
            
            <view class="memory-form">
              <view class="input-group">
                <text class="label">日期</text>
                <picker class="glass-picker" mode="date" :value="formData.low.date" @change="onLowDateChange">
                  <view class="picker-value">{{ formData.low.date || '请选择日期' }}</view>
                </picker>
              </view>
              
              <view class="input-group">
                <text class="label">描述那段有些艰难但让你成长的日子...</text>
                <textarea
                  class="glass-textarea"
                  rows="4"
                  placeholder="描述那段经历..."
                  v-model="formData.low.text"
                />
              </view>
              
              <view class="hint-section">
                <view class="hint-title">
                  <text class="icon">✨</text>
                  <text>灵感气泡</text>
                </view>
                <view class="hint-tags">
                  <text
                    v-for="(hint, index) in lowHints"
                    :key="index"
                    class="hint-tag"
                    @click="addLowHint(hint)"
                  >
                    {{ hint }}
                  </text>
                </view>
              </view>
            </view>
          </view>
          
          <view v-if="currentStep === 5" class="step animate-fade-in">
            <view class="step-header">
              <text class="step-title font-serif">未来憧憬</text>
              <text class="step-subtitle">对未来理想生活状态的预见</text>
            </view>
            
            <view class="memory-form">
              <view class="input-group">
                <text class="label">你想成为怎样的人？</text>
                <textarea
                  class="glass-textarea"
                  rows="3"
                  placeholder="描述你对未来的愿景..."
                  v-model="formData.future.vision"
                />
              </view>
              
              <view class="input-group">
                <text class="label">你的理想生活状态</text>
                <textarea
                  class="glass-textarea"
                  rows="3"
                  placeholder="描述理想的一天..."
                  v-model="formData.future.ideal"
                />
              </view>
              
              <view class="quote-box">
                <text class="quote-icon">✨</text>
                <text class="quote-text">"照见未来，便是创造的开始。"</text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      
      <view class="bottom-bar">
        <view class="step-dots">
          <view
            v-for="step in 5"
            :key="step"
            class="step-dot"
            :class="{ active: currentStep === step }"
          />
        </view>
        
        <view class="actions">
          <button
            v-if="currentStep > 1"
            class="btn-secondary"
            @click="prevStep"
          >
            返回
          </button>
          
          <button
            class="btn-primary next-btn"
            :loading="isSaving"
            @click="nextStep"
          >
            <text v-if="currentStep === 5">{{ isSaving ? '保存中...' : '开启人生' }}</text>
            <text v-else>继续</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue'
import { useAppStore } from '../../stores/app.js'
import * as lifeEventService from '../../services/lifeEvent.js'

const store = useAppStore()

const safeAreaTop = ref(uni.getStorageSync('safeAreaTop') || 20)
const safeAreaBottom = ref(uni.getStorageSync('safeAreaBottom') || 0)

onMounted(async () => {
  // 使用新的推荐 API 替代已弃用的 getSystemInfoSync
  const windowInfo = uni.getWindowInfo()
  // 获取安全区域值（px），转换为 rpx（乘以 2，假设设计稿宽度 750rpx）
  const safeTopPx = windowInfo.safeAreaInsets?.top || windowInfo.statusBarHeight || 20
  const safeBottomPx = windowInfo.safeAreaInsets?.bottom || 0
  // 转换为 rpx 用于 CSS 变量
  safeAreaTop.value = safeTopPx * 2
  safeAreaBottom.value = safeBottomPx * 2
  await store.fetchUserProfile()
  Object.assign(formData, store.registrationData)
  currentStep.value = store.currentStep || 1
})

const currentStep = ref(store.currentStep || 1)
const isSaving = ref(false)

const formData = reactive({
  nickname: '',
  gender: '',
  mbti: '',
  zodiac: '',
  profession: '',
  hobbies: [],
  childhood: { date: '', text: '' },
  joy: { date: '', text: '' },
  low: { date: '', text: '' },
  future: { vision: '', ideal: '' }
})

const genderOptions = ['男', '女']
const zodiacOptions = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座']
const mbtiOptions = ['INTJ', 'INTP', 'ENTJ', 'ENTP', 'INFJ', 'INFP', 'ENFJ', 'ENFP', 'ISTJ', 'ISFJ', 'ESTJ', 'ESFJ', 'ISTP', 'ISFP', 'ESTP', 'ESFP']

const childhoodHints = ['秘密花园', '老旧弄堂', '秋千', '夏蝉', '被保护的', '好奇心']
const joyHints = ['突破', '共鸣', '清晨阳光', '认可', '旅行终点', '深呼吸']
const lowHints = ['迷茫', '无力感', '雨后街道', '重新出发', '裂痕中的光', '蜕变']

const hobbiesText = computed({
  get: () => formData.hobbies.join('，'),
  set: (val) => {
    formData.hobbies = val.split(/[,，]/).map(s => s.trim()).filter(s => s)
  }
})

const genderIndex = computed(() => genderOptions.indexOf(formData.gender))
const zodiacIndex = computed(() => zodiacOptions.indexOf(formData.zodiac))
const mbtiIndex = computed(() => mbtiOptions.indexOf(formData.mbti))

const onGenderChange = (e) => {
  formData.gender = genderOptions[e.detail.value]
}

const onZodiacChange = (e) => {
  formData.zodiac = zodiacOptions[e.detail.value]
}

const onMbtiChange = (e) => {
  formData.mbti = mbtiOptions[e.detail.value]
}

const onChildhoodDateChange = (e) => {
  formData.childhood.date = e.detail.value
}

const onJoyDateChange = (e) => {
  formData.joy.date = e.detail.value
}

const onLowDateChange = (e) => {
  formData.low.date = e.detail.value
}

const addChildhoodHint = (hint) => {
  formData.childhood.text += hint + ' '
}

const addJoyHint = (hint) => {
  formData.joy.text += hint + ' '
}

const addLowHint = (hint) => {
  formData.low.text += hint + ' '
}

const prevStep = () => {
  if (currentStep.value > 1) {
    saveStepData()
    currentStep.value--
  }
}

const nextStep = async () => {
  saveStepData()
  
  if (currentStep.value < 5) {
    currentStep.value++
  } else {
    isSaving.value = true
    try {
      const result = await store.saveUserProfile()
      if (result.success) {
        const eventsToSave = [
          { data: formData.childhood, type: 'childhood', title: '童年记忆' },
          { data: formData.joy, type: 'joy', title: '光芒闪耀的时刻' },
          { data: formData.low, type: 'low', title: '在暗夜中潜行' }
        ]
        await Promise.all(
          eventsToSave.map(({ data, type, title }) => {
            if (!data?.date || !data?.text) return Promise.resolve()
            return lifeEventService.createEvent({
              title,
              time: data.date,
              content: data.text,
              eventType: 'milestone',
              tags: [type]
            })
          })
        )
        await store.fetchEvents()
        uni.showToast({ title: '欢迎开启人生OS', icon: 'success' })
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/main/index' })
        }, 1500)
      } else {
        uni.showToast({ title: result.error || '保存失败', icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: '保存失败', icon: 'none' })
    } finally {
      isSaving.value = false
    }
  }
}

const saveStepData = () => {
  store.updateRegistration({ ...formData })
}

watch(currentStep, (val) => {
  store.setCurrentStep(val)
})
</script>

<style scoped>
.onboarding-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #0F071A 0%, #1A0B2E 50%, #0F071A 100%);
  position: relative;
}

.bg-decoration {
  position: absolute;
  inset: 0;
  pointer-events: none;
}

.aurora-top {
  position: absolute;
  top: -10%;
  left: -10%;
  width: 120%;
  height: 60%;
  background: rgba(168, 85, 247, 0.08);
  filter: blur(120rpx);
  border-radius: 50%;
}

.aurora-bottom {
  position: absolute;
  bottom: -10%;
  right: -10%;
  width: 100%;
  height: 50%;
  background: rgba(139, 92, 246, 0.05);
  filter: blur(100rpx);
  border-radius: 50%;
}

.content {
  position: relative;
  z-index: 1;
  height: 100vh;
  display: flex;
  flex-direction: column;
  /* 统一使用 rpx 单位处理 padding */
  padding: 24rpx;
  /* 安全区域使用 CSS 变量，从内联样式传入 - 统一转换为 rpx */
  padding-top: calc(24rpx + var(--safe-area-top-rpx, 40rpx));
  padding-bottom: calc(24rpx + var(--safe-area-bottom-rpx, 0rpx));
  box-sizing: border-box;
}

.step-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  /* 精确计算：100vh 减去底部 bar 高度 (约 180rpx) 和上下 padding (48rpx) */
  height: calc(100vh - 260rpx);
  min-height: 0;
  /* 修复微信小程序滚动问题 */
  -webkit-overflow-scrolling: touch;
}

.step-inner {
  padding-bottom: 40rpx;
}

.step {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.step-header {
  margin-bottom: 48rpx;
}

.step-title {
  display: block;
  font-size: 46rpx;
  font-weight: 400;
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 12rpx;
  letter-spacing: 4rpx;
}

.step-subtitle {
  display: block;
  font-size: 24rpx;
  color: rgba(192, 132, 252, 0.6);
  font-style: italic;
}

.form-grid {
  display: grid;
  /* 响应式网格：最小 280rpx，自动适配列数 */
  grid-template-columns: repeat(auto-fit, minmax(280rpx, 1fr));
  gap: 20rpx;
}

/* 小屏幕设备单列布局 - 使用 fixed 列宽触发自动换行 */
.form-grid-mobile {
  grid-template-columns: 1fr;
}

.full-width {
  grid-column: 1 / -1;
}

.input-group {
  margin-bottom: 8rpx;
}

.label {
  display: block;
  font-size: 18rpx;
  color: rgba(255, 255, 255, 0.35);
  margin-bottom: 12rpx;
  letter-spacing: 4rpx;
  text-transform: uppercase;
}

.glass-input, .glass-picker {
  /* 输入框高度从 88rpx 降至 72rpx，为内容留出更多空间 */
  height: 72rpx;
  width: 100%;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid rgba(168, 85, 247, 0.15);
  border-radius: 40rpx; /* 原型标准：2.5rem = 40px = 80rpx -> 40rpx */
  padding: 0 24rpx;
  color: #F3E8FF;
  font-size: 28rpx;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.glass-input:active, .glass-picker:active {
  background: rgba(168, 85, 247, 0.1);
  border-color: rgba(168, 85, 247, 0.4);
  box-shadow: 0 0 15px rgba(168, 85, 247, 0.3);
}

.glass-input::placeholder {
  color: rgba(255, 255, 255, 0.3);
}

.picker-value {
  line-height: 72rpx;
  color: rgba(255, 255, 255, 0.8);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.glass-textarea {
  /* 自适应高度：最小 160rpx，最大 300rpx */
  width: 100%;
  min-height: 160rpx;
  max-height: 300rpx;
  height: auto;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid rgba(168, 85, 247, 0.15);
  border-radius: 40rpx; /* 原型标准：统一圆角 */
  padding: 24rpx;
  color: #F3E8FF;
  font-size: 28rpx;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.glass-textarea:active {
  background: rgba(168, 85, 247, 0.1);
  border-color: rgba(168, 85, 247, 0.4);
  box-shadow: 0 0 15px rgba(168, 85, 247, 0.3);
}

.glass-textarea::placeholder {
  color: rgba(255, 255, 255, 0.3);
}

.memory-form {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.hint-section {
  background: rgba(168, 85, 247, 0.08);
  border: 1px solid rgba(168, 85, 247, 0.15);
  border-radius: 32rpx;
  padding: 32rpx;
  margin-top: 16rpx;
  box-shadow: inset 0 0 30rpx rgba(168, 85, 247, 0.08);
}

.hint-title {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 18rpx;
  color: rgba(192, 132, 252, 0.6);
  text-transform: uppercase;
  letter-spacing: 4rpx;
  margin-bottom: 20rpx;
}

.icon {
  font-size: 24rpx;
}

.hint-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.hint-tag {
  /* 原型：可点击填充芯片 */
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 32rpx;
  padding: 10rpx 22rpx;
  font-size: 22rpx;
  color: rgba(243, 232, 255, 0.8);
  cursor: pointer;
  transition: all 0.2s ease;
}

.hint-tag:active {
  background: rgba(168, 85, 247, 0.2);
  border-color: rgba(168, 85, 247, 0.4);
  box-shadow: 0 0 12px rgba(168, 85, 247, 0.4);
  transform: scale(0.98);
}

.quote-box {
  background: linear-gradient(135deg, rgba(168, 85, 247, 0.15), rgba(232, 121, 249, 0.1));
  border: 1px solid rgba(168, 85, 247, 0.3);
  border-radius: 20rpx;
  padding: 32rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-top: 16rpx;
}

.quote-icon {
  font-size: 32rpx;
}

.quote-text {
  font-size: 26rpx;
  color: rgba(243, 232, 255, 0.7);
  font-style: italic;
}

.bottom-bar {
  padding-top: 32rpx;
  /* 使用 CSS 变量处理底部安全区域 */
  padding-bottom: calc(32rpx + var(--safe-area-bottom, 0px));
  border-top: 1px solid rgba(255, 255, 255, 0.05);
}

.step-dots {
  display: flex;
  gap: 8rpx;
  margin-bottom: 32rpx;
}

.step-dot {
  flex: 1;
  height: 8rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4rpx;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.step-dot.active {
  flex: 1.5; /* 激活状态加宽 */
  height: 8rpx;
  background: #A855F7;
  box-shadow: 0 0 24rpx rgba(168, 85, 247, 0.6);
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 24rpx;
  align-items: center;
}

.next-btn {
  min-width: 200rpx;
  padding: 24rpx 48rpx;
  background: linear-gradient(135deg, #9333EA 0%, #7C3AED 100%);
  border: none;
  border-radius: 40rpx;
  color: white;
  font-size: 28rpx;
  font-weight: 600;
  letter-spacing: 4rpx;
  box-shadow: 0 8rpx 24rpx rgba(168, 85, 247, 0.3);
  transition: all 0.3s ease;
}

.next-btn:active {
  transform: scale(0.96);
  box-shadow: 0 4rpx 16rpx rgba(168, 85, 247, 0.2);
}

.btn-secondary {
  padding: 24rpx 32rpx;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 40rpx;
  color: rgba(255, 255, 255, 0.7);
  font-size: 26rpx;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.btn-secondary:active {
  transform: scale(0.96);
  background: rgba(168, 85, 247, 0.1);
  border-color: rgba(168, 85, 247, 0.3);
}
</style>
