<template>
  <view class="script-view">
    <text class="page-title font-serif">剧本生成器</text>

    <view class="section-card glass-card-gold">
      <view class="section-header">
        <text class="section-title">我的基础人设</text>
        <text class="section-hint">可自由修改</text>
      </view>

      <view class="profile-grid">
        <input
          class="glass-input"
          placeholder="姓名"
          v-model="nickname"
        />
        <picker class="glass-picker" mode="selector" :range="zodiacOptions" :value="zodiacIndex" @change="onZodiacChange">
          <view class="picker-value">{{ registrationData.zodiac || '星座' }}</view>
        </picker>
        <picker class="glass-picker" mode="selector" :range="mbtiOptions" :value="mbtiIndex" @change="onMbtiChange">
          <view class="picker-value">{{ registrationData.mbti || 'MBTI' }}</view>
        </picker>
        <input
          class="glass-input"
          placeholder="职业"
          v-model="profession"
        />
      </view>
    </view>

    <view class="section-card glass-card-main">
      <view class="input-group">
        <text class="label">1. 剧本主题</text>
        <input
          class="glass-input theme-input"
          placeholder="如：巅峰重现、治愈之旅、赛博觉醒..."
          v-model="scriptConfig.theme"
        />
        <!-- 灵感气泡 -->
        <view class="hint-container">
          <view class="hint-header">
            <text class="hint-icon">✨</text>
            <text class="hint-label">灵感气泡</text>
          </view>
          <view class="hint-list">
            <view
              v-for="(hint, index) in scriptHints"
              :key="index"
              class="hint-chip"
              :style="{ animationDelay: index * 0.1 + 's' }"
              @click="addHint(hint)"
            >
              <text>{{ hint }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="input-group">
        <view class="npc-header">
          <text class="label">2. 关键配角/新的人设</text>
          <button class="add-btn" @click="addNpc">+ 添加</button>
        </view>

        <view class="npc-form">
          <input
            class="glass-input npc-input"
            placeholder="姓名"
            v-model="npcConfig.name"
          />
          <picker class="glass-picker npc-picker" mode="selector" :range="npcRoleOptions" :value="npcRoleIndex" @change="onNpcRoleChange">
            <view class="picker-value">{{ npcConfig.role || '角色' }}</view>
          </picker>
          <picker class="glass-picker npc-picker" mode="selector" :range="npcRelationOptions" :value="npcRelationIndex" @change="onNpcRelationChange">
            <view class="picker-value">{{ npcConfig.relation || '关系' }}</view>
          </picker>
          <textarea
            class="glass-textarea npc-textarea"
            placeholder="自由描述 TA 的人设特点或关键剧情点..."
            v-model="npcConfig.desc"
            rows="3"
          />
        </view>

        <view class="npc-list">
          <view
            v-for="(npc, index) in customNpcs"
            :key="index"
            class="npc-tag"
          >
            <text>{{ npc.name }} ({{ npc.role }})</text>
            <text class="delete-btn" @click="removeNpc(index)">×</text>
          </view>
        </view>
      </view>

      <view class="params-section">
        <text class="param-section-label">3. 核心参数</text>
        <view class="params-container">
          <view class="param-group">
            <text class="param-sublabel">叙事风格</text>
            <view class="param-options">
              <text
                v-for="style in scriptStyles"
                :key="style"
                class="param-option"
                :class="{ active: scriptConfig.style === style }"
                @click="scriptConfig.style = style"
              >
                {{ style }}
              </text>
            </view>
          </view>
          <view class="param-group">
            <text class="param-sublabel">故事篇幅</text>
            <view class="param-options">
              <text
                v-for="length in scriptLengths"
                :key="length"
                class="param-option"
                :class="{ active: scriptConfig.length === length }"
                @click="scriptConfig.length = length"
              >
                {{ length }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <button
        class="btn-primary generate-btn"
        :loading="isGenerating"
        :disabled="isGenerating || !scriptConfig.theme"
        @click="generateScript"
      >
        <text v-if="isGenerating">命运编织中...</text>
        <text v-else>生成平行人生剧本</text>
      </button>
    </view>

    <view v-if="scripts.length > 0" class="scripts-list">
      <view
        v-for="script in scripts"
        :key="script.id"
        class="script-card glass-card"
        :class="{ selected: script.isSelected }"
        @click="viewScriptDetail(script)"
      >
        <view class="script-header">
          <text class="script-title">{{ script.title }}</text>
          <text class="script-persona">{{ script.theme || '追光者' }}</text>
        </view>

        <view class="script-summary">
          <Markdown :content="getScriptSummary(script)" />
        </view>

        <view class="script-footer">
          <text class="script-style">{{ script.style || '风格' }}</text>
          <button class="select-btn" @click.stop="selectScript(script.id)">
            路径映射 →
          </button>
        </view>
      </view>
    </view>

    <view v-else-if="!isGenerating" class="empty-state glass-card">
      <text class="empty-icon">🎬</text>
      <text class="empty-text">尚未生成剧本，定义你的未来篇章</text>
    </view>

    <view v-if="isGenerating" class="generating-state glass-card">
      <view class="spinner"></view>
      <text class="generating-text">正在采集星海中的深紫色碎屑...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useAppStore } from '../../stores/app.js'
import Markdown from '../../components/Markdown.vue'

const store = useAppStore()

const zodiacOptions = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座']
const mbtiOptions = ['INTJ', 'INTP', 'ENTJ', 'ENTP', 'INFJ', 'INFP', 'ENFJ', 'ENFP', 'ISTJ', 'ISFJ', 'ESTJ', 'ESFJ', 'ISTP', 'ISFP', 'ESTP', 'ESFP']
const npcRoleOptions = ['伙伴', '宿敌', '导师', '挚爱', '下属', '路人']
const npcRelationOptions = ['信任', '对立', '暧昧', '敬畏', '背叛', '守护']
const scriptStyles = ['爽文', '治愈', '热血', '玄幻', '职场', '赛博']
const scriptLengths = ['短篇', '中篇', '长篇', '史诗']
const scriptHints = ['觉醒时刻', '命运转折', '自我救赎', '巅峰重现', '治愈之旅', '星际穿越', '破茧成蝶', '时光倒流']

const registrationData = computed(() => store.registrationData || {})
const scripts = computed(() => store.scripts || [])

const nickname = computed({
  get: () => registrationData.value.nickname || '',
  set: (val) => store.updateRegistration({ nickname: val })
})

const profession = computed({
  get: () => registrationData.value.profession || '',
  set: (val) => store.updateRegistration({ profession: val })
})

const zodiacIndex = computed(() => zodiacOptions.indexOf(registrationData.value.zodiac))
const mbtiIndex = computed(() => mbtiOptions.indexOf(registrationData.value.mbti))

const scriptConfig = reactive({
  theme: '',
  style: '爽文',
  length: '中篇'
})

const npcConfig = reactive({
  name: '',
  role: '伙伴',
  relation: '信任',
  desc: ''
})

const customNpcs = ref([])
const isGenerating = ref(false)

const npcRoleIndex = computed(() => npcRoleOptions.indexOf(npcConfig.role))
const npcRelationIndex = computed(() => npcRelationOptions.indexOf(npcConfig.relation))

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

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

const onNpcRoleChange = (e) => {
  npcConfig.role = npcRoleOptions[e.detail.value]
}

const onNpcRelationChange = (e) => {
  npcConfig.relation = npcRelationOptions[e.detail.value]
}

const addNpc = () => {
  if (npcConfig.name) {
    customNpcs.value.push({ ...npcConfig })
    npcConfig.name = ''
    npcConfig.desc = ''
  }
}

const removeNpc = (index) => {
  customNpcs.value.splice(index, 1)
}

const addHint = (hint) => {
  if (scriptConfig.theme) {
    scriptConfig.theme += ' · ' + hint
  } else {
    scriptConfig.theme = hint
  }
}

const generateScript = async () => {
  if (!scriptConfig.theme || isGenerating.value) return

  isGenerating.value = true

  try {
    await store.createScript({
      theme: scriptConfig.theme,
      style: scriptConfig.style,
      length: scriptConfig.length,
      character: registrationData.value,
      events: store.events
    })
    scriptConfig.theme = ''
  } finally {
    isGenerating.value = false
  }
}

const selectScript = async (id) => {
  await store.selectScript(id)
  uni.$emit('switchTab', 'path')
}

const viewScriptDetail = (script) => {
  uni.navigateTo({
    url: `/pages/main/ScriptDetailView?id=${script.id}`
  })
}

const getScriptSummary = (script) => {
  // 优先使用 summary 字段
  if (script.summary) {
    return script.summary
  }

  // 从 fullContent 提取前 200 字符
  const fullContent = script.plotJson?.fullContent || ''
  if (fullContent) {
    // 提取内容，去掉 Markdown 符号
    return fullContent
      .split('\n')
      .filter(line => line.trim())
      .slice(0, 5)  // 取前 5 行
      .join('\n')
      .slice(0, 200) + '...'
  }

  return '暂无摘要'
}

onMounted(async () => {
  await store.fetchUserProfile()
  await store.fetchEvents()
  await store.fetchScripts()
})
</script>

<style scoped>
.script-view {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  min-height: 100%;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.page-title {
  font-size: 36rpx;
  font-weight: 300;
  color: rgba(255, 255, 255, 0.9);
  letter-spacing: 4rpx;
  font-family: 'Cinzel', 'Inter', serif;
}

/* 人设卡片 - 金色玻璃态 */
.section-card {
  padding: 32rpx;
  border-radius: 40rpx;
  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);
  box-shadow: inset 0 0 30rpx rgba(168, 85, 247, 0.08), 0 4rpx 20rpx rgba(168, 85, 247, 0.1);
  transition: all 0.3s ease;
  margin-bottom: 32rpx;
}

.section-card:active {
  transform: scale(0.98);
  box-shadow: inset 0 0 20rpx rgba(168, 85, 247, 0.05), 0 2rpx 12rpx rgba(168, 85, 247, 0.05);
}

.glass-card-main {
  padding: 32rpx;
  border-radius: 40rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.section-title {
  font-size: 20rpx;
  color: rgba(192, 132, 252, 0.6);
  font-weight: 600;
  letter-spacing: 3rpx;
  text-transform: uppercase;
}

.section-hint {
  font-size: 15rpx;
  color: rgba(255, 255, 255, 0.35);
  font-style: italic;
}

.profile-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24rpx;
}

.glass-input, .glass-picker {
  width: 100%;
  height: 88rpx;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 32rpx;
  padding: 0 24rpx;
  color: rgba(255, 255, 255, 0.9);
  font-size: 28rpx;
  box-sizing: border-box;
}

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

.theme-input {
  height: 88rpx;
  font-size: 28rpx;
}

.picker-value {
  line-height: 88rpx;
  color: rgba(255, 255, 255, 0.9);
}

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

/* 灵感气泡容器 */
.hint-container {
  margin-top: 16rpx;
  padding: 24rpx;
  background: rgba(168, 85, 247, 0.08);
  border: 1px solid rgba(168, 85, 247, 0.15);
  border-radius: 32rpx;
  box-shadow: inset 0 0 20rpx rgba(168, 85, 247, 0.05);
}

.hint-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 16rpx;
}

.hint-icon {
  font-size: 24rpx;
  filter: drop-shadow(0 0 8rpx rgba(192, 132, 252, 0.6));
}

.hint-label {
  font-size: 18rpx;
  color: rgba(192, 132, 252, 0.8);
  font-weight: 600;
  letter-spacing: 4rpx;
  text-transform: uppercase;
}

.hint-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.hint-chip {
  padding: 10rpx 20rpx;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 24rpx;
  font-size: 20rpx;
  color: rgba(243, 232, 255, 0.8);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8rpx);
  transition: all 0.2s ease;
  animation: bubble-float 5s ease-in-out infinite;
}

.hint-chip:active {
  background: rgba(168, 85, 247, 0.25);
  border-color: rgba(168, 85, 247, 0.5);
  transform: scale(0.95);
  box-shadow: 0 8rpx 15rpx rgba(168, 85, 247, 0.3);
}

@keyframes bubble-float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  33% {
    transform: translateY(-4rpx) rotate(1deg);
  }
  66% {
    transform: translateY(2rpx) rotate(-1deg);
  }
}

.label {
  display: block;
  font-size: 20rpx;
  color: rgba(192, 132, 252, 0.6);
  font-weight: 600;
  letter-spacing: 3rpx;
  text-transform: uppercase;
  margin-bottom: 12rpx;
}

.npc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.add-btn {
  font-size: 16rpx;
  color: #C084FC;
  border: 1px solid rgba(192, 132, 252, 0.3);
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  background: transparent;
}

.npc-container {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 24rpx;
  padding: 16rpx;
  margin-bottom: 14rpx;
}

.npc-form {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;  /* 三列等分 */
  gap: 16rpx;  /* 间距适中 */
}

/* textarea 跨越三列 */
.npc-textarea {
  grid-column: 1 / -1;
}

.npc-input, .npc-picker {
  height: 88rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
}

.npc-picker .picker-value {
  line-height: 88rpx;
  font-size: 28rpx;
}

.glass-textarea {
  width: 100%;
  height: 120rpx;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 32rpx;
  padding: 20rpx;
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
  box-sizing: border-box;
}

.npc-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.npc-tag {
  background: rgba(168, 85, 247, 0.1);
  border: 1px solid rgba(168, 85, 247, 0.3);
  border-radius: 24rpx;
  padding: 10rpx 20rpx;
  font-size: 20rpx;
  color: rgba(243, 232, 255, 0.8);
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.delete-btn {
  color: rgba(255, 255, 255, 0.4);
  font-size: 24rpx;
  padding: 0 4rpx;
}

.params-section {
  margin-bottom: 32rpx;
}

.param-section-label {
  display: block;
  font-size: 20rpx;
  color: rgba(192, 132, 252, 0.6);
  font-weight: 600;
  letter-spacing: 3rpx;
  text-transform: uppercase;
  margin-bottom: 16rpx;
}

.params-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24rpx;
}

.param-group {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  min-width: 0;
}

.param-sublabel {
  font-size: 17rpx;
  color: rgba(255, 255, 255, 0.4);
  margin-left: 4rpx;
}

.param-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10rpx;
}

.param-option {
  padding: 8rpx 12rpx;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 20rpx;
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.4);
  text-align: center;
  transition: all 0.2s ease;
}

.param-option.active {
  background: rgba(168, 85, 247, 0.25);
  border-color: #C084FC;
  color: #F3E8FF;
  box-shadow: 0 0 15px rgba(168, 85, 247, 0.4);
  font-weight: 500;
}

.generate-btn {
  /* 尺寸 */
  width: 100%;
  height: 96rpx;

  /* 背景渐变 - 与原型一致 */
  background: linear-gradient(135deg, #9333EA 0%, #7C3AED 100%);

  /* 圆角 - 与原型 rounded-2xl 一致 */
  border-radius: 32rpx;

  /* 阴影 */
  box-shadow: 0 8rpx 32rpx rgba(168, 85, 247, 0.3);

  /* 外边距 */
  margin-top: 24rpx;

  /* 文字居中 - 核心修复 */
  display: flex;
  align-items: center;
  justify-content: center;

  /* 文字样式 */
  color: #ffffff !important;
  font-size: 28rpx;
  font-weight: 600;

  /* 过渡动画 */
  transition: all 0.2s ease;
}

.generate-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.generate-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.scripts-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.script-card {
  padding: 32rpx;
  border-left: 3rpx solid transparent;
  border-radius: 40rpx;
  position: relative;
}

.script-card::before {
  content: '👑';
  position: absolute;
  top: -12rpx;
  right: 24rpx;
  font-size: 32rpx;
  filter: drop-shadow(0 0 8rpx rgba(232, 121, 249, 0.6));
}

.script-card.selected {
  border-left-color: #C084FC;
}

.script-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14rpx;
}

.script-title {
  font-size: 32rpx;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
}

.script-persona {
  font-size: 17rpx;
  color: rgba(168, 85, 247, 0.6);
  background: rgba(168, 85, 247, 0.1);
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  border: 1px solid rgba(168, 85, 247, 0.2);
}

.script-summary {
  display: block;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.5);
  line-height: 1.5;
  margin-bottom: 16rpx;
}

.script-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.script-style {
  font-size: 18rpx;
  color: #C084FC;
}

.select-btn {
  font-size: 20rpx;
  color: #C084FC;
  font-weight: 600;
  background: transparent;
  border: none;
  padding: 0;
}

.empty-state {
  padding: 56rpx 36rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
  opacity: 0.5;
  border-radius: 48rpx;
}

.empty-icon {
  font-size: 48rpx;
}

.empty-text {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.5);
  text-align: center;
}

.generating-state {
  padding: 56rpx 36rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
  border-radius: 48rpx;
}

/* 星芒加载动画 - 原型标准（双环旋转） */
.starlight-loader {
  position: relative;
  width: 80rpx;
  height: 80rpx;
  margin: 40rpx auto;
}

.starlight-loader::before,
.starlight-loader::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3rpx solid transparent;
  border-top-color: #C084FC;
  border-right-color: #A855F7;
  animation: starlight-spin 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}

.starlight-loader::before {
  width: 70%;
  height: 70%;
  border-top-color: #E879F9;
  border-right-color: #9333EA;
  animation-delay: -0.75s;
}

@keyframes starlight-spin {
  0% {
    transform: translate(-50%, -50%) rotate(0deg) scale(1);
  }
  50% {
    transform: translate(-50%, -50%) rotate(180deg) scale(1.2);
  }
  100% {
    transform: translate(-50%, -50%) rotate(360deg) scale(1);
  }
}

/* 加载文字 - 脉冲效果 */
.generating-text {
  font-size: 20rpx;
  color: rgba(192, 132, 252, 0.6);
  font-style: italic;
  letter-spacing: 2rpx;
  animation: pulse-text 2s ease-in-out infinite;
}

@keyframes pulse-text {
  0%, 100% { opacity: 0.6; }
  50% { opacity: 1; }
}

/* 超小屏幕适配 - 375px 断点 */
@media (max-width: 375px) {
  .params-container {
    grid-template-columns: 1fr;
  }
}

/* 超小屏幕适配 - 320px 断点 */
@media (max-width: 320px) {
  .profile-grid, .npc-form {
    grid-template-columns: 1fr;
  }

  .section-card {
    padding: 24rpx;
  }

  .glass-input, .glass-picker {
    height: 80rpx;
    font-size: 26rpx;
  }

  .picker-value {
    line-height: 80rpx;
  }

  .generate-btn {
    height: 88rpx;
  }
}
</style>
