import {useEffect, useRef, useState} from 'react'
import {useNavigate, useSearchParams} from 'react-router-dom'
import Navbar from '../components/Navbar'
import {Book, Code2, Download, Edit, FileJson, FileUp, Image as ImageIcon, Layout, Plus, Search, Trash2, X} from 'lucide-react'
import {type Character, characterApi, extractFrontendCard} from '../api/character'
import {type RegexScript, regexScriptApi} from '../api/regex'
// import {useAppStore} from '../store'

interface WorldBookEntry {
  keys: string[]
  content: string
  enabled: boolean
  insertion_order: number
  case_sensitive?: boolean
  name?: string
  priority?: number
  id?: number
  comment?: string
  selective?: boolean
  secondary_keys?: string[]
  constant?: boolean
  position?: 'before_char' | 'after_char'
}

export default function CharacterManagePage() {
  const [characters, setCharacters] = useState<Character[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [showUploadModal, setShowUploadModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [selectedCharacter, setSelectedCharacter] = useState<Character | null>(null)
  const [loading, setLoading] = useState(true)
  const [uploading, setUploading] = useState(false)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [showWorldBookEditor, setShowWorldBookEditor] = useState(false)
  const [worldBookEntries, setWorldBookEntries] = useState<WorldBookEntry[]>([])
  const [showRegexScriptEditor, setShowRegexScriptEditor] = useState(false)
  const [regexScripts, setRegexScripts] = useState<RegexScript[]>([])
  const [_editingTab, _setEditingTab] = useState<'basic' | 'worldbook' | 'regex'>('basic')
  // 前端卡编辑器
  const [showFrontendCardEditor, setShowFrontendCardEditor] = useState(false)
  const [frontendCardHtml, setFrontendCardHtml] = useState('')
  const [frontendCardEnabled, setFrontendCardEnabled] = useState(true)
  const [frontendCardPosition, setFrontendCardPosition] = useState<'top' | 'bottom'>('top')
  const [showFrontendCardPreview, setShowFrontendCardPreview] = useState(false)
  const frontendCardPreviewRef = useRef<HTMLIFrameElement>(null)
  const [showAddRegexModal, setShowAddRegexModal] = useState(false)
  const [newRegexForm, setNewRegexForm] = useState({
    name: '',
    findRegex: '',
    replaceWith: '',
    placement: 1,
    order: 100,
  })
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()

  useEffect(() => {
    loadCharacters()
  }, [page, searchQuery])

  useEffect(() => {
    const editId = searchParams.get('edit')
    if (editId && characters.length > 0) {
      const char = characters.find(c => c.id === parseInt(editId))
      if (char) {
        setSelectedCharacter(char)
        setShowEditModal(true)
        loadWorldBook(char)
        loadRegexScripts(char.id)
        loadFrontendCard(char)
      }
    }
  }, [searchParams, characters])

  const loadFrontendCard = (character: Character) => {
    const fc = extractFrontendCard(character.extensions)
    if (fc) {
      setFrontendCardHtml(fc.html)
      setFrontendCardEnabled(fc.enabled !== false)
      setFrontendCardPosition(fc.position === 'bottom' ? 'bottom' : 'top')
    } else {
      setFrontendCardHtml('')
      setFrontendCardEnabled(true)
      setFrontendCardPosition('top')
    }
  }

  const loadWorldBook = (character: Character) => {
    if (!character.characterBook) {
      setWorldBookEntries([])
      return
    }
    try {
      const book = typeof character.characterBook === 'string'
        ? JSON.parse(character.characterBook)
        : character.characterBook
      setWorldBookEntries(book.entries || [])
    } catch {
      setWorldBookEntries([])
    }
  }

  const loadRegexScripts = async (characterId: number) => {
    try {
      const response = await regexScriptApi.getList({
        scope: 1,
        pageSize: 100,
      })
      console.log('正则脚本 API 响应:', response)

      // apiClient 拦截器返回 response.data，所以这里的 response 就是后端的完整响应
      // 后端返回: {code: 0, data: {list: [...], total: 10, ...}, msg: '获取成功'}
      let list = []
      if (response.data && response.data.list && Array.isArray(response.data.list)) {
        // response.data.list 是正确的路径
        list = response.data.list
      } else {
        console.warn('正则脚本列表数据格式不正确:', response)
        setRegexScripts([])
        return
      }

      const charScripts = list.filter((s: any) => s.ownerCharId === characterId)
      console.log(`找到 ${charScripts.length} 个角色关联的正则脚本`)
      setRegexScripts(charScripts)
    } catch (err) {
      console.error('加载正则脚本失败:', err)
      setRegexScripts([])
    }
  }

  const loadCharacters = async () => {
    try {
      setLoading(true)
      const response = await characterApi.getCharacterList({
        page,
        pageSize: 20,
        keyword: searchQuery || undefined,
      })
      setCharacters(response.data.list)
      setTotal(response.data.total)
    } catch (err: any) {
      console.error('获取角色卡列表失败:', err)
      if (err.response?.status === 401) {
        navigate('/login')
      }
    } finally {
      setLoading(false)
    }
  }

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    try {
      setUploading(true)
      await characterApi.uploadCharacter(file)
      setShowUploadModal(false)
      loadCharacters()
      alert('上传成功！')
    } catch (err: any) {
      console.error('上传角色卡失败:', err)
      alert(err.response?.data?.msg || '上传失败，请重试')
    } finally {
      setUploading(false)
    }
  }

  const handleExport = async (character: Character) => {
    try {
      const response = await characterApi.exportCharacter(character.id)
      const blob = new Blob([response.data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${character.name}.json`
      a.click()
      URL.revokeObjectURL(url)
    } catch (err) {
      console.error('导出角色卡失败:', err)
      alert('导出失败，请重试')
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个角色卡吗？')) return

    try {
      await characterApi.deleteCharacter(id)
      loadCharacters()
      alert('删除成功！')
    } catch (err: any) {
      console.error('删除角色卡失败:', err)
      alert(err.response?.data?.msg || '删除失败，请重试')
    }
  }

  const handleSaveEdit = async () => {
    if (!selectedCharacter) return

    const formData = new FormData(document.getElementById('edit-form') as HTMLFormElement)

    // 构建世界书数据
    const characterBook = worldBookEntries.length > 0 ? {
      name: selectedCharacter.name + ' 的世界书',
      entries: worldBookEntries
    } : null

    // 构建 extensions：保留原有字段，写入/清除前端卡
    const baseExtensions: Record<string, any> = {
      ...(selectedCharacter.extensions || {}),
    }
    if (frontendCardHtml.trim()) {
      baseExtensions['frontend_card'] = {
        html: frontendCardHtml,
        enabled: frontendCardEnabled,
        position: frontendCardPosition,
      }
    } else {
      // HTML 清空则删除前端卡
      delete baseExtensions['frontend_card']
      delete baseExtensions['chara_card_ui']
    }

    const updateData = {
      name: formData.get('name') as string,
      description: formData.get('description') as string,
      personality: formData.get('personality') as string,
      scenario: formData.get('scenario') as string,
      firstMes: formData.get('firstMes') as string,
      mesExample: formData.get('mesExample') as string,
      systemPrompt: formData.get('systemPrompt') as string,
      tags: (formData.get('tags') as string).split(',').map(t => t.trim()).filter(Boolean),
      isPublic: formData.get('isPublic') === 'on',
      characterBook: characterBook,
      extensions: baseExtensions,
    }

    try {
      await characterApi.updateCharacter(selectedCharacter.id, updateData)
      setShowEditModal(false)
      setShowWorldBookEditor(false)
      loadCharacters()
      alert('保存成功！')
    } catch (err: any) {
      console.error('更新角色卡失败:', err)
      alert(err.response?.data?.msg || '保存失败，请重试')
    }
  }

  const addWorldBookEntry = () => {
    setWorldBookEntries([...worldBookEntries, {
      keys: [],
      content: '',
      comment: '',
      enabled: true,
      insertion_order: worldBookEntries.length,
      position: 'after_char'
    }])
  }

  const updateWorldBookEntry = (index: number, field: keyof WorldBookEntry, value: any) => {
    const newEntries = [...worldBookEntries]
    newEntries[index] = { ...newEntries[index], [field]: value }
    setWorldBookEntries(newEntries)
  }

  const deleteWorldBookEntry = (index: number) => {
    setWorldBookEntries(worldBookEntries.filter((_, i) => i !== index))
  }

  const getWorldBookEntryCount = (character: Character) => {
    if (!character.characterBook) return 0
    try {
      const book = typeof character.characterBook === 'string'
        ? JSON.parse(character.characterBook)
        : character.characterBook
      return book.entries?.length || 0
    } catch {
      return 0
    }
  }

  if (loading && characters.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F] flex items-center justify-center">
        <div className="text-white">加载中...</div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F]">
      <Navbar />

      <div className="pt-32 pb-20 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="flex items-center justify-between mb-8">
            <div>
              <h1 className="text-4xl font-bold mb-2">角色卡管理</h1>
              <p className="text-white/60">管理和编辑你的角色卡</p>
            </div>
            <button
              onClick={() => setShowUploadModal(true)}
              className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer flex items-center gap-2"
            >
              <Plus className="w-5 h-5" />
              添加角色卡
            </button>
          </div>

          <div className="glass rounded-2xl p-6 mb-8">
            <div className="flex gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/40" />
                <input
                  type="text"
                  placeholder="搜索角色名称或描述..."
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value)
                    setPage(1)
                  }}
                  className="w-full pl-12 pr-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                />
              </div>
            </div>
          </div>

          {characters.length === 0 ? (
            <div className="glass rounded-2xl p-12 text-center">
              <p className="text-white/60 mb-4">还没有角色卡</p>
              <button
                onClick={() => setShowUploadModal(true)}
                className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer"
              >
                上传第一个角色卡
              </button>
            </div>
          ) : (
            <>
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                {characters.map((char) => {
                  const worldBookCount = getWorldBookEntryCount(char)
                  return (
                    <div
                      key={char.id}
                      className="glass-hover rounded-2xl overflow-hidden cursor-pointer"
                      onClick={() => navigate(`/my-character/${char.id}`)}
                    >
                      <div className="relative h-48 bg-gradient-to-br from-primary/20 to-secondary/20">
                        {char.avatar ? (
                          <img src={char.avatar} alt={char.name} className="w-full h-full object-cover" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center text-6xl">
                            👤
                          </div>
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-[#0A0A0F] to-transparent" />
                        {worldBookCount > 0 && (
                          <div className="absolute top-3 right-3 px-2 py-1 glass rounded-lg flex items-center gap-1 text-xs">
                            <Book className="w-3 h-3" />
                            {worldBookCount}
                          </div>
                        )}
                      </div>

                      <div className="p-4">
                        <h3 className="text-lg font-semibold mb-1 truncate">{char.name}</h3>
                        <p className="text-sm text-white/60 mb-3">{char.creator || '未知作者'}</p>

                        {char.tags && char.tags.length > 0 && (
                          <div className="flex flex-wrap gap-1 mb-3">
                            {char.tags.slice(0, 3).map((tag, i) => (
                              <span key={i} className="text-xs px-2 py-1 bg-primary/20 text-primary rounded">
                                {tag}
                              </span>
                            ))}
                          </div>
                        )}

                        <p className="text-sm text-white/60 mb-4 line-clamp-2">
                          {char.description || '暂无描述'}
                        </p>

                        <div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
                          <button
                            onClick={() => {
                              setSelectedCharacter(char)
                              setShowEditModal(true)
                              loadWorldBook(char)
                              loadRegexScripts(char.id)
                              loadFrontendCard(char)
                            }}
                            className="flex-1 px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer flex items-center justify-center gap-2"
                          >
                            <Edit className="w-4 h-4" />
                            编辑
                          </button>
                          <button
                            onClick={() => handleExport(char)}
                            className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer"
                          >
                            <Download className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleDelete(char.id)}
                            className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer text-red-400"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>

              {total > 20 && (
                <div className="flex justify-center gap-2 mt-8">
                  <button
                    onClick={() => setPage(p => Math.max(1, p - 1))}
                    disabled={page === 1}
                    className="px-4 py-2 glass-hover rounded-lg cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    上一页
                  </button>
                  <span className="px-4 py-2 glass rounded-lg">
                    {page} / {Math.ceil(total / 20)}
                  </span>
                  <button
                    onClick={() => setPage(p => p + 1)}
                    disabled={page >= Math.ceil(total / 20)}
                    className="px-4 py-2 glass-hover rounded-lg cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    下一页
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {showUploadModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-8 max-w-md w-full">
            <h2 className="text-2xl font-bold mb-6">上传角色卡</h2>

            <div className="space-y-4">
              <div>
                <label className="block text-sm text-white/80 mb-2">PNG 角色卡</label>
                <label className="glass-hover rounded-xl p-6 border-2 border-dashed border-white/20 cursor-pointer block text-center">
                  <ImageIcon className="w-8 h-8 mx-auto mb-2 text-white/40" />
                  <span className="text-sm text-white/60">
                    {uploading ? '上传中...' : '点击上传 PNG 格式角色卡'}
                  </span>
                  <input
                    type="file"
                    accept=".png"
                    onChange={handleFileUpload}
                    disabled={uploading}
                    className="hidden"
                  />
                </label>
              </div>

              <div className="text-center text-white/40 text-sm">或</div>

              <div>
                <label className="block text-sm text-white/80 mb-2">JSON 角色卡</label>
                <label className="glass-hover rounded-xl p-6 border-2 border-dashed border-white/20 cursor-pointer block text-center">
                  <FileJson className="w-8 h-8 mx-auto mb-2 text-white/40" />
                  <span className="text-sm text-white/60">
                    {uploading ? '上传中...' : '点击上传 JSON 格式角色卡'}
                  </span>
                  <input
                    type="file"
                    accept=".json"
                    onChange={handleFileUpload}
                    disabled={uploading}
                    className="hidden"
                  />
                </label>
              </div>
            </div>

            <button
              onClick={() => setShowUploadModal(false)}
              disabled={uploading}
              className="w-full mt-6 px-6 py-3 glass-hover rounded-xl cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
            >
              取消
            </button>
          </div>
        </div>
      )}

      {showEditModal && selectedCharacter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4 overflow-y-auto">
          <div className="glass rounded-3xl p-8 max-w-2xl w-full my-8">
            <h2 className="text-2xl font-bold mb-6">编辑角色卡</h2>

            <form id="edit-form" className="space-y-4 max-h-[60vh] overflow-y-auto pr-2">
              <div>
                <label className="text-sm text-white/80 mb-2 block">角色名称</label>
                <input
                  type="text"
                  name="name"
                  defaultValue={selectedCharacter.name}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">角色描述</label>
                <textarea
                  name="description"
                  rows={3}
                  defaultValue={selectedCharacter.description}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">性格特征</label>
                <textarea
                  name="personality"
                  rows={3}
                  defaultValue={selectedCharacter.personality}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">场景设定</label>
                <textarea
                  name="scenario"
                  rows={3}
                  defaultValue={selectedCharacter.scenario}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">第一条消息</label>
                <textarea
                  name="firstMes"
                  rows={3}
                  defaultValue={selectedCharacter.firstMes}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">示例对话</label>
                <textarea
                  name="mesExample"
                  rows={4}
                  defaultValue={selectedCharacter.mesExample}
                  placeholder="<START>&#10;{{user}}: 你好&#10;{{char}}: 你好！很高兴见到你。"
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">系统提示词</label>
                <textarea
                  name="systemPrompt"
                  rows={3}
                  defaultValue={selectedCharacter.systemPrompt}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                />
              </div>

              <div>
                <label className="text-sm text-white/80 mb-2 block">标签（逗号分隔）</label>
                <input
                  type="text"
                  name="tags"
                  defaultValue={selectedCharacter.tags?.join(', ')}
                  className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                />
              </div>

              <div>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    name="isPublic"
                    defaultChecked={selectedCharacter.isPublic}
                    className="w-4 h-4 cursor-pointer"
                  />
                  <span className="text-sm text-white/80">公开到角色广场</span>
                </label>
                <p className="text-xs text-white/40 mt-1">公开后其他用户可以在角色广场看到并使用此角色卡</p>
              </div>

              <div className="grid grid-cols-3 gap-3">
                <button
                  type="button"
                  onClick={() => setShowWorldBookEditor(true)}
                  className="px-4 py-3 glass-hover rounded-xl text-sm cursor-pointer flex items-center justify-center gap-2"
                >
                  <Book className="w-4 h-4" />
                  世界书 ({getWorldBookEntryCount(selectedCharacter)})
                </button>
                <button
                  type="button"
                  onClick={() => setShowRegexScriptEditor(true)}
                  className="px-4 py-3 glass-hover rounded-xl text-sm cursor-pointer flex items-center justify-center gap-2"
                >
                  <Code2 className="w-4 h-4" />
                  正则脚本 ({regexScripts.length})
                </button>
                <button
                  type="button"
                  onClick={() => setShowFrontendCardEditor(true)}
                  className={`px-4 py-3 rounded-xl text-sm cursor-pointer flex items-center justify-center gap-2 ${
                    frontendCardHtml.trim()
                      ? 'bg-primary/20 border border-primary/40 text-primary'
                      : 'glass-hover'
                  }`}
                >
                  <Layout className="w-4 h-4" />
                  前端卡{frontendCardHtml.trim() ? ' ✓' : ''}
                </button>
              </div>
            </form>

            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowEditModal(false)}
                className="flex-1 px-6 py-3 glass-hover rounded-xl cursor-pointer"
              >
                取消
              </button>
              <button
                onClick={handleSaveEdit}
                className="flex-1 px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer"
              >
                保存
              </button>
            </div>
          </div>
        </div>
      )}

      {showWorldBookEditor && selectedCharacter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-8 max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold">编辑世界书</h2>
              <button
                onClick={() => setShowWorldBookEditor(false)}
                className="p-2 glass-hover rounded-lg cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto pr-2 space-y-4">
              {worldBookEntries.length === 0 ? (
                <div className="glass rounded-xl p-8 text-center">
                  <Book className="w-12 h-12 mx-auto mb-3 text-white/40" />
                  <p className="text-white/60 mb-4">还没有世界书条目</p>
                  <button
                    onClick={addWorldBookEntry}
                    className="px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-lg text-sm cursor-pointer"
                  >
                    添加第一个条目
                  </button>
                </div>
              ) : (
                worldBookEntries.map((entry, index) => (
                  <div key={index} className="glass rounded-xl p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex-1">
                        <span className="text-sm font-medium">
                          {entry.comment ? entry.comment : `条目 #${index + 1}`}
                        </span>
                        {entry.comment && (
                          <span className="text-xs text-white/40 ml-2">#{index + 1}</span>
                        )}
                      </div>
                      <div className="flex items-center gap-2">
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={entry.enabled}
                            onChange={(e) => updateWorldBookEntry(index, 'enabled', e.target.checked)}
                            className="cursor-pointer"
                          />
                          <span className="text-xs text-white/60">启用</span>
                        </label>
                        <button
                          onClick={() => deleteWorldBookEntry(index)}
                          className="p-1 glass-hover rounded text-red-400 cursor-pointer"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>

                    <div className="space-y-3">
                      <div>
                        <label className="text-xs text-white/60 mb-1 block">条目标题</label>
                        <input
                          type="text"
                          value={entry.comment || ''}
                          onChange={(e) => updateWorldBookEntry(index, 'comment', e.target.value)}
                          placeholder="例如: 魔法系统设定"
                          className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                        />
                      </div>

                      <div>
                        <label className="text-xs text-white/60 mb-1 block">触发关键词（逗号分隔）</label>
                        <input
                          type="text"
                          value={entry.keys.join(', ')}
                          onChange={(e) => updateWorldBookEntry(index, 'keys', e.target.value.split(',').map(k => k.trim()).filter(Boolean))}
                          placeholder="例如: 魔法, 咒语, 法术"
                          className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                        />
                      </div>

                      <div>
                        <label className="text-xs text-white/60 mb-1 block">内容</label>
                        <textarea
                          value={entry.content}
                          onChange={(e) => updateWorldBookEntry(index, 'content', e.target.value)}
                          placeholder="当触发关键词时，这段内容会被添加到对话上下文中..."
                          rows={3}
                          className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                        />
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="text-xs text-white/60 mb-1 block">插入位置</label>
                          <select
                            value={entry.position || 'after_char'}
                            onChange={(e) => updateWorldBookEntry(index, 'position', e.target.value)}
                            className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                          >
                            <option value="before_char">角色描述之前</option>
                            <option value="after_char">角色描述之后</option>
                          </select>
                        </div>

                        <div>
                          <label className="text-xs text-white/60 mb-1 block">插入顺序</label>
                          <input
                            type="number"
                            value={entry.insertion_order}
                            onChange={(e) => updateWorldBookEntry(index, 'insertion_order', parseInt(e.target.value))}
                            className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            <div className="flex gap-3 mt-6 pt-6 border-t border-white/10">
              <button
                onClick={addWorldBookEntry}
                className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                添加条目
              </button>
              <div className="flex-1" />
              <button
                onClick={() => setShowWorldBookEditor(false)}
                className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer"
              >
                取消
              </button>
              <button
                onClick={() => {
                  setShowWorldBookEditor(false)
                  // 世界书数据会在保存角色卡时一起保存
                }}
                className="px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-lg text-sm cursor-pointer"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}

      {showRegexScriptEditor && selectedCharacter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-8 max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold">编辑正则脚本</h2>
              <button
                onClick={() => setShowRegexScriptEditor(false)}
                className="p-2 glass-hover rounded-lg cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto pr-2 space-y-4">
              {regexScripts.length === 0 ? (
                <div className="glass rounded-xl p-8 text-center">
                  <Code2 className="w-12 h-12 mx-auto mb-3 text-white/40" />
                  <p className="text-white/60 mb-4">还没有正则脚本</p>
                  <button
                    onClick={async () => {
                      try {
                        await regexScriptApi.create({
                          name: '新脚本',
                          findRegex: '.*',  // 默认匹配所有内容
                          replaceWith: '',
                          scope: 1,
                          ownerCharId: selectedCharacter.id,
                          disabled: false,
                          placement: 1,  // 默认输出阶段
                          order: 100,
                        })
                        loadRegexScripts(selectedCharacter.id)
                      } catch (err: any) {
                        console.error('创建脚本失败:', err)
                        alert(err.response?.data?.msg || err.message || '创建失败')
                      }
                    }}
                    className="px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-lg text-sm cursor-pointer"
                  >
                    添加第一个脚本
                  </button>
                </div>
              ) : (
                regexScripts.map((script) => (
                  <div key={script.id} className="glass rounded-xl p-4">
                    <div className="flex items-center justify-between mb-3">
                      <input
                        type="text"
                        value={script.name}
                        onChange={(e) => {
                          const newScripts = regexScripts.map(s =>
                            s.id === script.id ? { ...s, name: e.target.value } : s
                          )
                          setRegexScripts(newScripts)
                        }}
                        className="flex-1 px-3 py-2 glass rounded-lg text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/50"
                      />
                      <div className="flex items-center gap-2 ml-3">
                        <label className="flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={!script.disabled}
                            onChange={(e) => {
                              const newScripts = regexScripts.map(s =>
                                s.id === script.id ? { ...s, disabled: !e.target.checked } : s
                              )
                              setRegexScripts(newScripts)
                            }}
                            className="cursor-pointer"
                          />
                          <span className="text-xs text-white/60">启用</span>
                        </label>
                        <button
                          onClick={async () => {
                            if (!confirm('确定要删除这个脚本吗？')) return
                            try {
                              await regexScriptApi.delete(script.id)
                              loadRegexScripts(selectedCharacter.id)
                            } catch (err: any) {
                              alert(err.response?.data?.msg || '删除失败')
                            }
                          }}
                          className="p-1 glass-hover rounded text-red-400 cursor-pointer"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>

                    <div className="space-y-3">
                      <div>
                        <label className="text-xs text-white/60 mb-1 block">查找正则表达式</label>
                        <input
                          type="text"
                          value={script.findRegex}
                          onChange={(e) => {
                            const newScripts = regexScripts.map(s =>
                              s.id === script.id ? { ...s, findRegex: e.target.value } : s
                            )
                            setRegexScripts(newScripts)
                          }}
                          placeholder="例如: /\*\*(.+?)\*\*/"
                          className="w-full px-3 py-2 glass rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/50"
                        />
                      </div>

                      <div>
                        <label className="text-xs text-white/60 mb-1 block">替换为</label>
                        <input
                          type="text"
                          value={script.replaceWith}
                          onChange={(e) => {
                            const newScripts = regexScripts.map(s =>
                              s.id === script.id ? { ...s, replaceWith: e.target.value } : s
                            )
                            setRegexScripts(newScripts)
                          }}
                          placeholder="例如: <strong>$1</strong>"
                          className="w-full px-3 py-2 glass rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/50"
                        />
                      </div>

                      <div className="grid grid-cols-3 gap-3">
                        <div>
                          <label className="text-xs text-white/60 mb-1 block">执行阶段</label>
                          <select
                            value={script.placement}
                            onChange={(e) => {
                              const newScripts = regexScripts.map(s =>
                                s.id === script.id ? { ...s, placement: parseInt(e.target.value) } : s
                              )
                              setRegexScripts(newScripts)
                            }}
                            className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                          >
                            <option value="0">输入</option>
                            <option value="1">输出</option>
                            <option value="2">世界书</option>
                            <option value="3">推理</option>
                          </select>
                        </div>

                        <div>
                          <label className="text-xs text-white/60 mb-1 block">执行顺序</label>
                          <input
                            type="number"
                            value={script.order}
                            onChange={(e) => {
                              const newScripts = regexScripts.map(s =>
                                s.id === script.id ? { ...s, order: parseInt(e.target.value) } : s
                              )
                              setRegexScripts(newScripts)
                            }}
                            className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                          />
                        </div>

                        <div className="flex flex-col gap-1 pt-5">
                          <label className="flex items-center gap-2 cursor-pointer text-xs">
                            <input
                              type="checkbox"
                              checked={script.substituteRegex}
                              onChange={(e) => {
                                const newScripts = regexScripts.map(s =>
                                  s.id === script.id ? { ...s, substituteRegex: e.target.checked } : s
                                )
                                setRegexScripts(newScripts)
                              }}
                              className="cursor-pointer"
                            />
                            <span className="text-white/60">替换宏</span>
                          </label>
                        </div>
                      </div>

                      <div className="flex gap-2">
                        <button
                          onClick={async () => {
                            const testInput = prompt('输入测试文本：', '这是一段**测试**文本')
                            if (!testInput) return

                            try {
                              const response = await regexScriptApi.test(script.id, testInput)
                              console.log('测试响应:', response)

                              // 处理响应数据结构
                              const testResult = response.data || response
                              if (testResult.success === false && testResult.error) {
                                alert(`测试失败：${testResult.error}`)
                              } else {
                                alert(`原文：${testResult.original}\n\n结果：${testResult.result}`)
                              }
                            } catch (err: any) {
                              console.error('测试失败:', err)
                              alert(err.response?.data?.msg || err.message || '测试失败')
                            }
                          }}
                          className="px-3 py-1.5 glass-hover rounded-lg text-xs cursor-pointer"
                        >
                          测试
                        </button>
                        <button
                          onClick={async () => {
                            try {
                              await regexScriptApi.update(script.id, {
                                name: script.name,
                                findRegex: script.findRegex,
                                replaceWith: script.replaceWith,
                                placement: script.placement,
                                disabled: script.disabled,
                                order: script.order,
                                substituteRegex: script.substituteRegex,
                              })
                              alert('保存成功')
                            } catch (err: any) {
                              alert(err.response?.data?.msg || '保存失败')
                            }
                          }}
                          className="px-3 py-1.5 bg-gradient-to-r from-primary to-secondary rounded-lg text-xs cursor-pointer"
                        >
                          保存
                        </button>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            <div className="flex gap-3 mt-6 pt-6 border-t border-white/10">
              <button
                onClick={() => setShowAddRegexModal(true)}
                className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                添加脚本
              </button>
              <div className="flex-1" />
              <button
                onClick={() => setShowRegexScriptEditor(false)}
                className="px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-lg text-sm cursor-pointer"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 添加正则脚本弹窗 */}
      {showAddRegexModal && selectedCharacter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-8 max-w-2xl w-full">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold">添加正则脚本</h2>
              <button
                onClick={() => {
                  setShowAddRegexModal(false)
                  setNewRegexForm({
                    name: '',
                    findRegex: '',
                    replaceWith: '',
                    placement: 1,
                    order: 100,
                  })
                }}
                className="p-2 glass-hover rounded-lg cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-6">
              {/* 导入 JSON 文件 */}
              <div>
                <label className="block text-sm text-white/80 mb-2">从 JSON 文件导入</label>
                <label className="glass-hover rounded-xl p-6 border-2 border-dashed border-white/20 cursor-pointer block text-center">
                  <FileUp className="w-8 h-8 mx-auto mb-2 text-white/40" />
                  <span className="text-sm text-white/60">点击选择 JSON 文件</span>
                  <input
                    type="file"
                    accept=".json"
                    onChange={async (e) => {
                      const file = e.target.files?.[0]
                      if (!file) return

                      try {
                        const text = await file.text()
                        const jsonData = JSON.parse(text)

                        // 支持单个脚本或脚本数组
                        const scripts = Array.isArray(jsonData) ? jsonData : [jsonData]

                        for (const scriptData of scripts) {
                          await regexScriptApi.create({
                            name: scriptData.scriptName || scriptData.name || '导入的脚本',
                            findRegex: scriptData.findRegex || '.*',
                            replaceWith: scriptData.replaceString || scriptData.replaceWith || '',
                            placement: scriptData.placement || 1,
                            disabled: scriptData.disabled || false,
                            order: scriptData.order || 100,
                            scope: 1,
                            ownerCharId: selectedCharacter.id,
                            markdownOnly: scriptData.markdownOnly || false,
                            runOnEdit: scriptData.runOnEdit || false,
                            promptOnly: scriptData.promptOnly || false,
                            substituteRegex: scriptData.substituteRegex !== false,
                          })
                        }

                        loadRegexScripts(selectedCharacter.id)
                        setShowAddRegexModal(false)
                        alert(`成功导入 ${scripts.length} 个正则脚本`)
                      } catch (err: any) {
                        console.error('导入失败:', err)
                        alert('导入失败：' + (err.message || '文件格式不正确'))
                      }
                    }}
                    className="hidden"
                  />
                </label>
                <p className="text-xs text-white/40 mt-2">
                  支持 SillyTavern 格式的正则脚本 JSON 文件
                </p>
              </div>

              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-white/10"></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className="px-4 glass text-white/60">或手动创建</span>
                </div>
              </div>

              {/* 手动输入表单 */}
              <div className="space-y-4">
                <div>
                  <label className="text-sm text-white/80 mb-2 block">脚本名称 *</label>
                  <input
                    type="text"
                    value={newRegexForm.name}
                    onChange={(e) => setNewRegexForm({ ...newRegexForm, name: e.target.value })}
                    placeholder="例如: 移除 Markdown 加粗"
                    className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                  />
                </div>

                <div>
                  <label className="text-sm text-white/80 mb-2 block">查找正则表达式 *</label>
                  <input
                    type="text"
                    value={newRegexForm.findRegex}
                    onChange={(e) => setNewRegexForm({ ...newRegexForm, findRegex: e.target.value })}
                    placeholder="例如: \*\*(.+?)\*\*"
                    className="w-full px-4 py-3 glass rounded-xl text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/50"
                  />
                </div>

                <div>
                  <label className="text-sm text-white/80 mb-2 block">替换为</label>
                  <input
                    type="text"
                    value={newRegexForm.replaceWith}
                    onChange={(e) => setNewRegexForm({ ...newRegexForm, replaceWith: e.target.value })}
                    placeholder="例如: <strong>$1</strong>"
                    className="w-full px-4 py-3 glass rounded-xl text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/50"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm text-white/80 mb-2 block">执行阶段</label>
                    <select
                      value={newRegexForm.placement}
                      onChange={(e) => setNewRegexForm({ ...newRegexForm, placement: parseInt(e.target.value) })}
                      className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    >
                      <option value="0">输入</option>
                      <option value="1">输出</option>
                      <option value="2">世界书</option>
                      <option value="3">推理</option>
                    </select>
                  </div>

                  <div>
                    <label className="text-sm text-white/80 mb-2 block">执行顺序</label>
                    <input
                      type="number"
                      value={newRegexForm.order}
                      onChange={(e) => setNewRegexForm({ ...newRegexForm, order: parseInt(e.target.value) })}
                      className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    />
                  </div>
                </div>
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  onClick={() => {
                    setShowAddRegexModal(false)
                    setNewRegexForm({
                      name: '',
                      findRegex: '',
                      replaceWith: '',
                      placement: 1,
                      order: 100,
                    })
                  }}
                  className="flex-1 px-6 py-3 glass-hover rounded-xl cursor-pointer"
                >
                  取消
                </button>
                <button
                  onClick={async () => {
                    if (!newRegexForm.name.trim()) {
                      alert('请输入脚本名称')
                      return
                    }
                    if (!newRegexForm.findRegex.trim()) {
                      alert('请输入查找正则表达式')
                      return
                    }

                    try {
                      await regexScriptApi.create({
                        name: newRegexForm.name,
                        findRegex: newRegexForm.findRegex,
                        replaceWith: newRegexForm.replaceWith,
                        placement: newRegexForm.placement,
                        order: newRegexForm.order,
                        scope: 1,
                        ownerCharId: selectedCharacter.id,
                        disabled: false,
                        substituteRegex: true,
                      })

                      loadRegexScripts(selectedCharacter.id)
                      setShowAddRegexModal(false)
                      setNewRegexForm({
                        name: '',
                        findRegex: '',
                        replaceWith: '',
                        placement: 1,
                        order: 100,
                      })
                      alert('创建成功')
                    } catch (err: any) {
                      console.error('创建失败:', err)
                      alert(err.response?.data?.msg || err.message || '创建失败')
                    }
                  }}
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer"
                >
                  创建
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 前端卡编辑器弹窗 */}
      {showFrontendCardEditor && selectedCharacter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-8 max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-2xl font-bold flex items-center gap-2">
                  <Layout className="w-6 h-6 text-primary" />
                  前端卡编辑器
                </h2>
                <p className="text-sm text-white/50 mt-1">
                  存储在角色卡 extensions.frontend_card 中，在聊天界面固定显示的 HTML 面板
                </p>
              </div>
              <button
                onClick={() => { setShowFrontendCardEditor(false); setShowFrontendCardPreview(false) }}
                className="p-2 glass-hover rounded-lg cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* 控制栏 */}
            <div className="flex items-center gap-4 mb-4 flex-shrink-0">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={frontendCardEnabled}
                  onChange={(e) => setFrontendCardEnabled(e.target.checked)}
                  className="w-4 h-4 cursor-pointer"
                />
                <span className="text-sm text-white/80">启用前端卡</span>
              </label>

              <div className="flex items-center gap-2">
                <span className="text-sm text-white/60">显示位置：</span>
                <select
                  value={frontendCardPosition}
                  onChange={(e) => setFrontendCardPosition(e.target.value as 'top' | 'bottom')}
                  className="px-3 py-1.5 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                >
                  <option value="top">消息列表上方</option>
                  <option value="bottom">输入框上方</option>
                </select>
              </div>

              <div className="ml-auto flex items-center gap-2">
                <button
                  onClick={() => setShowFrontendCardPreview(v => !v)}
                  className={`px-4 py-2 rounded-lg text-sm cursor-pointer transition-all ${
                    showFrontendCardPreview
                      ? 'bg-primary/30 text-primary border border-primary/40'
                      : 'glass-hover'
                  }`}
                >
                  {showFrontendCardPreview ? '▶ 隐藏预览' : '▶ 预览'}
                </button>
                <button
                  onClick={() => {
                    setFrontendCardHtml('')
                    setFrontendCardEnabled(true)
                    setFrontendCardPosition('top')
                  }}
                  className="px-4 py-2 glass-hover rounded-lg text-sm text-red-400 cursor-pointer"
                >
                  清空
                </button>
              </div>
            </div>

            {/* 编辑区 + 预览区 */}
            <div className={`flex-1 overflow-hidden flex gap-4 min-h-0 ${showFrontendCardPreview ? 'flex-row' : 'flex-col'}`}>
              {/* 代码编辑器 */}
              <div className={`flex flex-col ${showFrontendCardPreview ? 'w-1/2' : 'flex-1'} min-h-0`}>
                <div className="flex items-center justify-between mb-2">
                  <span className="text-xs text-white/50">HTML / CSS / JS</span>
                  <span className="text-xs text-white/30">{frontendCardHtml.length} 字符</span>
                </div>
                <textarea
                  value={frontendCardHtml}
                  onChange={(e) => setFrontendCardHtml(e.target.value)}
                  placeholder={`<!DOCTYPE html>
<html>
<head>
  <style>
    body { background: transparent; color: white; font-family: sans-serif; }
  </style>
</head>
<body>
  <div id="status-panel">...</div>
  <script>
    // 可以使用 ST 兼容 API：
    // getCurrentMessageId() → 当前消息索引
    // getChatMessages(id) → [{ message: "..." }]
    // window.onPlayerAction(text) → 触发玩家行动
    document.addEventListener('DOMContentLoaded', function() {
      var msg = getChatMessages(getCurrentMessageId());
      document.getElementById('status-panel').textContent = msg[0]?.message || '';
    });
  <\/script>
</body>
</html>`}
                  className="flex-1 w-full px-4 py-3 glass rounded-xl text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none overflow-y-auto"
                  style={{ minHeight: 0 }}
                  spellCheck={false}
                />
              </div>

              {/* 预览区（iframe） */}
              {showFrontendCardPreview && (
                <div className="w-1/2 flex flex-col min-h-0">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-xs text-white/50">预览（沙盒 iframe）</span>
                    <button
                      onClick={() => {
                        if (frontendCardPreviewRef.current) {
                          frontendCardPreviewRef.current.srcdoc = frontendCardHtml
                        }
                      }}
                      className="text-xs px-2 py-1 glass-hover rounded cursor-pointer text-primary"
                    >
                      刷新预览
                    </button>
                  </div>
                  <div className="flex-1 border border-white/10 rounded-xl overflow-hidden bg-black/20">
                    <iframe
                      ref={frontendCardPreviewRef}
                      srcDoc={frontendCardHtml}
                      sandbox="allow-scripts"
                      className="w-full h-full"
                      style={{ border: 'none', minHeight: '300px' }}
                      title="前端卡预览"
                    />
                  </div>
                </div>
              )}
            </div>

            {/* 底部说明 + 保存按钮 */}
            <div className="flex items-start justify-between gap-4 mt-4 flex-shrink-0">
              <div className="text-xs text-white/30 flex-1">
                <p>前端卡在聊天时以 <code className="text-primary/70">sandbox="allow-scripts"</code> 沙盒 iframe 渲染，支持完整 HTML/CSS/JS。</p>
                <p className="mt-0.5">可访问 ST 兼容 API：<code className="text-primary/70">getCurrentMessageId()</code>、<code className="text-primary/70">getChatMessages(id)</code>、<code className="text-primary/70">window.onPlayerAction(text)</code></p>
              </div>
              <button
                onClick={() => setShowFrontendCardEditor(false)}
                className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer flex-shrink-0"
              >
                完成
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
