/* Simple i18n helper for the BlackEagle extension
   - default: English ('en'), optional Chinese ('zh')
   - stores selection in localStorage key 'beLang'
   - provides i18n.t(key, vars) and i18n.apply() to translate DOM
*/
(function (global) {
  const STORAGE_KEY = "beLang";
  const dict = {
    en: {
      // header / hero
      heroEyebrow: "BlackEagle",
      heroTitle: "AI Assistant Settings",
      heroLead1: "Configure multiple AI endpoints and schedule lightweight tasks that trigger your agent with one sentence.",
      heroLead2: "All configured endpoints must comply with OpenAI specifications to be usable.",

      // tabs
      tabLLM: "LLM Config",
      tabMore: "More Config",
      tabTasks: "Task Management",
      tabAbout: "About",

      // forms
      formTitle: "Create configuration",
      formOpenAIHint: "Only OpenAI-spec compatible endpoints are accepted. Your Key / Base URL / Model must follow the OpenAI API to work.",
      submitSave: "Save configuration",
      submitUpdate: "Update configuration",
      reset: "Reset",

      // more config
      moreTitle: "More configuration",
      moreLead: "Manage extra integration tokens. Notion token is stored locally and used only by this extension.",
      dtNotionToken: "Notion Token",
      phNotionToken: "secret_xxx",
      notionTokenRequired: "Please provide a Notion token.",
      notionSaved: "Notion token saved.",
      moreCleared: "Extra settings cleared.",
      unableToLoadMore: "Unable to load extra settings.",

      // configs list
      configCounter: "{count} configs",
      emptyState: "No configurations yet. Create your first endpoint on the left.",
      dtModelName: "Model Name",
      dtApiKey: "API Key",
      dtBaseUrl: "Base URL",
      dtApiVersion: "API Version",
      dtModel: "Model",
      dtLlmType: "LLM Type",
      btnEdit: "Edit",
      btnDelete: "Delete",

      // tasks
      taskFormTitle: "Create Task",
      taskCounter: "{count} tasks",
      taskEmpty: "No tasks yet. Create the first to start scheduling.",
      dtInstruction: "Instruction",
      dtInterval: "Interval",
      dtSchedule: "Schedule",
      dtStatus: "Status",
      dtCreated: "Created",
      dtLastRun: "Last run",
      btnRunNow: "Run now",
      btnPause: "Pause",
      btnResume: "Resume",
      untitledTask: "Untitled task",
      enabled: "Enabled",
      disabled: "Disabled",

      // status messages
      noConfigsExport: "No configs to export",
      configsExported: "Configs exported",
      importNoConfigs: "Import file has no configs",
      noValidConfigsImport: "No valid configs to import",
      unableToLoadConfigs: "Unable to load configurations.",
      savingFailed: "Saving failed. Try again.",
      importedConfigs: "Imported {n} configs",
      importedTasks: "Imported {n} tasks",
      importFailedInvalidJson: "Import failed: invalid JSON",
      pleaseFillRequired: "Please fill in all required fields.",
      configUpdated: "Configuration updated.",
      configSaved: "Configuration saved.",
      configRemoved: "Configuration removed.",
      confirmDeleteConfig: "Delete this configuration? This cannot be undone.",
      confirmDeleteTask: "Delete this task?",
      taskDeleted: "Task deleted",
      taskResumed: "Task resumed",
      taskPaused: "Task paused",
      taskSaved: "Task saved",
      saveFailed: "Save failed",
      formCleared: "Form cleared.",
      formReset: "Form reset",
      noTasksExport: "No tasks to export",
      tasksExported: "Tasks exported",
      importNoTasks: "Import file has no tasks",
      noValidTasksImport: "No valid tasks to import",

      // generic
      minutesShort: "{n} min",
      // about / docs
      pill: "BlackEagle · Local-first AI",
      aboutTitle: "About this extension",
      aboutLead:
        "BlackEagle is a local-first browser AI agent: it reads webpages, understands text/images/video, operates websites like a human, uploads and analyzes documents, runs scheduled tasks, and generates exportable results — all without any backend server.",
      whatYouCanDo: "What you can do",
      s1Title: "Web & Media",
      s1li1: "Read full pages or selections and extract structured data",
      s1li2: "Understand text, images, and embedded media",
      s1li3: "Click, fill, and navigate like a human",
      s2Title: "Documents & Output",
      s2li1: "Upload PDFs/text and automatically summarize and extract key points",
      s2li2: "Turn conversation results into exportable documents",
      s3Title: "Automation & Privacy",
      s3li1: "Create scheduled or rule-based tasks and monitor page changes",
      s3li2: "Bring your own API key; runs entirely in the browser",
      s3li3: "No account, no server, no tracking",
      feedbackTitle: "Feedback & contribution",
      feedbackLead: "Got ideas, bugs, or feature requests? Visit the GitHub repo to open issues. You can also fork and contribute via PRs. Your feedback helps improve BlackEagle.",
      ctaGitHubHome: "GitHub Home · Feedback",
      ctaViewReadme: "View README",
      ctaOpenIssues: "Open Issues",
      ctaJoinDiscussions: "Join Discussions",
      // placeholders
      phName: "Cozy GPT-4o",
      phApiKey: "sk-...",
      phBaseUrl: "https://api.provider.com/v1",
      phApiVersion: "2024-05-01-preview",
      phModel: "gpt-4o-mini",
      phTaskName: "Example: Summarize current page periodically",
      phTaskInstruction: "Tell the Agent what to do in one sentence",
      phInterval: "e.g., 30 (minimum 5 minutes)",
      // import/export
      btnExport: "Export JSON",
      btnImport: "Import JSON",
      hintExport: "API keys are included in exports. Keep the file safe.",
    },
    zh: {
      heroEyebrow: "BlackEagle",
      heroTitle: "AI 助手 设置",
      heroLead1: "配置多个 AI 接口，并调度轻量任务，让代理一句话触发。",
      heroLead2: "所有配置的接口需符合 OpenAI 规格以便使用。",

      tabLLM: "LLM 配置",
      tabMore: "更多配置",
      tabTasks: "任务管理",
      tabAbout: "关于",

      formTitle: "创建配置",
      formOpenAIHint: "仅支持符合 OpenAI API 规范的模型配置，填写的 Key / Base URL / Model 需兼容 OpenAI 协议才会生效。",
      submitSave: "保存配置",
      submitUpdate: "更新配置",
      reset: "重置",

      moreTitle: "更多配置",
      moreLead: "管理额外的集成令牌。Notion Token 会本地存储，仅供此扩展使用。",
      dtNotionToken: "Notion Token",
      phNotionToken: "secret_xxx",
      notionTokenRequired: "请填写 Notion Token。",
      notionSaved: "Notion Token 已保存。",
      moreCleared: "额外配置已清空。",
      unableToLoadMore: "无法加载额外配置。",

      configCounter: "{count} 个配置",
      emptyState: "还没有任何配置。在左侧创建第一个端点。",
      dtModelName: "模型名称",
      dtApiKey: "API 密钥",
      dtBaseUrl: "基础地址",
      dtApiVersion: "API 版本",
      dtModel: "模型",
      dtLlmType: "LLM 类型",
      btnEdit: "编辑",
      btnDelete: "删除",

      taskFormTitle: "创建任务",
      taskCounter: "{count} 个任务",
      taskEmpty: "还没有任务。创建第一个任务开始调度。",
      dtInstruction: "指令",
      dtInterval: "间隔",
      dtSchedule: "计划",
      dtStatus: "状态",
      dtCreated: "创建时间",
      dtLastRun: "上次运行",
      btnRunNow: "立即运行",
      btnPause: "暂停",
      btnResume: "继续",
      untitledTask: "未命名任务",
      enabled: "已启用",
      disabled: "已禁用",

      noConfigsExport: "没有可导出的配置",
      configsExported: "配置已导出",
      importNoConfigs: "导入文件不包含配置",
      noValidConfigsImport: "没有可导入的有效配置",
      unableToLoadConfigs: "无法加载配置。",
      savingFailed: "保存失败，请重试。",
      importedConfigs: "已导入 {n} 个配置",
      importedTasks: "已导入 {n} 个任务",
      importFailedInvalidJson: "导入失败：无效的 JSON",
      pleaseFillRequired: "请填写所有必填项。",
      configUpdated: "配置已更新。",
      configSaved: "配置已保存。",
      configRemoved: "配置已删除。",
      confirmDeleteConfig: "删除此配置？此操作无法撤销。",
      confirmDeleteTask: "删除此任务？",
      taskDeleted: "任务已删除",
      taskResumed: "任务已恢复",
      taskPaused: "任务已暂停",
      taskSaved: "任务已保存",
      saveFailed: "保存失败",
      formCleared: "表单已清除。",
      formReset: "表单已重置",
      noTasksExport: "没有可导出的任务",
      tasksExported: "任务已导出",
      importNoTasks: "导入文件不包含任务",
      noValidTasksImport: "没有可导入的有效任务",

      minutesShort: "{n} 分",
      // about / docs
      pill: "BlackEagle · 本地优先 AI",
      aboutTitle: "关于此扩展",
      aboutLead: "BlackEagle 是一个本地优先的浏览器 AI 代理：它可读取网页，理解文本/图像/视频，像人类一样操作网站，上传并分析文档，运行计划任务，并生成可导出的结果——所有操作均无需后端服务器。",
      whatYouCanDo: "功能概览",
      s1Title: "网页与媒体",
      s1li1: "读取完整页面或选区并提取结构化数据",
      s1li2: "理解文本、图像和嵌入媒体",
      s1li3: "像人类一样点击、填写并导航网页",
      s2Title: "文档与输出",
      s2li1: "上传 PDF/文本并自动生成摘要与要点提取",
      s2li2: "将对话结果导出为文档",
      s3Title: "自动化与隐私",
      s3li1: "创建计划或规则驱动的任务并监控页面变化",
      s3li2: "自带 API 密钥；全部在浏览器中运行",
      s3li3: "无需账户、无需服务器、无跟踪",
      feedbackTitle: "反馈与贡献",
      feedbackLead: "有想法、Bug 或功能请求？访问 GitHub 仓库打开 issue。你也可以 fork 并通过 PR 贡献。你的反馈会帮助改进 BlackEagle。",
      ctaGitHubHome: "GitHub 仓库 · 反馈",
      ctaViewReadme: "查看 README",
      ctaOpenIssues: "打开 Issue",
      ctaJoinDiscussions: "加入讨论",
      // placeholders
      phName: "Cozy GPT-4o",
      phApiKey: "sk-...",
      phBaseUrl: "https://api.provider.com/v1",
      phApiVersion: "2024-05-01-preview",
      phModel: "gpt-4o-mini",
      phTaskName: "例如：定期汇总当前页面",
      phTaskInstruction: "用一句话告诉代理需要做什么",
      phInterval: "例如：30（最小 5 分钟）",
      // import/export
      btnExport: "导出 JSON",
      btnImport: "导入 JSON",
      hintExport: "导出包含 API 密钥，请妥善保管该文件。",
    },
  };

  let current = (function () {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved === "en" || saved === "zh") return saved;
    } catch (e) {}
    return "en";
  })();

  function t(key, vars) {
    const src = dict[current] || dict.en;
    let s = src[key] ?? dict.en[key] ?? key;
    if (vars) {
      Object.keys(vars).forEach((k) => {
        s = s.replace(new RegExp("{" + k + "}", "g"), vars[k]);
      });
    }
    return s;
  }

  function apply() {
    // elements with data-i18n attribute
    document.querySelectorAll("[data-i18n]").forEach((el) => {
      const key = el.getAttribute("data-i18n");
      if (!key) return;
      const text = t(key);
      if (el.tagName === "INPUT" || el.tagName === "TEXTAREA") {
        el.placeholder = text;
      } else {
        el.textContent = text;
      }
    });

    // elements with id matching keys
    Object.keys(dict.en).forEach((key) => {
      const el = document.getElementById(key);
      if (el) {
        el.textContent = t(key);
      }
    });
  }

  function setLang(lang) {
    if (lang !== "en" && lang !== "zh") return;
    current = lang;
    try {
      localStorage.setItem(STORAGE_KEY, lang);
    } catch (e) {}
    apply();
    window.dispatchEvent(new CustomEvent("i18n:change", { detail: { lang } }));
  }

  global.i18n = { t, apply, setLang, getLang: () => current };

  document.addEventListener("DOMContentLoaded", function () {
    apply();
    // sync any lang selector
    const select = document.getElementById("langSelect");
    if (select) {
      select.value = current;
      select.addEventListener("change", function () {
        setLang(select.value);
      });
    }

    // Toggle button support (langToggleBtn)
    const btn = document.getElementById("langToggleBtn");
    if (btn) {
      btn.textContent = current === "zh" ? "中文" : "EN";
      btn.addEventListener("click", function () {
        const next = current === "zh" ? "en" : "zh";
        setLang(next);
        btn.textContent = next === "zh" ? "中文" : "EN";
      });
    }
    // keep button label in sync when language changes elsewhere
    window.addEventListener("i18n:change", function (ev) {
      const b = document.getElementById("langToggleBtn");
      if (b) b.textContent = ev?.detail?.lang === "zh" ? "中文" : "EN";
    });
  });
})(window);
