<template>
  <div>
    <n-space justify="space-between" align="flex-start" style="margin-bottom: 20px;">
      <div>
        <div style="font-size: 22px; font-weight: 600; color: #111827; margin-bottom: 4px;">出行指南</div>
        <div style="font-size: 13px; color: #9ca3af;">管理出行准备指南各章节内容，对应官网「出行指南」页面</div>
      </div>
      <n-space>
        <a href="/guides" target="_blank" style="text-decoration: none;">
          <n-button>查看前台 ↗</n-button>
        </a>
        <n-button type="primary" :loading="saving" :disabled="saving" @click="save">
          {{ saving ? '保存中...' : '保存' }}
        </n-button>
      </n-space>
    </n-space>

    <n-spin v-if="!loaded" style="display:block; padding: 60px; text-align: center;" />
    <template v-else>
      <n-card title="页面介绍" style="margin-bottom: 12px;">
        <n-input v-model:value="data.pageIntro" type="textarea" :rows="3" />
      </n-card>

      <n-card
        v-for="(s, i) in data.sections"
        :key="i"
        style="margin-bottom: 12px;"
      >
        <template #header>
          <div
            style="display: flex; justify-content: space-between; align-items: center; cursor: pointer; user-select: none;"
            @click="open[i] = !open[i]"
          >
            <span style="font-size: 15px; color: #333;">{{ s.icon || '' }} {{ s.title }}</span>
            <n-space align="center">
              <span style="font-size: 12px; color: #9ca3af;">{{ s.subtitle || '' }}</span>
              <span style="font-size: 12px; color: #999; transition: transform 0.2s; display: inline-block;" :style="open[i] ? 'transform: rotate(90deg)' : ''">&#9656;</span>
            </n-space>
          </div>
        </template>
        <div v-show="open[i]">
          <!-- 公共基础字段 -->
          <n-grid :cols="2" :x-gap="10" style="margin-bottom: 12px;">
            <n-gi>
              <n-form-item label="ID" :show-feedback="false">
                <n-input v-model:value="s.id" size="small" />
              </n-form-item>
            </n-gi>
            <n-gi>
              <n-form-item label="标题" :show-feedback="false">
                <n-input v-model:value="s.title" size="small" />
              </n-form-item>
            </n-gi>
            <n-gi>
              <n-form-item label="副标题" :show-feedback="false">
                <n-input v-model:value="s.subtitle" size="small" />
              </n-form-item>
            </n-gi>
            <n-gi>
              <n-form-item label="图标" :show-feedback="false">
                <n-input v-model:value="s.icon" size="small" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-form-item label="正文内容" :show-feedback="false" style="margin-bottom: 10px;">
            <n-input v-model:value="s.content" type="textarea" :rows="3" />
          </n-form-item>

          <!-- tips（documents / packing） -->
          <n-form-item v-if="'tips' in s" label="Tips（每行一个）" :show-feedback="false" style="margin-bottom: 10px;">
            <n-input
              type="textarea"
              :rows="3"
              :value="(s.tips||[]).join('\n')"
              @input="s.tips = $event.split('\n').filter(Boolean)"
            />
          </n-form-item>

          <!-- items（documents：{text, important}） -->
          <div v-if="s.items && s.items.length" style="margin-top: 14px; border-top: 1px solid #f0f0f0; padding-top: 10px;">
            <div style="font-size: 14px; color: #555; margin-bottom: 10px; font-weight: 500;">子项列表</div>
            <n-space v-for="(item, ii) in s.items" :key="ii" align="center" style="margin-bottom: 6px; width: 100%;">
              <template v-if="typeof item === 'string'">
                <n-input
                  :value="item"
                  @input="s.items[ii] = $event"
                  size="small"
                  style="flex: 1; min-width: 300px;"
                />
              </template>
              <template v-else>
                <n-input v-model:value="item.text" placeholder="文字" size="small" style="flex: 1; min-width: 300px;" />
                <n-tag
                  :type="item.important ? 'warning' : 'default'"
                  checkable
                  :checked="item.important"
                  @update:checked="item.important = $event"
                  size="small"
                >
                  重要
                </n-tag>
              </template>
              <n-button size="tiny" quaternary type="error" @click="s.items.splice(ii, 1)">删除</n-button>
            </n-space>
            <n-button size="small" dashed @click="addItem(s)" style="margin-top: 6px;">+ 添加子项</n-button>
          </div>

          <!-- 穿搭：months + extraTips -->
          <template v-if="s.id === 'clothing'">
            <n-card title="每月穿搭" size="small" style="margin-top: 12px;">
              <n-collapse>
                <n-collapse-item v-for="(m, mi) in s.months" :key="mi" :name="mi">
                  <template #header>{{ m.name }}</template>
                  <n-form-item label="月份名称" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input v-model:value="m.name" />
                  </n-form-item>
                  <n-form-item label="描述" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input v-model:value="m.desc" type="textarea" :rows="2" />
                  </n-form-item>
                  <n-grid :cols="2" :x-gap="12">
                    <n-gi>
                      <n-form-item label="日间温度" :show-feedback="false" style="margin-bottom: 8px;">
                        <n-input v-model:value="m.tempDay" />
                      </n-form-item>
                    </n-gi>
                    <n-gi>
                      <n-form-item label="夜间温度" :show-feedback="false" style="margin-bottom: 8px;">
                        <n-input v-model:value="m.tempNight" />
                      </n-form-item>
                    </n-gi>
                    <n-gi>
                      <n-form-item label="成人穿搭" :show-feedback="false" style="margin-bottom: 8px;">
                        <n-input v-model:value="m.adultWear" type="textarea" :rows="2" />
                      </n-form-item>
                    </n-gi>
                    <n-gi>
                      <n-form-item label="儿童穿搭" :show-feedback="false" style="margin-bottom: 8px;">
                        <n-input v-model:value="m.kidsWear" type="textarea" :rows="2" />
                      </n-form-item>
                    </n-gi>
                  </n-grid>
                  <n-form-item label="亮点" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input v-model:value="m.highlight" />
                  </n-form-item>
                  <n-form-item label="备注" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input v-model:value="m.note" />
                  </n-form-item>
                  <div style="text-align: right;">
                    <n-button size="tiny" quaternary type="error" @click="s.months.splice(mi, 1)">删除此月份</n-button>
                  </div>
                </n-collapse-item>
              </n-collapse>
              <n-button size="small" dashed @click="s.months.push({name:'',desc:'',tempDay:'',tempNight:'',adultWear:'',kidsWear:'',highlight:'',note:''})" style="margin-top: 10px;">+ 添加月份</n-button>
            </n-card>
            <n-form-item label="额外提示（每行一个）" :show-feedback="false" style="margin-top: 12px;">
              <n-input
                type="textarea"
                :rows="3"
                :value="(s.extraTips||[]).join('\n')"
                @input="s.extraTips = $event.split('\n').filter(Boolean)"
              />
            </n-form-item>
          </template>

          <!-- 行李清单：categories + provided + dontBring -->
          <template v-if="s.id === 'packing'">
            <n-card title="分类清单" size="small" style="margin-top: 12px;">
              <n-collapse>
                <n-collapse-item v-for="(cat, ci) in s.categories" :key="ci" :name="ci">
                  <template #header>{{ cat.name || '(未命名)' }}</template>
                  <n-form-item label="分类名称" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input v-model:value="cat.name" />
                  </n-form-item>
                  <n-form-item label="备注说明" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input v-model:value="cat.note" />
                  </n-form-item>
                  <n-form-item label="条目（每行一个）" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input
                      type="textarea"
                      :rows="4"
                      :value="(cat.items||[]).join('\n')"
                      @input="cat.items = $event.split('\n').filter(Boolean)"
                    />
                  </n-form-item>
                  <div style="text-align: right;">
                    <n-button size="tiny" quaternary type="error" @click="s.categories.splice(ci, 1)">删除此分类</n-button>
                  </div>
                </n-collapse-item>
              </n-collapse>
              <n-button size="small" dashed @click="s.categories.push({name:'',note:'',items:[]})" style="margin-top: 10px;">+ 添加分类</n-button>
            </n-card>

            <n-card title="已为您准备好的" size="small" style="margin-top: 12px;">
              <n-form-item label="标题" :show-feedback="false" style="margin-bottom: 8px;">
                <n-input v-model:value="s.provided.title" />
              </n-form-item>
              <n-form-item label="描述" :show-feedback="false" style="margin-bottom: 8px;">
                <n-input v-model:value="s.provided.description" type="textarea" :rows="2" />
              </n-form-item>
              <n-form-item label="物品列表（逗号或空格分隔的文字）" :show-feedback="false" style="margin-bottom: 8px;">
                <n-input v-model:value="s.provided.items" type="textarea" :rows="2" />
              </n-form-item>
            </n-card>

            <n-form-item label="不用带（每行一个）" :show-feedback="false" style="margin-top: 12px;">
              <n-input
                type="textarea"
                :rows="4"
                :value="(s.dontBring||[]).join('\n')"
                @input="s.dontBring = $event.split('\n').filter(Boolean)"
              />
            </n-form-item>
          </template>

          <!-- 活动安全：activities -->
          <template v-if="s.id === 'activities'">
            <n-card title="活动卡片" size="small" style="margin-top: 12px;">
              <n-collapse>
                <n-collapse-item v-for="(a, ai) in s.activities" :key="ai" :name="ai">
                  <template #header>{{ a.icon || '' }} {{ a.name || '(未命名)' }}</template>
                  <n-grid :cols="2" :x-gap="10">
                    <n-gi>
                      <n-form-item label="图标" :show-feedback="false" style="margin-bottom: 8px;">
                        <n-input v-model:value="a.icon" />
                      </n-form-item>
                    </n-gi>
                    <n-gi>
                      <n-form-item label="活动名称" :show-feedback="false" style="margin-bottom: 8px;">
                        <n-input v-model:value="a.name" />
                      </n-form-item>
                    </n-gi>
                  </n-grid>
                  <n-form-item label="安全要点（每行一个）" :show-feedback="false" style="margin-bottom: 8px;">
                    <n-input
                      type="textarea"
                      :rows="5"
                      :value="(a.points||[]).join('\n')"
                      @input="a.points = $event.split('\n').filter(Boolean)"
                    />
                  </n-form-item>
                  <div style="text-align: right;">
                    <n-button size="tiny" quaternary type="error" @click="s.activities.splice(ai, 1)">删除此活动</n-button>
                  </div>
                </n-collapse-item>
              </n-collapse>
              <n-button size="small" dashed @click="s.activities.push({icon:'',name:'',points:[]})" style="margin-top: 10px;">+ 添加活动</n-button>
            </n-card>
          </template>

          <!-- 实用信息：topics + apps + appNote -->
          <template v-if="s.id === 'practical'">
            <n-card title="常见话题" size="small" style="margin-top: 12px;">
              <n-space v-for="(t, ti) in s.topics" :key="ti" align="start" style="margin-bottom: 8px; width: 100%;">
                <n-input v-model:value="t.name" placeholder="话题名称" size="small" style="width: 160px;" />
                <n-input v-model:value="t.content" type="textarea" :rows="2" placeholder="内容" size="small" style="flex: 1; min-width: 400px;" />
                <n-button size="tiny" quaternary type="error" @click="s.topics.splice(ti, 1)">删除</n-button>
              </n-space>
              <n-button size="small" dashed @click="s.topics.push({name:'',content:''})">+ 添加话题</n-button>
            </n-card>

            <n-card title="推荐 App" size="small" style="margin-top: 12px;">
              <n-space v-for="(app, pi) in s.apps" :key="pi" align="center" style="margin-bottom: 6px; width: 100%;">
                <n-input v-model:value="app.category" placeholder="类别" size="small" style="width: 140px;" />
                <n-input v-model:value="app.names" placeholder="App 名称" size="small" style="flex: 1; min-width: 360px;" />
                <n-button size="tiny" quaternary type="error" @click="s.apps.splice(pi, 1)">删除</n-button>
              </n-space>
              <n-button size="small" dashed @click="s.apps.push({category:'',names:''})">+ 添加 App</n-button>
            </n-card>

            <n-form-item label="App 说明 / 额外提示" :show-feedback="false" style="margin-top: 12px;">
              <n-input v-model:value="s.appNote" type="textarea" :rows="2" />
            </n-form-item>
          </template>

          <!-- 幼童指南：notes / dining / equipment / conditional / recommended / notRecommended -->
          <template v-if="s.id === 'toddler'">
            <n-card title="注意事项 notes" size="small" style="margin-top: 12px;">
              <n-space v-for="(n, ni) in s.notes" :key="ni" align="start" style="margin-bottom: 8px; width: 100%;">
                <n-input v-model:value="n.title" placeholder="标题" size="small" style="width: 180px;" />
                <n-input v-model:value="n.content" type="textarea" :rows="2" placeholder="内容" size="small" style="flex: 1; min-width: 400px;" />
                <n-button size="tiny" quaternary type="error" @click="s.notes.splice(ni, 1)">删除</n-button>
              </n-space>
              <n-button size="small" dashed @click="s.notes.push({title:'',content:''})">+ 添加</n-button>
            </n-card>

            <n-form-item label="餐饮 dining（每行一个）" :show-feedback="false" style="margin-top: 12px;">
              <n-input
                type="textarea"
                :rows="4"
                :value="(s.dining||[]).join('\n')"
                @input="s.dining = $event.split('\n').filter(Boolean)"
              />
            </n-form-item>

            <n-card title="装备 equipment" size="small" style="margin-top: 12px;">
              <n-space v-for="(e, ei) in s.equipment" :key="ei" align="start" style="margin-bottom: 8px; width: 100%;">
                <n-input v-model:value="e.name" placeholder="名称" size="small" style="width: 140px;" />
                <n-input v-model:value="e.desc" type="textarea" :rows="2" placeholder="描述" size="small" style="flex: 1; min-width: 300px;" />
                <n-tag
                  :type="e.provided ? 'success' : 'default'"
                  checkable
                  :checked="!!e.provided"
                  @update:checked="e.provided = $event"
                  size="small"
                >
                  呼籁提供
                </n-tag>
                <n-button size="tiny" quaternary type="error" @click="s.equipment.splice(ei, 1)">删除</n-button>
              </n-space>
              <n-button size="small" dashed @click="s.equipment.push({name:'',desc:'',provided:false})">+ 添加装备</n-button>
            </n-card>

            <n-card
              v-for="key in ['recommended','conditional','notRecommended']"
              :key="key"
              :title="toddlerGroupTitle(key)"
              size="small"
              style="margin-top: 12px;"
            >
              <n-form-item label="标题" :show-feedback="false" style="margin-bottom: 8px;">
                <n-input v-model:value="s[key].title" />
              </n-form-item>
              <n-form-item label="描述" :show-feedback="false" style="margin-bottom: 8px;">
                <n-input v-model:value="s[key].desc" type="textarea" :rows="2" />
              </n-form-item>
              <n-form-item label="条目（每行一个）" :show-feedback="false" style="margin-bottom: 8px;">
                <n-input
                  type="textarea"
                  :rows="4"
                  :value="(s[key].items||[]).join('\n')"
                  @input="s[key].items = $event.split('\n').filter(Boolean)"
                />
              </n-form-item>
            </n-card>
          </template>
        </div>
      </n-card>
    </template>
  </div>
</template>

<script setup>
import { NButton, NCard, NSpace, NInput, NFormItem, NSpin, NGrid, NGi, NTag, NCollapse, NCollapseItem } from 'naive-ui'
import { useMessage } from 'naive-ui'

definePageMeta({ layout: 'admin', middleware: 'admin' })
const { adminFetch } = useAdmin()
const message = useMessage()
const data = ref({ pageIntro: '', sections: [] })
const loaded = ref(false)
const saving = ref(false)
const open = reactive({})

function toddlerGroupTitle(key) {
  return { recommended: '推荐参与 recommended', conditional: '视情况而定 conditional', notRecommended: '不建议 notRecommended' }[key]
}

function addItem(s) {
  const sample = s.items[0]
  if (typeof sample === 'string' || sample === undefined) s.items.push('')
  else s.items.push({ text: '', important: false })
}

async function load() {
  const res = await adminFetch('/api/admin/site-content?key=guides')
  const d = res.data || { pageIntro: '', sections: [] }
  // 兜底补齐各 section 缺失的字段，避免 v-model 绑定到 undefined
  for (const s of d.sections || []) {
    if (s.id === 'packing') {
      s.categories = s.categories || []
      s.provided = s.provided || { title: '', description: '', items: '' }
      s.dontBring = s.dontBring || []
    }
    if (s.id === 'clothing') {
      s.months = s.months || []
      s.extraTips = s.extraTips || []
    }
    if (s.id === 'activities') s.activities = s.activities || []
    if (s.id === 'practical') {
      s.topics = s.topics || []
      s.apps = s.apps || []
      s.appNote = s.appNote || ''
    }
    if (s.id === 'toddler') {
      s.notes = s.notes || []
      s.dining = s.dining || []
      s.equipment = s.equipment || []
      s.recommended = s.recommended || { title: '', desc: '', items: [] }
      s.conditional = s.conditional || { title: '', desc: '', items: [] }
      s.notRecommended = s.notRecommended || { title: '', desc: '', items: [] }
    }
  }
  data.value = d
  loaded.value = true
}
async function save() {
  saving.value = true
  try {
    await adminFetch('/api/admin/site-content', { method: 'PUT', body: { key: 'guides', data: data.value } })
    message.success('已保存')
  } catch { message.error('保存失败') } finally { saving.value = false }
}
onMounted(load)
</script>
