<template>
  <div
    v-if="open"
    class="fixed inset-0 z-40 flex items-start justify-center overflow-y-auto overscroll-contain p-6 bg-[rgba(30,28,32,0.35)] backdrop-blur-lg max-md:p-3"
    @click.self="$emit('close')"
  >
    <section
      class="flex w-[min(920px,100%)] max-h-[min(calc(100dvh-32px),calc(100vh-32px))] flex-col min-h-0 my-4 shrink-0 overflow-hidden rounded-xl border border-white/35 bg-white/95 p-7 shadow-[0_24px_60px_rgba(33,33,40,0.2)] max-md:my-3 max-md:max-h-[min(calc(100dvh-24px),calc(100vh-24px))] max-md:p-[18px]"
      @click.stop
    >
      <!-- Header -->
      <div class="flex shrink-0 items-start justify-between gap-4 pb-[22px]">
        <div>
          <h3>{{ form.id ? '编辑商品' : '添加新商品' }}</h3>
          <p class="tag">封面图和最多 5 张商品截图共用这一套编辑表单。</p>
        </div>
        <button class="ghost" @click="$emit('close')">关闭</button>
      </div>

      <!-- Body (scrolls; keeps footer actions reachable) -->
      <div class="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto pr-1">
        <div class="form-field">
          <label>商品名称</label>
          <input v-model="form.name" placeholder="商品名称" />
        </div>

        <div class="grid grid-cols-2 gap-3 max-md:grid-cols-1">
          <div class="form-field">
            <label>原价（元）</label>
            <input v-model.number="form.price" type="number" step="0.01" />
          </div>
          <div class="form-field">
            <label>折扣价（元，可选）</label>
            <input v-model.number="form.discountPrice" type="number" step="0.01" />
            <p class="tag">留空或不小于原价时，将不启用折扣。</p>
          </div>
        </div>

        <div class="form-field">
          <label>封面链接（http）</label>
          <input v-model="form.coverUrl" placeholder="http://..." />
        </div>

        <div class="form-field">
          <label>发货方式</label>
          <div class="flex flex-col gap-2 rounded-lg border border-white/35 bg-white/70 p-3">
            <label class="flex items-start gap-2.5 cursor-pointer font-semibold text-apptext m-0">
              <input v-model="form.fulfillmentType" class="mt-1 w-auto accent-accent" type="radio" value="card" />
              <span>
                卡密 / 逐条库存
                <span class="block text-[13px] font-normal text-muted">每条库存单独添加，下单按条扣减；售完不可再买。</span>
              </span>
            </label>
            <label class="flex items-start gap-2.5 cursor-pointer font-semibold text-apptext m-0">
              <input v-model="form.fulfillmentType" class="mt-1 w-auto accent-accent" type="radio" value="fixed" />
              <span>
                固定内容（不限库存）
                <span class="block text-[13px] font-normal text-muted">同一篇内容反复发货，如网盘链接、统一说明；无需维护条数。</span>
              </span>
            </label>
          </div>
        </div>

        <div v-if="form.fulfillmentType === 'fixed'" class="form-field">
          <label>固定发货内容</label>
          <textarea v-model="form.fixedContent" rows="5" placeholder="例如：https://… 网盘链接，或一段固定发给买家的文字"></textarea>
          <p class="tag">保存后顾客每笔订单会收到这份内容（若一次买多件，会复制多行相同内容便于核对）。</p>
        </div>

        <div v-else class="form-field">
          <div class="flex items-center gap-3 flex-wrap">
            <label>卡密 / 库存条目</label>
            <span class="tag">共 {{ form.inventoryItems.length }} 条</span>
            <button class="ghost px-3.5 py-1.5 text-[13px] rounded-full" type="button" @click="addInventoryItem">添加一行</button>
          </div>
          <p class="tag">每条一行，手动逐个添加；购买后按顺序发放并扣减库存。</p>
          <div class="flex flex-col gap-2 mt-1">
            <div v-for="(_, index) in form.inventoryItems" :key="index" class="flex items-center gap-2 max-md:flex-col max-md:items-stretch">
              <input
                :ref="(el) => setInventoryInputRef(el, index)"
                v-model="form.inventoryItems[index]"
                class="flex-1"
                placeholder="单条卡密或可发放内容"
              />
              <button
                v-if="form.inventoryItems.length > 1"
                class="ghost px-3.5 py-1.5 text-[13px] rounded-full"
                type="button"
                @click="removeInventoryItem(index)"
              >删除</button>
            </div>
          </div>
        </div>

        <div class="form-field">
          <label>商品截图链接（最多 5 个）</label>
          <div class="grid grid-cols-2 gap-2.5 max-md:grid-cols-1">
            <input
              v-for="(_, index) in screenshotInputSlots"
              :key="index"
              v-model="form.screenshotUrls[index]"
              :placeholder="`截图链接 ${index + 1}（http://...）`"
            />
          </div>
        </div>

        <div class="form-field">
          <label>商品介绍（Markdown）</label>
          <textarea v-model="form.description"></textarea>
        </div>

        <div class="form-field">
          <label>商品标签（英文逗号分隔）</label>
          <input v-model="form.tagsText" placeholder="例如: chatgpt, linux, 域名" />
          <p class="tag">用于前端搜索与筛选，多个标签用英文逗号分开</p>
        </div>

        <div class="form-field">
          <label>是否上架</label>
          <select v-model="form.active" class="rounded-lg border border-white/35 bg-white/70 px-3 py-2.5 text-[15px] outline-none" style="font-family: var(--font-serif);">
            <option :value="true">上架</option>
            <option :value="false">下架</option>
          </select>
        </div>

        <div class="grid grid-cols-2 gap-3 max-md:grid-cols-1">
          <div class="form-field">
            <label class="flex items-center font-semibold text-apptext cursor-default">
              <input type="checkbox" v-model="form.requireLogin" class="w-auto mr-1.5 accent-accent cursor-pointer" />
              需要登录才能购买
            </label>
            <p class="tag">开启后未登录用户将无法完成购买</p>
          </div>
          <div class="form-field">
            <label>每账户最多购买数量（0 = 不限）</label>
            <input v-model.number="form.maxPerAccount" type="number" min="0" step="1" placeholder="0 表示不限制" />
          </div>
        </div>

        <div class="form-field">
          <label>发货模式</label>
          <p class="rounded-lg border border-white/35 bg-white/70 px-3 py-2.5 text-[15px] text-apptext m-0" style="font-family: var(--font-serif);">
            自动发货（下单后自动提取库存内容）
          </p>
          <p class="tag">手动发货已暂时关闭，后续版本再开放</p>
        </div>

        <div class="grid grid-cols-2 gap-3 max-md:grid-cols-1">
          <div class="form-field">
            <label class="flex items-center font-semibold text-apptext cursor-default">
              <input type="checkbox" v-model="form.showNote" class="w-auto mr-1.5 accent-accent cursor-pointer" />
              下单时显示备注输入框
            </label>
          </div>
          <div class="form-field">
            <label class="flex items-center font-semibold text-apptext cursor-default">
              <input type="checkbox" v-model="form.showContact" class="w-auto mr-1.5 accent-accent cursor-pointer" />
              下单时显示联系方式输入框
            </label>
            <p class="tag">包含手机号和邮箱两个输入框</p>
          </div>
        </div>
      </div>

      <!-- Actions -->
      <div class="flex shrink-0 gap-3 border-t border-white/35 bg-white/95 pt-4 mt-5">
        <button class="primary" @click="handleSubmit">{{ form.id ? '更新商品' : '新增商品' }}</button>
        <button class="ghost" @click="resetForm">重置表单</button>
      </div>
    </section>
  </div>
</template>

<script setup>
import { nextTick, reactive, ref, watch } from 'vue'

const MAX_SCREENSHOT_URLS = 5
const MAX_INVENTORY_ITEMS = 500
const screenshotInputSlots = Array.from({ length: MAX_SCREENSHOT_URLS })
const inventoryInputRefs = ref([])

const props = defineProps({
  open: { type: Boolean, default: false },
  editItem: { type: Object, default: null }
})

const emit = defineEmits(['close', 'submit'])

const createScreenshotSlots = (values = []) => Array.from({ length: MAX_SCREENSHOT_URLS }, (_, i) => values[i] || '')

const createInventoryItems = (values = []) => {
  const items = values.map((v) => (v || '').trim()).filter((v) => v).slice(0, MAX_INVENTORY_ITEMS)
  return items.length ? items : ['']
}

const normalizeInventoryItems = (values = []) =>
  values.map((item) => (item || '').trim()).filter((item) => item).slice(0, MAX_INVENTORY_ITEMS)

const normalizeScreenshotUrls = (values = []) =>
  values.map((item) => item.trim()).filter(Boolean).slice(0, MAX_SCREENSHOT_URLS)

const makeEmptyForm = () => ({
  id: '', name: '', price: 0, discountPrice: 0, tagsText: '', coverUrl: '',
  screenshotUrls: createScreenshotSlots(), inventoryItems: createInventoryItems(),
  fulfillmentType: 'card', fixedContent: '',
  description: '', active: true, requireLogin: false, maxPerAccount: 0,
  deliveryMode: 'auto', showNote: true, showContact: true
})

const form = reactive(makeEmptyForm())

const fillForm = (item) => {
  const ft = (item?.fulfillmentType || 'card').toLowerCase() === 'fixed' ? 'fixed' : 'card'
  Object.assign(form, {
    id: item?.id || '', name: item?.name || '', price: item?.price || 0, discountPrice: item?.discountPrice || 0,
    tagsText: (item?.tags || []).join(','), coverUrl: item?.coverUrl || '',
    screenshotUrls: createScreenshotSlots(item?.screenshotUrls || []),
    inventoryItems: ft === 'fixed' ? [''] : createInventoryItems(item?.codes || []),
    fulfillmentType: ft,
    fixedContent: item?.fixedContent || '',
    description: item?.description || '', active: item?.active ?? true,
    requireLogin: item?.requireLogin ?? false, maxPerAccount: item?.maxPerAccount ?? 0,
    deliveryMode: item?.deliveryMode || 'auto',
    showNote: item?.showNote ?? true, showContact: item?.showContact ?? true
  })
}

const resetForm = () => { Object.assign(form, makeEmptyForm()) }

watch(() => props.editItem, (item) => { if (item) { fillForm(item) } else { resetForm() } }, { immediate: true })

const setInventoryInputRef = (el, index) => { if (!el) return; inventoryInputRefs.value[index] = el }

const addInventoryItem = async () => {
  form.inventoryItems.push('')
  await nextTick()
  const lastIndex = form.inventoryItems.length - 1
  const input = inventoryInputRefs.value[lastIndex]
  if (input?.focus) input.focus()
  if (input?.scrollIntoView) input.scrollIntoView({ block: 'center', behavior: 'smooth' })
}

const removeInventoryItem = async (index) => {
  if (form.inventoryItems.length <= 1) { form.inventoryItems[0] = ''; return }
  form.inventoryItems.splice(index, 1)
  inventoryInputRefs.value.splice(index, 1)
  await nextTick()
  const targetIndex = Math.min(index, form.inventoryItems.length - 1)
  const input = inventoryInputRefs.value[targetIndex]
  if (input?.focus) input.focus()
}

const handleSubmit = () => {
  const ft = form.fulfillmentType === 'fixed' ? 'fixed' : 'card'
  emit('submit', {
    id: form.id, name: form.name, price: form.price, discountPrice: form.discountPrice || 0,
    tags: form.tagsText, coverUrl: form.coverUrl,
    codes: ft === 'fixed' ? [] : normalizeInventoryItems(form.inventoryItems),
    fulfillmentType: ft,
    fixedContent: ft === 'fixed' ? (form.fixedContent || '').trim() : '',
    screenshotUrls: normalizeScreenshotUrls(form.screenshotUrls),
    description: form.description, active: form.active, requireLogin: form.requireLogin,
    maxPerAccount: form.maxPerAccount || 0, deliveryMode: form.deliveryMode || 'auto',
    showNote: form.showNote, showContact: form.showContact
  })
}
</script>
