(function initPromptFiller() {
  "use strict";

  const core = window.PromptFillerCore;
  const LEGACY_STORAGE_KEY = "doudou_diy_ai_prompt_filler_state";
  const STORAGE_KEY = "doudou_diy_ai_prompt_filler_state_v2";

  const els = {
    speciesCapsules: document.getElementById("speciesCapsules"),
    speciesForm: document.getElementById("speciesForm"),
    speciesKeyInput: document.getElementById("speciesKeyInput"),
    speciesLabelInput: document.getElementById("speciesLabelInput"),
    promptCardList: document.getElementById("promptCardList"),
    promptEditorForm: document.getElementById("promptEditorForm"),
    editorHeading: document.getElementById("editorHeading"),
    editorStatusBadge: document.getElementById("editorStatusBadge"),
    selectedFieldTitle: document.getElementById("selectedFieldTitle"),
    selectedFieldKey: document.getElementById("selectedFieldKey"),
    selectedComposition: document.getElementById("selectedComposition"),
    promptEditorText: document.getElementById("promptEditorText"),
    historyList: document.getElementById("historyList"),
    clearFieldButton: document.getElementById("clearFieldButton"),
    copyConfigButton: document.getElementById("copyConfigButton"),
    deleteSpeciesButton: document.getElementById("deleteSpeciesButton"),
    exportConfigButton: document.getElementById("exportConfigButton"),
    exportBackupButton: document.getElementById("exportBackupButton"),
    importButton: document.getElementById("importButton"),
    importFileInput: document.getElementById("importFileInput"),
    toastMessage: document.getElementById("toastMessage"),
  };

  let state = loadState();
  let activeSpecies = state.editor_meta.active_species || firstSpeciesKey();
  let selectedFieldKey = `action_prompts.${activeSpecies}.idle`;
  let toastTimer = 0;
  els.speciesKeyInput.value = "";
  els.speciesLabelInput.value = "";

  function loadState() {
    try {
      localStorage.removeItem(LEGACY_STORAGE_KEY);
    } catch (_error) {
      // Ignore storage cleanup errors; the new storage key still starts blank.
    }
    const saved = localStorage.getItem(STORAGE_KEY);
    if (!saved) return core.createDefaultPromptState();
    try {
      return core.importPromptPayload(JSON.parse(saved));
    } catch (error) {
      console.warn("无法读取本地提示词填写器状态，已创建空白状态。", error);
      return core.createDefaultPromptState();
    }
  }

  function saveState() {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(core.exportEditorBackup(state)));
  }

  function updateSelectedDraft(text) {
    state = core.updatePromptDraft(state, selectedFieldKey, text);
    saveState();
  }

  function refreshSelectedDraftStatus() {
    renderPromptCards();
    const card = fieldCard();
    els.editorStatusBadge.textContent = card.statusLabel;
    els.editorStatusBadge.className = `status-badge ${card.status}`;
    renderHistory();
  }

  function firstSpeciesKey() {
    return Object.keys(state.service_config.action_prompts)[0] || "cat";
  }

  function showToast(message) {
    window.clearTimeout(toastTimer);
    els.toastMessage.textContent = message;
    els.toastMessage.classList.add("show");
    toastTimer = window.setTimeout(() => {
      els.toastMessage.classList.remove("show");
    }, 2200);
  }

  function formatDate(iso) {
    if (!iso) return "未保存";
    const date = new Date(iso);
    if (Number.isNaN(date.getTime())) return iso;
    return new Intl.DateTimeFormat("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    }).format(date);
  }

  function fieldCard() {
    return core.promptCardsForSpecies(state, activeSpecies).find((card) => card.fieldKey === selectedFieldKey)
      || core.promptCardsForSpecies(state, activeSpecies)[0];
  }

  function render() {
    const speciesKeys = Object.keys(state.service_config.action_prompts);
    if (!speciesKeys.includes(activeSpecies)) activeSpecies = firstSpeciesKey();
    const selectedParts = selectedFieldKey.split(".");
    const selectedSpecies = selectedParts[0] === "action_prompts" ? selectedParts[1] : "";
    if (!selectedFieldKey || !speciesKeys.includes(selectedSpecies)) {
      selectedFieldKey = `action_prompts.${activeSpecies}.idle`;
    }
    renderSpeciesCapsules();
    renderPromptCards();
    renderEditor();
  }

  function renderSpeciesCapsules() {
    els.speciesCapsules.innerHTML = "";
    for (const speciesKey of Object.keys(state.service_config.action_prompts)) {
      const label = state.editor_meta.species_labels[speciesKey] || speciesKey;
      const button = document.createElement("button");
      button.type = "button";
      button.className = "species-capsule";
      button.setAttribute("role", "option");
      button.setAttribute("aria-selected", String(speciesKey === activeSpecies));
      button.dataset.speciesKey = speciesKey;
      button.innerHTML = `<span>${escapeHtml(label)}</span><code>${escapeHtml(speciesKey)}</code>`;
      button.addEventListener("click", () => {
        activeSpecies = speciesKey;
        selectedFieldKey = `action_prompts.${speciesKey}.idle`;
        state.editor_meta.active_species = speciesKey;
        saveState();
        render();
      });
      els.speciesCapsules.appendChild(button);
    }
  }

  function renderPromptCards() {
    els.promptCardList.innerHTML = "";
    const cards = core.promptCardsForSpecies(state, activeSpecies);
    for (const card of cards) {
      const button = document.createElement("button");
      button.type = "button";
      button.className = "prompt-card";
      button.setAttribute("aria-pressed", String(card.fieldKey === selectedFieldKey));
      button.dataset.fieldKey = card.fieldKey;
      button.innerHTML = [
        '<div class="prompt-card-title-row">',
        `<span class="prompt-card-title">${escapeHtml(card.title)}</span>`,
        `<span class="status-badge ${card.status}">${escapeHtml(card.statusLabel)}</span>`,
        "</div>",
        `<code class="prompt-card-key">${escapeHtml(card.keyName)}</code>`,
        '<div class="prompt-card-meta">',
        `<span>${escapeHtml(card.versionLabel)}</span>`,
        `<span>${escapeHtml(formatDate(card.lastSavedAt))}</span>`,
        "</div>",
      ].join("");
      button.addEventListener("click", () => {
        selectedFieldKey = card.fieldKey;
        render();
      });
      els.promptCardList.appendChild(button);
    }
  }

  function renderEditor() {
    const card = fieldCard();
    selectedFieldKey = card.fieldKey;
    const text = core.getFieldText(state, selectedFieldKey);
    els.editorHeading.textContent = card.title;
    els.editorStatusBadge.textContent = card.statusLabel;
    els.editorStatusBadge.className = `status-badge ${card.status}`;
    els.selectedFieldTitle.textContent = card.title;
    els.selectedFieldKey.textContent = card.keyName;
    els.selectedComposition.textContent = card.composition;
    if (document.activeElement !== els.promptEditorText) {
      els.promptEditorText.value = text;
    }
    renderHistory();
  }

  function renderHistory() {
    els.historyList.innerHTML = "";
    const history = state.editor_meta.histories[selectedFieldKey] || [];
    if (!history.length) {
      const empty = document.createElement("p");
      empty.className = "empty-history";
      empty.textContent = "这个字段还没有保存过版本。";
      els.historyList.appendChild(empty);
      return;
    }

    history.slice().reverse().forEach((entry, index) => {
      const versionNumber = history.length - index;
      const item = document.createElement("div");
      item.className = "history-item";
      item.innerHTML = [
        "<div>",
        `<p class="history-title">版本 ${versionNumber}</p>`,
        `<p class="history-time">${escapeHtml(formatDate(entry.saved_at))}</p>`,
        "</div>",
        `<button type="button" class="secondary-button" data-version-id="${escapeHtml(entry.id)}">恢复到编辑框</button>`,
      ].join("");
      item.querySelector("button").addEventListener("click", () => {
        els.promptEditorText.value = entry.text;
        els.promptEditorText.focus();
        showToast("已把该版本恢复到编辑框，保存后才会成为新版本。");
      });
      els.historyList.appendChild(item);
    });
  }

  function escapeHtml(value) {
    return String(value)
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;");
  }

  function downloadJson(filename, payload) {
    const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    link.click();
    URL.revokeObjectURL(url);
  }

  els.promptEditorForm.addEventListener("submit", (event) => {
    event.preventDefault();
    state = core.savePromptVersion(state, selectedFieldKey, els.promptEditorText.value);
    saveState();
    render();
    showToast("已保存为新版本。");
  });

  els.promptEditorText.addEventListener("input", () => {
    updateSelectedDraft(els.promptEditorText.value);
    refreshSelectedDraftStatus();
  });

  els.clearFieldButton.addEventListener("click", () => {
    els.promptEditorText.value = "";
    updateSelectedDraft("");
    refreshSelectedDraftStatus();
    els.promptEditorText.focus();
  });

  els.copyConfigButton.addEventListener("click", async () => {
    const text = JSON.stringify(core.exportServiceConfig(state), null, 2);
    try {
      await navigator.clipboard.writeText(text);
      showToast("生成配置已复制。");
    } catch (error) {
      els.promptEditorText.value = text;
      showToast("浏览器不允许复制，已把配置放到编辑框。");
    }
  });

  els.speciesForm.addEventListener("submit", (event) => {
    event.preventDefault();
    const key = els.speciesKeyInput.value.trim();
    const label = els.speciesLabelInput.value.trim();
    if (!key) {
      showToast("请先填写物种键名。");
      return;
    }
    state = core.ensureSpecies(state, key, label);
    activeSpecies = state.editor_meta.active_species;
    selectedFieldKey = `action_prompts.${activeSpecies}.idle`;
    saveState();
    render();
    els.speciesKeyInput.value = "";
    els.speciesLabelInput.value = "";
    showToast("已新增物种。");
  });

  els.deleteSpeciesButton.addEventListener("click", () => {
    if (Object.keys(state.service_config.action_prompts).length <= 1) {
      showToast("至少保留一个物种。");
      return;
    }
    const label = state.editor_meta.species_labels[activeSpecies] || activeSpecies;
    if (!window.confirm(`确认删除物种“${label}”？相关物种提示词版本也会删除。`)) return;
    state = core.deleteSpecies(state, activeSpecies);
    activeSpecies = state.editor_meta.active_species || firstSpeciesKey();
    selectedFieldKey = `action_prompts.${activeSpecies}.idle`;
    saveState();
    render();
    showToast("已删除当前物种。");
  });

  els.exportConfigButton.addEventListener("click", () => {
    downloadJson("doudou-diy-ai-prompt-config.json", core.exportServiceConfig(state));
    showToast("已导出生成配置。");
  });

  els.exportBackupButton.addEventListener("click", () => {
    downloadJson("doudou-diy-ai-prompt-filler-backup.json", core.exportEditorBackup(state));
    showToast("已导出编辑备份。");
  });

  els.importButton.addEventListener("click", () => {
    els.importFileInput.click();
  });

  els.importFileInput.addEventListener("change", async () => {
    const file = els.importFileInput.files && els.importFileInput.files[0];
    if (!file) return;
    try {
      const payload = JSON.parse(await file.text());
      state = core.importPromptPayload(payload);
      activeSpecies = state.editor_meta.active_species || firstSpeciesKey();
      selectedFieldKey = `action_prompts.${activeSpecies}.idle`;
      saveState();
      render();
      showToast("JSON 已导入。");
    } catch (error) {
      console.error(error);
      showToast("导入失败，请确认文件是 JSON。");
    } finally {
      els.importFileInput.value = "";
    }
  });

  render();
  window.requestAnimationFrame(() => {
    els.speciesKeyInput.value = "";
    els.speciesLabelInput.value = "";
  });
})();
