<script setup lang="ts">
import { CheckCircle2, Pencil, Plus, Save, Trash2 } from "lucide-vue-next";

defineProps<{ ctx: any }>();
</script>

<template>
  <section class="panel page-stack">
    <div class="section-head">
      <div>
        <h2>{{ ctx.activeLegacyLabel }}</h2>
        <p class="muted">可视化表单只维护常用字段，保存时会合并回当前 JSON，未识别字段继续保留。</p>
      </div>
      <div class="button-row">
        <button class="btn ghost" @click="ctx.validateLegacy(ctx.activeLegacyName)"><CheckCircle2 :size="16" />校验</button>
        <button class="btn primary" @click="ctx.saveLegacy(ctx.activeLegacyName)"><Save :size="16" />保存发布</button>
      </div>
    </div>

    <div class="tabs">
      <button :class="{ active: ctx.legacyDrafts[ctx.activeLegacyName].tab === 'form' }" @click="ctx.legacyDrafts[ctx.activeLegacyName].tab = 'form'">可视化</button>
      <button :class="{ active: ctx.legacyDrafts[ctx.activeLegacyName].tab === 'raw' }" @click="ctx.legacyDrafts[ctx.activeLegacyName].tab = 'raw'">Raw JSON</button>
      <button :class="{ active: ctx.legacyDrafts[ctx.activeLegacyName].tab === 'preview' }" @click="ctx.legacyDrafts[ctx.activeLegacyName].tab = 'preview'">预览</button>
      <button :class="{ active: ctx.legacyDrafts[ctx.activeLegacyName].tab === 'history' }" @click="ctx.legacyDrafts[ctx.activeLegacyName].tab = 'history'">历史版本</button>
    </div>

    <section v-if="ctx.legacyDrafts[ctx.activeLegacyName].tab === 'form' && ctx.activeLegacyName === 'update-info'" class="page-stack">
      <section class="form-grid">
        <label>版本号<input v-model="ctx.legacyDrafts['update-info'].form.app_version" /></label>
        <label>标题<input v-model="ctx.legacyDrafts['update-info'].form.title" /></label>
        <label class="wide">公告<textarea v-model="ctx.legacyDrafts['update-info'].form.message" rows="3"></textarea></label>
        <label class="wide">下载地址<input v-model="ctx.legacyDrafts['update-info'].form.download_url" /></label>
        <label>包 SHA256<input v-model="ctx.legacyDrafts['update-info'].form.package_sha256" /></label>
        <label>包大小<input v-model="ctx.legacyDrafts['update-info'].form.package_size" type="number" /></label>
        <label class="wide">发布说明<textarea v-model="ctx.legacyDrafts['update-info'].form.release_notes" rows="4"></textarea></label>
        <label class="wide">发布说明 Markdown<textarea v-model="ctx.legacyDrafts['update-info'].form.release_notes_md" rows="4"></textarea></label>
      </section>

      <section class="nested-card">
        <div class="section-head">
          <h3>下载镜像</h3>
          <button class="btn ghost compact" @click="ctx.openUpdateMirrorModal()"><Plus :size="14" />新增镜像</button>
        </div>
        <table>
          <thead><tr><th>ID</th><th>名称</th><th>类型</th><th>状态</th><th>URL</th><th>操作</th></tr></thead>
          <tbody>
            <tr v-for="(mirror, index) in ctx.legacyDrafts['update-info'].form.download_mirrors || []" :key="mirror.id || index">
              <td class="mono">{{ mirror.id }}</td>
              <td>{{ mirror.name }}</td>
              <td>{{ mirror.type || "direct" }}</td>
              <td><span :class="['badge', mirror.enabled === false ? 'neutral' : 'good']">{{ mirror.enabled === false ? "停用" : "启用" }}</span></td>
              <td class="hash">{{ mirror.url }}</td>
              <td>
                <div class="button-row">
                  <button class="btn ghost compact" @click="ctx.openUpdateMirrorModal(index)"><Pencil :size="14" />编辑</button>
                  <button class="btn ghost compact danger" @click="ctx.removeItem(ctx.legacyDrafts['update-info'].form.download_mirrors, index)"><Trash2 :size="14" />删除</button>
                </div>
              </td>
            </tr>
            <tr v-if="!(ctx.legacyDrafts['update-info'].form.download_mirrors || []).length"><td colspan="6">暂无镜像。</td></tr>
          </tbody>
        </table>
      </section>

      <details>
        <summary>高级 JSON 字段</summary>
        <div class="form-grid">
          <label class="wide">更新说明 JSON<textarea v-model="ctx.legacyDrafts['update-info'].form.update_notes" class="code-editor mini-editor"></textarea></label>
          <label class="wide">上次更新说明 JSON<textarea v-model="ctx.legacyDrafts['update-info'].form.last_update_notes" class="code-editor mini-editor"></textarea></label>
        </div>
      </details>
      <div class="button-row"><button class="btn" @click="ctx.updateLegacyRawFromForm('update-info')">生成预览 JSON</button></div>
    </section>

    <section v-else-if="ctx.legacyDrafts[ctx.activeLegacyName].tab === 'form'" class="split legacy-media-editor">
      <section class="panel-soft page-stack">
        <div class="form-grid">
          <label>布局版本<input v-model="ctx.legacyDrafts['media-types'].form.layout_version" /></label>
          <label>更新时间<input v-model="ctx.legacyDrafts['media-types'].form.last_updated" /></label>
          <label class="wide">UI 配置 JSON<textarea v-model="ctx.legacyDrafts['media-types'].form.ui_config" class="code-editor mini-editor"></textarea></label>
        </div>
        <div class="section-head">
          <h3>分类</h3>
          <button class="btn ghost compact" @click="ctx.openMediaCategoryModal()"><Plus :size="14" />新增分类</button>
        </div>
        <div class="category-list" v-if="ctx.legacyDrafts['media-types'].form.categories.length">
          <button
            v-for="(cat, cIndex) in ctx.legacyDrafts['media-types'].form.categories"
            :key="cat.id || cIndex"
            type="button"
            :class="{ active: ctx.activeMediaCategoryIndex === cIndex }"
            @click="ctx.selectMediaCategory(cIndex)"
          >
            <span><strong>{{ cat.name || cat.id || `分类 ${cIndex + 1}` }}</strong><small class="mono">{{ cat.id || "-" }}</small></span>
            <span class="badge">{{ cat.subcategories?.length || 0 }}</span>
          </button>
        </div>
        <div v-else class="empty-state compact">暂无分类。</div>
      </section>

      <aside class="panel-soft page-stack media-subcategory-panel">
        <div class="section-head">
          <div>
            <h3>{{ ctx.activeMediaCategory?.name || ctx.activeMediaCategory?.id || "子接口" }}</h3>
            <p class="muted">右侧仅显示当前选中分类下的子接口。</p>
          </div>
          <div class="button-row">
            <button class="btn ghost compact" :disabled="!ctx.activeMediaCategory" @click="ctx.openMediaCategoryModal(ctx.activeMediaCategoryIndex)"><Pencil :size="14" />编辑分类</button>
            <button class="btn ghost compact" :disabled="!ctx.activeMediaCategory" @click="ctx.openMediaSubcategoryModal(ctx.activeMediaCategoryIndex)"><Plus :size="14" />新增子接口</button>
            <button class="btn" @click="ctx.updateLegacyRawFromForm('media-types')">生成预览 JSON</button>
          </div>
        </div>
        <section v-if="ctx.activeMediaCategory" class="source-group">
          <div class="button-row">
            <span :class="['badge', ctx.activeMediaCategory.enabled === false ? 'neutral' : 'good']">{{ ctx.activeMediaCategory.enabled === false ? "停用" : "启用" }}</span>
            <button class="btn ghost compact danger" @click="ctx.removeItem(ctx.legacyDrafts['media-types'].form.categories, ctx.activeMediaCategoryIndex)"><Trash2 :size="14" />删除分类</button>
          </div>
          <div class="table-scroll media-subcategory-table">
          <table>
            <thead><tr><th>ID</th><th>名称</th><th>刷新</th><th>URL</th><th>操作</th></tr></thead>
            <tbody>
              <tr v-for="(sub, sIndex) in ctx.activeMediaCategory.subcategories || []" :key="sub.id || sIndex">
                <td class="mono">{{ sub.id }}</td>
                <td>{{ sub.name }}</td>
                <td>{{ sub.refresh_interval || 300 }}s</td>
                <td class="hash url-cell" :title="sub.api_url">{{ sub.api_url }}</td>
                <td>
                  <div class="button-row">
                    <button class="btn ghost compact" @click="ctx.openMediaSubcategoryModal(ctx.activeMediaCategoryIndex, sIndex)"><Pencil :size="14" />编辑</button>
                    <button class="btn ghost compact danger" @click="ctx.removeItem(ctx.activeMediaCategory.subcategories, sIndex)"><Trash2 :size="14" />删除</button>
                  </div>
                </td>
              </tr>
              <tr v-if="!(ctx.activeMediaCategory.subcategories || []).length"><td colspan="5">当前分类暂无子接口。</td></tr>
            </tbody>
          </table>
          </div>
        </section>
        <div v-else class="empty-state compact">请选择或新增一个分类。</div>
      </aside>
    </section>

    <section v-else-if="ctx.legacyDrafts[ctx.activeLegacyName].tab === 'raw'" class="page-stack">
      <textarea v-model="ctx.legacyDrafts[ctx.activeLegacyName].raw" class="code-editor"></textarea>
      <label>保存备注<input v-model="ctx.legacyDrafts[ctx.activeLegacyName].note" /></label>
    </section>

    <section v-else-if="ctx.legacyDrafts[ctx.activeLegacyName].tab === 'preview'">
      <pre class="json-preview tall">{{ ctx.pretty(ctx.legacyDrafts[ctx.activeLegacyName].preview) }}</pre>
    </section>

    <section v-else class="revision-list">
      <button v-for="revision in ctx.legacyDocuments[ctx.activeLegacyName]?.revisions || []" :key="revision.id" @click="ctx.restoreLegacy(ctx.activeLegacyName, revision.id)">
        #{{ revision.id }} {{ revision.createdAt }}<small>{{ revision.note || "无备注" }}</small>
      </button>
      <div v-if="(ctx.legacyDocuments[ctx.activeLegacyName]?.revisions || []).length === 0" class="empty-state compact">暂无历史版本。</div>
    </section>

    <Teleport to="body">
      <div v-if="ctx.legacyModal.open" class="modal-backdrop" @click.self="ctx.closeLegacyModal">
        <section class="modal-panel">
          <div class="section-head">
            <h2>{{ ctx.legacyModal.type === 'media-category' ? '分类' : ctx.legacyModal.type === 'media-subcategory' ? '子接口' : '下载镜像' }}</h2>
            <button class="btn ghost compact" @click="ctx.closeLegacyModal">关闭</button>
          </div>

          <div v-if="ctx.legacyModal.type === 'media-category'" class="form-grid">
            <label>ID<input v-model="ctx.legacyModal.draft.id" /></label>
            <label>名称<input v-model="ctx.legacyModal.draft.name" /></label>
            <label class="checkbox wide"><input v-model="ctx.legacyModal.draft.enabled" type="checkbox" />启用分类</label>
          </div>

          <div v-else-if="ctx.legacyModal.type === 'media-subcategory'" class="form-grid">
            <label>ID<input v-model="ctx.legacyModal.draft.id" /></label>
            <label>名称<input v-model="ctx.legacyModal.draft.name" /></label>
            <label class="wide">接口 URL<input v-model="ctx.legacyModal.draft.api_url" /></label>
            <label>缩略图<input v-model="ctx.legacyModal.draft.thumbnail_url" /></label>
            <label>刷新间隔<input v-model.number="ctx.legacyModal.draft.refresh_interval" type="number" /></label>
            <label>格式<input v-model="ctx.legacyModal.draft.supported_formats" placeholder="json, mp4, webp" /></label>
            <label class="checkbox"><input v-model="ctx.legacyModal.draft.downloadable" type="checkbox" />可下载</label>
            <label class="wide">描述<textarea v-model="ctx.legacyModal.draft.description" rows="2"></textarea></label>
          </div>

          <div v-else class="form-grid">
            <label>ID<input v-model="ctx.legacyModal.draft.id" /></label>
            <label>名称<input v-model="ctx.legacyModal.draft.name" /></label>
            <label>类型<input v-model="ctx.legacyModal.draft.type" /></label>
            <label class="wide">URL<input v-model="ctx.legacyModal.draft.url" /></label>
            <label>SHA256<input v-model="ctx.legacyModal.draft.sha256" /></label>
            <label class="checkbox"><input v-model="ctx.legacyModal.draft.enabled" type="checkbox" />启用</label>
          </div>

          <div class="button-row">
            <button class="btn primary" @click="ctx.applyLegacyModal">保存</button>
          </div>
        </section>
      </div>
    </Teleport>
  </section>
</template>
