import { useState, type KeyboardEvent } from "react"
import type { AppConfig, ConfigSecretId } from "@qjclaw/shared-types"
import { Tabs, type TabItem } from "../../components/ui/Tabs"

type SetDraft = (value: string) => void
type SettingsActionHandler = () => void | boolean | Promise<void | boolean>
type SecretRevealState = Partial<Record<ConfigSecretId, boolean>>
type SecretValueState = Partial<Record<ConfigSecretId, string>>

interface SettingsDrafts {
  lobsterKey: string
  xhsFeishuAppId: string
  xhsFeishuAppSecret: string
  xhsFeishuAppToken: string
  xhsFeishuTableId: string
  copywritingModelBaseUrl: string
  copywritingModelModelId: string
  copywritingModelApiKey: string
  imageModelBaseUrl: string
  imageModelModelId: string
  imageModelApiKey: string
  videoModelBaseUrl: string
  videoModelModelId: string
  videoModelApiKey: string
  digitalHumanVolcAccessKey: string
  digitalHumanVolcSecretKey: string
  digitalHumanQiniuAccessKey: string
  digitalHumanQiniuSecretKey: string
  videoAnalyzerBaseUrl: string
  videoAnalyzerModelId: string
  videoAnalyzerApiKey: string
  replicationBriefBaseUrl: string
  replicationBriefModelId: string
  replicationBriefApiKey: string
  vectcutBaseUrl: string
  vectcutFileBaseUrl: string
  vectcutApiKey: string
}

interface SettingsDraftSetters {
  setLobsterKey: SetDraft
  setXhsFeishuAppId: SetDraft
  setXhsFeishuAppSecret: SetDraft
  setXhsFeishuAppToken: SetDraft
  setXhsFeishuTableId: SetDraft
  setCopywritingModelBaseUrl: SetDraft
  setCopywritingModelModelId: SetDraft
  setCopywritingModelApiKey: SetDraft
  setImageModelBaseUrl: SetDraft
  setImageModelModelId: SetDraft
  setImageModelApiKey: SetDraft
  setVideoModelBaseUrl: SetDraft
  setVideoModelModelId: SetDraft
  setVideoModelApiKey: SetDraft
  setDigitalHumanVolcAccessKey: SetDraft
  setDigitalHumanVolcSecretKey: SetDraft
  setDigitalHumanQiniuAccessKey: SetDraft
  setDigitalHumanQiniuSecretKey: SetDraft
  setVideoAnalyzerBaseUrl: SetDraft
  setVideoAnalyzerModelId: SetDraft
  setVideoAnalyzerApiKey: SetDraft
  setReplicationBriefBaseUrl: SetDraft
  setReplicationBriefModelId: SetDraft
  setReplicationBriefApiKey: SetDraft
  setVectcutBaseUrl: SetDraft
  setVectcutFileBaseUrl: SetDraft
  setVectcutApiKey: SetDraft
}

interface SettingsPanelsProps {
  config: AppConfig | null
  workspaceApiKeyConfigured: boolean
  displayedWorkspacePath: string
  saving: boolean
  hasPendingLobsterKey: boolean
  hasPendingWorkspacePathChange: boolean
  hasPendingXhsFeishuConfig: boolean
  hasPendingCopywritingConfig: boolean
  hasPendingImageConfig: boolean
  hasPendingVideoConfig: boolean
  hasPendingDigitalHumanConfig: boolean
  hasPendingDouyinRuntimeConfig: boolean
  labels: {
    export: string
  }
  drafts: SettingsDrafts
  setters: SettingsDraftSetters
  onSaveLobsterKey: SettingsActionHandler
  onSaveXhsFeishuConfig: SettingsActionHandler
  onResetXhsFeishuConfig: SettingsActionHandler
  onSaveCopywritingConfig: SettingsActionHandler
  onResetCopywritingConfig: SettingsActionHandler
  onSaveImageConfig: SettingsActionHandler
  onResetImageConfig: SettingsActionHandler
  onSaveVideoConfig: SettingsActionHandler
  onResetVideoConfig: SettingsActionHandler
  onSaveDigitalHumanConfig: SettingsActionHandler
  onResetDigitalHumanConfig: SettingsActionHandler
  onSaveDouyinRuntimeConfig: SettingsActionHandler
  onResetDouyinRuntimeConfig: SettingsActionHandler
  onRevealSecret: (secretId: ConfigSecretId) => Promise<string | null>
  onConfigSourceChange?: (source: SettingsConfigSource) => void | Promise<void>
  loadCloudConfig?: () => void | Promise<void>
  pickWorkspaceDirectory: () => void | Promise<void>
  exportDiagnostics: () => void | Promise<void>
}

interface SectionActions {
  hasPending: boolean
  onSave: SettingsActionHandler
  onReset: SettingsActionHandler
  className?: string
}

type SettingsTabId = "basic" | "xhsFeishu" | "copywriting" | "image" | "video" | "digitalHuman" | "douyinRuntime"
type EditableSettingsSectionId = "copywriting" | "image" | "video" | "douyinRuntime"
type SettingsConfigSource = "cloud" | "local"
type EditingSettingsSections = Partial<Record<EditableSettingsSectionId, boolean>>

const settingsTabs: TabItem[] = [
  { id: "basic", label: "基础配置" },
  { id: "xhsFeishu", label: "小红书飞书" },
  { id: "copywriting", label: "文案模型" },
  { id: "image", label: "生图模型" },
  { id: "video", label: "视频模型" },
  { id: "digitalHuman", label: "数字人配置" },
  { id: "douyinRuntime", label: "抖音运行时" }
]

function SecretVisibilityIcon({ visible }: { visible: boolean }) {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
      <path d="M2.8 12s3.4-5.8 9.2-5.8 9.2 5.8 9.2 5.8-3.4 5.8-9.2 5.8S2.8 12 2.8 12Z" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M12 9.1a2.9 2.9 0 1 1 0 5.8 2.9 2.9 0 0 1 0-5.8Z" fill="none" stroke="currentColor" strokeWidth="1.7" />
      {visible ? <path d="m4.5 19.5 15-15" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" /> : null}
    </svg>
  )
}

export function SettingsPanels({
  config,
  workspaceApiKeyConfigured,
  displayedWorkspacePath,
  saving,
  hasPendingLobsterKey,
  hasPendingWorkspacePathChange,
  hasPendingXhsFeishuConfig,
  hasPendingCopywritingConfig,
  hasPendingImageConfig,
  hasPendingVideoConfig,
  hasPendingDigitalHumanConfig,
  hasPendingDouyinRuntimeConfig,
  labels,
  drafts,
  setters,
  onSaveLobsterKey,
  onSaveXhsFeishuConfig,
  onResetXhsFeishuConfig,
  onSaveCopywritingConfig,
  onResetCopywritingConfig,
  onSaveImageConfig,
  onResetImageConfig,
  onSaveVideoConfig,
  onResetVideoConfig,
  onSaveDigitalHumanConfig,
  onResetDigitalHumanConfig,
  onSaveDouyinRuntimeConfig,
  onResetDouyinRuntimeConfig,
  onRevealSecret,
  onConfigSourceChange,
  loadCloudConfig,
  pickWorkspaceDirectory,
  exportDiagnostics
}: SettingsPanelsProps) {
  const [activeTab, setActiveTab] = useState<SettingsTabId>("basic")
  const [configSource, setConfigSource] = useState<SettingsConfigSource>("local")
  const [revealedSecrets, setRevealedSecrets] = useState<SecretRevealState>({})
  const [revealedSecretValues, setRevealedSecretValues] = useState<SecretValueState>({})
  const [copiedConfigValue, setCopiedConfigValue] = useState<string | null>(null)
  const [editingSettingsSections, setEditingSettingsSections] = useState<EditingSettingsSections>({})

  const handleConfigSourceChange = (source: SettingsConfigSource) => {
    setConfigSource(source)
    void onConfigSourceChange?.(source)
    if (source === "cloud") {
      void loadCloudConfig?.()
    }
  }

  const renderActions = ({ hasPending, onReset, onSave, className }: SectionActions) => (
    <div className={["settings-actions-row", className].filter(Boolean).join(" ")}>
      <button
        type="button"
        className="settings-action-button settings-action-button-secondary"
        disabled={saving || !hasPending}
        onClick={() => void onReset()}
      >
        重置
      </button>
      <button
        type="button"
        className="settings-action-button settings-action-button-primary"
        disabled={saving || !hasPending}
        onClick={() => void onSave()}
      >
        {saving ? "保存中" : "保存"}
      </button>
    </div>
  )

  const renderEditableActions = ({
    sectionId,
    hasPending,
    onReset,
    onSave,
    className
  }: SectionActions & { sectionId: EditableSettingsSectionId }) => {
    const editing = Boolean(editingSettingsSections[sectionId])

    return (
      <div className={["settings-actions-row", className].filter(Boolean).join(" ")}>
        <button
          type="button"
          className="settings-action-button settings-action-button-secondary"
          disabled={saving}
          onClick={() => {
            void onReset()
            setEditingSettingsSections((current) => ({ ...current, [sectionId]: !editing }))
          }}
        >
          {editing ? "取消" : "编辑"}
        </button>
        <button
          type="button"
          className="settings-action-button settings-action-button-primary"
          disabled={saving || !editing || !hasPending}
          onClick={() => {
            void Promise.resolve(onSave()).then((saved) => {
              if (saved !== false) {
                setEditingSettingsSections((current) => ({ ...current, [sectionId]: false }))
              }
            })
          }}
        >
          {saving ? "保存中" : "保存"}
        </button>
      </div>
    )
  }

  const handleSecretRevealToggle = async (secretId: ConfigSecretId, value: string, setValue: SetDraft) => {
    if (revealedSecrets[secretId]) {
      setRevealedSecrets((current) => ({ ...current, [secretId]: false }))
      if (revealedSecretValues[secretId] && value === revealedSecretValues[secretId]) {
        setValue("")
      }
      return
    }

    const secretValue = await onRevealSecret(secretId)
    if (!secretValue) {
      return
    }

    setValue(secretValue)
    setRevealedSecretValues((current) => ({ ...current, [secretId]: secretValue }))
    setRevealedSecrets((current) => ({ ...current, [secretId]: true }))
  }

  const renderSecretInput = ({
    secretId,
    configured,
    label,
    value,
    setValue,
    placeholder,
    inputClassName,
    labelClassName,
    editable = true
  }: {
    secretId: ConfigSecretId
    configured: boolean
    label?: string
    value: string
    setValue: SetDraft
    placeholder: string
    inputClassName?: string
    labelClassName?: string
    editable?: boolean
  }) => {
    const visible = configured && Boolean(revealedSecrets[secretId])
    const secretPlaceholder = configured && !value && !visible ? "••••••••••••" : placeholder
    return (
      <label className={["settings-input-label", labelClassName].filter(Boolean).join(" ")}>
        {label ? <span className="settings-input-label-text">{label}</span> : null}
        <div className={["settings-secret-input-row", configured ? "has-reveal" : ""].filter(Boolean).join(" ")}>
          <input
            className={["settings-secret-value-input", inputClassName].filter(Boolean).join(" ")}
            type={visible ? "text" : "password"}
            value={value}
            title={value || undefined}
            placeholder={secretPlaceholder}
            readOnly={!editable}
            onChange={(event) => {
              if (editable) {
                setValue(event.target.value)
              }
            }}
          />
          {configured ? (
            <button
              type="button"
              className="settings-secret-reveal-button settings-secret-reveal-button-adornment"
              aria-label={visible ? "隐藏密钥" : "显示密钥"}
              title={visible ? "隐藏密钥" : "显示密钥"}
              disabled={saving}
              onClick={() => void handleSecretRevealToggle(secretId, value, setValue)}
            >
              <SecretVisibilityIcon visible={visible} />
            </button>
          ) : null}
        </div>
      </label>
    )
  }

  const copyReadonlyConfigValue = (value?: string) => {
    if (!value) {
      return
    }

    setCopiedConfigValue(value)
    window.setTimeout(() => {
      setCopiedConfigValue((current) => current === value ? null : current)
    }, 1200)

    if (navigator.clipboard) {
      void navigator.clipboard.writeText(value).catch(() => undefined)
    }
  }

  const handleReadonlyConfigKeyDown = (event: KeyboardEvent<HTMLDivElement>, value?: string) => {
    if (event.key !== "Enter" && event.key !== " ") {
      return
    }

    event.preventDefault()
    copyReadonlyConfigValue(value)
  }

  const renderReadonlyConfigValue = (label: string, value?: string) => {
    const copied = Boolean(value && copiedConfigValue === value)

    return (
      <div className="settings-input-label settings-readonly-config-field">
        <span className="settings-input-label-text">{label}</span>
        <div
          className={["settings-readonly-config-value", copied ? "is-copied" : ""].filter(Boolean).join(" ")}
          role="button"
          tabIndex={value ? 0 : -1}
          aria-disabled={!value}
          aria-label={value ? `${label} ${copied ? "已复制" : "复制"}` : label}
          title={copied ? "✅已复制" : value || undefined}
          onClick={() => copyReadonlyConfigValue(value)}
          onKeyDown={(event) => handleReadonlyConfigKeyDown(event, value)}
        >
          <span className="settings-readonly-config-text">{value || "-"}</span>
          {copied ? <span className="settings-readonly-config-copy-feedback">✅已复制</span> : null}
        </div>
      </div>
    )
  }

  const renderEditableConfigValue = (label: string, value: string, setValue: SetDraft, fallbackValue: string | undefined, editing: boolean, placeholder = "") => {
    if (!editing) {
      return renderReadonlyConfigValue(label, value || fallbackValue)
    }

    return (
      <label className="settings-input-label settings-editable-config-field">
        <span className="settings-input-label-text">{label}</span>
        <input
          className="settings-truncated-input"
          type="text"
          value={value}
          title={value || undefined}
          placeholder={placeholder}
          onChange={(event) => setValue(event.target.value)}
        />
      </label>
    )
  }

  const editingCopywritingConfig = Boolean(editingSettingsSections.copywriting)
  const editingImageConfig = Boolean(editingSettingsSections.image)
  const editingVideoConfig = Boolean(editingSettingsSections.video)
  const editingDouyinRuntimeConfig = Boolean(editingSettingsSections.douyinRuntime)

  return (
    <div className="settings-tabs-layout">
      <div className="settings-tabs-toolbar">
        <div className="settings-tabs-row">
          <Tabs
            items={settingsTabs}
            value={activeTab}
            onValueChange={(value) => setActiveTab(value as SettingsTabId)}
            ariaLabel="设置分组"
            className="settings-tabs"
          />
        </div>
        <div className="settings-config-source-toggle" role="group" aria-label="配置来源">
          <button
            type="button"
            className={"settings-config-source-option settings-config-source-option-cloud" + (configSource === "cloud" ? " active" : "")}
            aria-pressed={configSource === "cloud"}
            onClick={() => handleConfigSourceChange("cloud")}
          >
            云端配置
          </button>
          <button
            type="button"
            className={"settings-config-source-option settings-config-source-option-local" + (configSource === "local" ? " active" : "")}
            aria-pressed={configSource === "local"}
            onClick={() => handleConfigSourceChange("local")}
          >
            本地配置
          </button>
        </div>
      </div>

      {activeTab === "basic" ? (
        <section className="panel settings-panel settings-panel-modern settings-panel-basic-config">
          <div className="settings-section-card settings-section-card-compact settings-basic-config-card">
            <div className="settings-basic-config-form">
              <div className="settings-basic-config-row settings-basic-config-row-key">
                {renderSecretInput({
                  secretId: "lobsterKey",
                  configured: workspaceApiKeyConfigured,
                  label: "龙虾密钥",
                  value: drafts.lobsterKey,
                  setValue: setters.setLobsterKey,
                  inputClassName: "settings-truncated-input",
                  labelClassName: "settings-basic-config-field",
                  placeholder: workspaceApiKeyConfigured ? "输入新的龙虾密钥或更新绑定" : "请输入龙虾密钥"
                })}
                <div className="settings-actions-row settings-actions-row-inline-save">
                  <button
                    type="button"
                    className="settings-action-button settings-action-button-primary settings-inline-save-button"
                    disabled={saving || !hasPendingLobsterKey}
                    onClick={() => void onSaveLobsterKey()}
                  >
                    {saving ? "保存中" : "保存"}
                  </button>
                </div>
              </div>

              <div className="settings-basic-config-row settings-basic-config-row-directory">
                <div className="settings-input-label settings-directory-label settings-basic-config-field">
                  <span className="settings-input-label-text">工作目录</span>
                  <div className="workspace-directory-card settings-basic-directory-card">
                    <div className="workspace-directory-panel settings-basic-directory-panel settings-readonly-field">
                      <strong className="workspace-directory-path" title={displayedWorkspacePath}>{displayedWorkspacePath}</strong>
                    </div>
                    {hasPendingWorkspacePathChange ? (
                      <div className="workspace-directory-hint">当前目录已修改。</div>
                    ) : (
                      <div className="workspace-directory-hint">导出诊断不会参与保存状态。</div>
                    )}
                  </div>
                </div>
                <div className="button-row settings-actions-row workspace-directory-actions settings-basic-directory-actions">
                  <button
                    type="button"
                    className="settings-action-button settings-action-button-secondary"
                    disabled={saving || !config}
                    onClick={() => void pickWorkspaceDirectory()}
                  >
                    更改目录
                  </button>
                  <button
                    type="button"
                    className="settings-action-button settings-action-button-secondary"
                    disabled={saving}
                    onClick={() => void exportDiagnostics()}
                  >
                    {labels.export}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </section>
      ) : null}

      {activeTab === "xhsFeishu" ? (
        <section className="panel settings-panel settings-panel-secondary settings-panel-xhs-feishu">
          <div className="settings-section-card settings-section-card-compact-body-actions">
            <div className="settings-xhs-feishu-form">
              <div className="settings-field-grid settings-field-grid-xhs-feishu">
                {renderSecretInput({
                  secretId: "xhsFeishuAppId",
                  configured: Boolean(config?.xhsFeishuConfig.appIdConfigured),
                  label: "FEISHU_APP_ID",
                  value: drafts.xhsFeishuAppId,
                  setValue: setters.setXhsFeishuAppId,
                  placeholder: config?.xhsFeishuConfig.appIdConfigured ? "留空则保持当前已保存密钥" : "请输入 App ID"
                })}
                {renderSecretInput({
                  secretId: "xhsFeishuAppSecret",
                  configured: Boolean(config?.xhsFeishuConfig.appSecretConfigured),
                  label: "FEISHU_APP_SECRET",
                  value: drafts.xhsFeishuAppSecret,
                  setValue: setters.setXhsFeishuAppSecret,
                  placeholder: config?.xhsFeishuConfig.appSecretConfigured ? "留空则保持当前已保存密钥" : "请输入 App Secret"
                })}
                {renderSecretInput({
                  secretId: "xhsFeishuAppToken",
                  configured: Boolean(config?.xhsFeishuConfig.appTokenConfigured),
                  label: "FEISHU_APP_TOKEN",
                  value: drafts.xhsFeishuAppToken,
                  setValue: setters.setXhsFeishuAppToken,
                  placeholder: config?.xhsFeishuConfig.appTokenConfigured ? "留空则保持当前已保存密钥" : "请输入 App Token"
                })}
                {renderSecretInput({
                  secretId: "xhsFeishuTableId",
                  configured: Boolean(config?.xhsFeishuConfig.tableIdConfigured),
                  label: "FEISHU_TABLE_ID",
                  value: drafts.xhsFeishuTableId,
                  setValue: setters.setXhsFeishuTableId,
                  placeholder: config?.xhsFeishuConfig.tableIdConfigured ? "留空则保持当前已保存密钥" : "请输入 Table ID"
                })}
              </div>
              {renderActions({
                hasPending: hasPendingXhsFeishuConfig,
                onReset: () => void onResetXhsFeishuConfig(),
                onSave: () => void onSaveXhsFeishuConfig(),
                className: "settings-xhs-feishu-actions"
              })}
            </div>
          </div>
        </section>
      ) : null}

      {activeTab === "copywriting" ? (
        <section className="panel settings-panel settings-panel-models">
          <div className="settings-section-card settings-section-card-models">
            <div className="model-config-grid model-config-grid-single">
              <article className="model-config-card model-config-card-copywriting">
                <div className="model-config-card-head">
                  <div>
                    <p>用于标题、脚本、口播稿与内容润色</p>
                  </div>
                </div>
                <div className="model-config-card-body">
                  <div className="settings-field-grid">
                    {renderEditableConfigValue("base_url", drafts.copywritingModelBaseUrl, setters.setCopywritingModelBaseUrl, config?.expertModelConfig.copywriting.baseUrl, editingCopywritingConfig, "请输入文案模型 base_url")}
                    {renderEditableConfigValue("model_id", drafts.copywritingModelModelId, setters.setCopywritingModelModelId, config?.expertModelConfig.copywriting.modelId, editingCopywritingConfig, "请输入文案模型 model_id")}
                    {renderSecretInput({
                      secretId: "copywritingModelApiKey",
                      configured: Boolean(config?.expertModelConfig.copywriting.apiKeyConfigured),
                      label: "api_key",
                      value: drafts.copywritingModelApiKey,
                      setValue: setters.setCopywritingModelApiKey,
                      placeholder: config?.expertModelConfig.copywriting.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入文案模型 API Key",
                      editable: editingCopywritingConfig
                    })}
                  </div>
                </div>
                {renderEditableActions({
                  sectionId: "copywriting",
                  hasPending: hasPendingCopywritingConfig,
                  onReset: onResetCopywritingConfig,
                  onSave: onSaveCopywritingConfig
                })}
              </article>
            </div>
          </div>
        </section>
      ) : null}

      {activeTab === "image" ? (
        <section className="panel settings-panel settings-panel-models">
          <div className="settings-section-card settings-section-card-models">
            <div className="model-config-grid model-config-grid-single">
              <article className="model-config-card model-config-card-image">
                <div className="model-config-card-head">
                  <div>
                    <p>用于封面草图、画面创意和视觉素材生成</p>
                  </div>
                </div>
                <div className="model-config-card-body">
                  <div className="settings-field-grid">
                    {renderEditableConfigValue("base_url", drafts.imageModelBaseUrl, setters.setImageModelBaseUrl, config?.expertModelConfig.image.baseUrl, editingImageConfig, "请输入生图模型 base_url")}
                    {renderEditableConfigValue("model_id", drafts.imageModelModelId, setters.setImageModelModelId, config?.expertModelConfig.image.modelId, editingImageConfig, "请输入生图模型 model_id")}
                    {renderSecretInput({
                      secretId: "imageModelApiKey",
                      configured: Boolean(config?.expertModelConfig.image.apiKeyConfigured),
                      label: "api_key",
                      value: drafts.imageModelApiKey,
                      setValue: setters.setImageModelApiKey,
                      placeholder: config?.expertModelConfig.image.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入生图模型 API Key",
                      editable: editingImageConfig
                    })}
                  </div>
                </div>
                {renderEditableActions({
                  sectionId: "image",
                  hasPending: hasPendingImageConfig,
                  onReset: onResetImageConfig,
                  onSave: onSaveImageConfig
                })}
              </article>
            </div>
          </div>
        </section>
      ) : null}

      {activeTab === "video" ? (
        <section className="panel settings-panel settings-panel-models">
          <div className="settings-section-card settings-section-card-models">
            <div className="model-config-grid model-config-grid-single">
              <article className="model-config-card model-config-card-video">
                <div className="model-config-card-head">
                  <div>
                    <p>用于纯画面视频生成</p>
                  </div>
                </div>
                <div className="model-config-card-body">
                  <div className="settings-field-grid">
                    {renderEditableConfigValue("base_url", drafts.videoModelBaseUrl, setters.setVideoModelBaseUrl, config?.expertModelConfig.video.baseUrl, editingVideoConfig, "请输入视频模型 base_url")}
                    {renderEditableConfigValue("model_id", drafts.videoModelModelId, setters.setVideoModelModelId, config?.expertModelConfig.video.modelId, editingVideoConfig, "请输入视频模型 model_id")}
                    {renderSecretInput({
                      secretId: "videoModelApiKey",
                      configured: Boolean(config?.expertModelConfig.video.apiKeyConfigured),
                      label: "api_key",
                      value: drafts.videoModelApiKey,
                      setValue: setters.setVideoModelApiKey,
                      placeholder: config?.expertModelConfig.video.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入视频模型 API Key",
                      editable: editingVideoConfig
                    })}
                  </div>
                </div>
                {renderEditableActions({
                  sectionId: "video",
                  hasPending: hasPendingVideoConfig,
                  onReset: onResetVideoConfig,
                  onSave: onSaveVideoConfig
                })}
              </article>
            </div>
          </div>
        </section>
      ) : null}

      {activeTab === "digitalHuman" ? (
        <section className="panel settings-panel settings-panel-models">
          <div className="settings-section-card settings-section-card-models">
            <div className="model-config-grid model-config-grid-single">
              <article className="model-config-card model-config-card-digital-human">
                <div className="model-config-card-head">
                  <div>
                    <p>用于数字人口播视频，火山与七牛的四个 Key</p>
                  </div>
                </div>
                <div className="model-config-card-body model-config-card-body-digital-human">
                  <div className="settings-field-grid settings-field-grid-digital-human">
                    {renderSecretInput({
                      secretId: "digitalHumanVolcAccessKey",
                      configured: Boolean(config?.expertModelConfig.digitalHuman.volcAccessKeyConfigured),
                      label: "VOLC_ACCESS_KEY",
                      value: drafts.digitalHumanVolcAccessKey,
                      setValue: setters.setDigitalHumanVolcAccessKey,
                      placeholder: config?.expertModelConfig.digitalHuman.volcAccessKeyConfigured ? "留空则保持当前已保存密钥" : "请输入火山 ACCESS_KEY"
                    })}
                    {renderSecretInput({
                      secretId: "digitalHumanVolcSecretKey",
                      configured: Boolean(config?.expertModelConfig.digitalHuman.volcSecretKeyConfigured),
                      label: "VOLC_SECRET_KEY",
                      value: drafts.digitalHumanVolcSecretKey,
                      setValue: setters.setDigitalHumanVolcSecretKey,
                      placeholder: config?.expertModelConfig.digitalHuman.volcSecretKeyConfigured ? "留空则保持当前已保存密钥" : "请输入火山 SECRET_KEY"
                    })}
                    {renderSecretInput({
                      secretId: "digitalHumanQiniuAccessKey",
                      configured: Boolean(config?.expertModelConfig.digitalHuman.qiniuAccessKeyConfigured),
                      label: "QINIU_ACCESS_KEY",
                      value: drafts.digitalHumanQiniuAccessKey,
                      setValue: setters.setDigitalHumanQiniuAccessKey,
                      placeholder: config?.expertModelConfig.digitalHuman.qiniuAccessKeyConfigured ? "留空则保持当前已保存密钥" : "请输入七牛 ACCESS_KEY"
                    })}
                    {renderSecretInput({
                      secretId: "digitalHumanQiniuSecretKey",
                      configured: Boolean(config?.expertModelConfig.digitalHuman.qiniuSecretKeyConfigured),
                      label: "QINIU_SECRET_KEY",
                      value: drafts.digitalHumanQiniuSecretKey,
                      setValue: setters.setDigitalHumanQiniuSecretKey,
                      placeholder: config?.expertModelConfig.digitalHuman.qiniuSecretKeyConfigured ? "留空则保持当前已保存密钥" : "请输入七牛 SECRET_KEY"
                    })}
                  </div>
                </div>
                {renderActions({
                  hasPending: hasPendingDigitalHumanConfig,
                  onReset: () => void onResetDigitalHumanConfig(),
                  onSave: () => void onSaveDigitalHumanConfig()
                })}
              </article>
            </div>
          </div>
        </section>
      ) : null}

      {activeTab === "douyinRuntime" ? (
        <section className="panel settings-panel settings-panel-models">
          <div className="settings-section-card settings-section-card-models">
            <div className="model-config-grid model-config-grid-four model-config-grid-runtime">
              <article className="model-config-card model-config-card-video-analyzer" aria-label="Video Analyzer">
                <div className="model-config-card-head">
                  <div>
                    <p>用于抖音样本分析阶段。</p>
                  </div>
                </div>
                <div className="model-config-card-body">
                  <div className="settings-field-grid">
                    {renderEditableConfigValue("base_url", drafts.videoAnalyzerBaseUrl, setters.setVideoAnalyzerBaseUrl, config?.douyinRuntimeConfig.videoAnalyzer.baseUrl, editingDouyinRuntimeConfig, "请输入 Video Analyzer base_url")}
                    {renderEditableConfigValue("model_id", drafts.videoAnalyzerModelId, setters.setVideoAnalyzerModelId, config?.douyinRuntimeConfig.videoAnalyzer.modelId || "doubao-vision", editingDouyinRuntimeConfig, "请输入 Video Analyzer model_id")}
                    {renderSecretInput({
                      secretId: "videoAnalyzerApiKey",
                      configured: Boolean(config?.douyinRuntimeConfig.videoAnalyzer.apiKeyConfigured),
                      label: "api_key",
                      value: drafts.videoAnalyzerApiKey,
                      setValue: setters.setVideoAnalyzerApiKey,
                      placeholder: config?.douyinRuntimeConfig.videoAnalyzer.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入 Video Analyzer API Key",
                      editable: editingDouyinRuntimeConfig
                    })}
                  </div>
                </div>
              </article>
              <article className="model-config-card model-config-card-replication-brief" aria-label="Replication Brief">
                <div className="model-config-card-head">
                  <div>
                    <p>用于抖音 brief 生成阶段。</p>
                  </div>
                </div>
                <div className="model-config-card-body">
                  <div className="settings-field-grid">
                    {renderEditableConfigValue("base_url", drafts.replicationBriefBaseUrl, setters.setReplicationBriefBaseUrl, config?.douyinRuntimeConfig.replicationBrief.baseUrl, editingDouyinRuntimeConfig, "请输入 Replication Brief base_url")}
                    {renderEditableConfigValue("model_id", drafts.replicationBriefModelId, setters.setReplicationBriefModelId, config?.douyinRuntimeConfig.replicationBrief.modelId || "qwen-max", editingDouyinRuntimeConfig, "请输入 Replication Brief model_id")}
                    {renderSecretInput({
                      secretId: "replicationBriefApiKey",
                      configured: Boolean(config?.douyinRuntimeConfig.replicationBrief.apiKeyConfigured),
                      label: "api_key",
                      value: drafts.replicationBriefApiKey,
                      setValue: setters.setReplicationBriefApiKey,
                      placeholder: config?.douyinRuntimeConfig.replicationBrief.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入 Replication Brief API Key",
                      editable: editingDouyinRuntimeConfig
                    })}
                  </div>
                </div>
              </article>
              <article className="model-config-card model-config-card-vectcut" aria-label="VectCut">
                <div className="model-config-card-head">
                  <div>
                    <p>用于抖音后处理剪辑阶段。</p>
                  </div>
                </div>
                <div className="model-config-card-body">
                  <div className="settings-field-grid">
                    {renderEditableConfigValue("base_url", drafts.vectcutBaseUrl, setters.setVectcutBaseUrl, config?.douyinRuntimeConfig.vectcut.baseUrl, editingDouyinRuntimeConfig, "请输入 VectCut base_url")}
                    {renderEditableConfigValue("file_base_url", drafts.vectcutFileBaseUrl, setters.setVectcutFileBaseUrl, config?.douyinRuntimeConfig.vectcut.fileBaseUrl, editingDouyinRuntimeConfig, "请输入 VectCut file_base_url")}
                    {renderSecretInput({
                      secretId: "vectcutApiKey",
                      configured: Boolean(config?.douyinRuntimeConfig.vectcut.apiKeyConfigured),
                      label: "api_key",
                      value: drafts.vectcutApiKey,
                      setValue: setters.setVectcutApiKey,
                      placeholder: config?.douyinRuntimeConfig.vectcut.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入 VectCut API Key",
                      editable: editingDouyinRuntimeConfig
                    })}
                  </div>
                </div>
              </article>
              <div className="settings-runtime-actions-panel">
                {renderEditableActions({
                  sectionId: "douyinRuntime",
                  hasPending: hasPendingDouyinRuntimeConfig,
                  onReset: onResetDouyinRuntimeConfig,
                  onSave: onSaveDouyinRuntimeConfig,
                  className: "settings-runtime-actions"
                })}
              </div>
            </div>
          </div>
        </section>
      ) : null}
    </div>
  )
}
