(() => {
  "use strict";

  const MODE_KEY = "jianglai_usability_mode";
  const state = {
    items: [],
    filtered: [],
    activeIndex: -1,
    timer: 0
  };

  const byId = id => document.getElementById(id);
  const bridge = () => window.__jianglaiUsabilityBridge || null;
  const text = value => String(value ?? "").replace(/\s+/g, " ").trim();

  function friendlyError(error) {
    const raw = text(error?.message || error || "");
    if (!raw) return "操作暂时没有完成，请稍后重试。";
    if (/not found|404|找不到/i.test(raw)) return "没有找到对应资料，可能已被删除或链接已经失效。";
    if (/unauthorized|401|登录|token|认证/i.test(raw)) return "登录状态已失效，请重新登录后继续。";
    if (/forbidden|403|permission|权限/i.test(raw)) return "当前账号没有这项操作权限，请联系管理员。";
    if (/timeout|timed out|超时|abort/i.test(raw)) return "服务响应较慢，本次资料已保留，可以直接重试。";
    if (/failed to fetch|network|网络|connection|连接/i.test(raw)) return "当前网络连接不稳定，请检查网络后重试。";
    if (/undefined|can't find variable|is not defined|null/i.test(raw)) return "页面状态没有正确加载，请刷新页面后重试。";
    if (/server|500|502|503|504|服务/i.test(raw)) return "服务暂时繁忙，本次资料已保留，请稍后重试。";
    return raw.length > 120 ? "操作暂时没有完成，本次资料已保留，请稍后重试。" : raw;
  }
  window.__jianglaiFriendlyError = friendlyError;

  window.selectAutoRenewPlan = function (planKey) {
    const offer = {
      standard: { name: "AI跟单版连续包月", first: "¥99", recurring: "¥199/月" },
      pro: { name: "团队协作版连续包月", first: "¥249", recurring: "¥499/月" }
    }[planKey];
    if (!offer) return;
    window.__selectedMemberPlan = "";
    window.__selectedAutoRenewPlan = planKey;
    const panel = byId("memberPurchasePanel");
    panel?.classList.remove("is-hidden");
    if (byId("memberPurchaseTag")) byId("memberPurchaseTag").textContent = "连续包月 · 默认关闭";
    if (byId("memberPurchaseTitle")) byId("memberPurchaseTitle").textContent = `${offer.name} · 首月${offer.first}`;
    if (byId("memberPurchaseDescription")) byId("memberPurchaseDescription").textContent = `首月扣款${offer.first}，次月起每月${offer.recurring}；每月同日扣款，扣款前5日提醒。可在账号中心随时关闭，关闭后已支付周期仍可继续使用。当前微信支付和支付宝产品审核中，审核通过后开放签约。`;
    byId("memberPaymentMethods")?.classList.remove("is-hidden");
    const action = byId("memberPaymentAction");
    if (action) {
      action.disabled = true;
      action.textContent = "平台审核通过后签约";
    }
    panel?.scrollIntoView({ behavior:"smooth", block:"center" });
  };

  function createButton(className, label, title) {
    const button = document.createElement("button");
    button.type = "button";
    button.className = className;
    button.title = title;
    button.setAttribute("aria-label", title);
    button.innerHTML = label;
    return button;
  }

  function buildLayer() {
    if (byId("usabilitySearchLayer")) return;
    const layer = document.createElement("div");
    layer.id = "usabilitySearchLayer";
    layer.className = "usability-search-layer";
    layer.setAttribute("role", "dialog");
    layer.setAttribute("aria-modal", "true");
    layer.setAttribute("aria-label", "全局搜索与快捷新建");
    layer.innerHTML = `
      <section class="usability-search-dialog">
        <div class="usability-search-head">
          <input id="usabilitySearchInput" type="search" autocomplete="off" placeholder="搜索客户、订单、报价或功能…">
          <button class="usability-search-close" id="usabilitySearchClose" type="button" aria-label="关闭">×</button>
        </div>
        <div class="usability-search-body">
          <section class="usability-search-section">
            <div class="usability-search-section-title">快捷新建</div>
            <div class="usability-quick-actions">
              <button class="usability-quick-action" type="button" data-quick-action="inquiry"><strong>新询盘</strong><span>接收客户文字和文件</span></button>
              <button class="usability-quick-action" type="button" data-quick-action="quote"><strong>新报价</strong><span>直接进入核价工作台</span></button>
              <button class="usability-quick-action" type="button" data-quick-action="order"><strong>新订单</strong><span>建立订单跟进任务</span></button>
              <button class="usability-quick-action" type="button" data-quick-action="outsource"><strong>新外协</strong><span>发给供应商接单</span></button>
            </div>
          </section>
          <section class="usability-search-section">
            <div class="usability-search-section-title" id="usabilitySearchResultTitle">最近业务与功能</div>
            <div class="usability-search-results" id="usabilitySearchResults"></div>
          </section>
        </div>
      </section>`;
    document.body.appendChild(layer);
    layer.addEventListener("mousedown", event => {
      if (event.target === layer) closeSearch();
    });
    byId("usabilitySearchClose").addEventListener("click", closeSearch);
    byId("usabilitySearchInput").addEventListener("input", event => renderResults(event.target.value));
    byId("usabilitySearchInput").addEventListener("keydown", handleSearchKeys);
    layer.querySelectorAll("[data-quick-action]").forEach(button => {
      button.addEventListener("click", () => {
        bridge()?.quickAction?.(button.dataset.quickAction || "");
        closeSearch();
      });
    });
  }

  function installHeaderControls() {
    const header = document.querySelector(".header-status");
    if (!header || byId("usabilitySearchButton")) return;
    const search = createButton(
      "usability-search-button",
      `<span aria-hidden="true">⌕</span><span class="usability-button-copy"> 全局搜索</span><kbd>⌘K</kbd>`,
      "搜索客户、订单、报价和功能"
    );
    search.id = "usabilitySearchButton";
    search.addEventListener("click", openSearch);

    const mode = createButton(
      "usability-mode-button",
      `<span aria-hidden="true">◐</span><span class="usability-button-copy" id="usabilityModeLabel"> 基础模式</span>`,
      "切换基础模式和专业模式"
    );
    mode.id = "usabilityModeButton";
    mode.addEventListener("click", toggleMode);
    header.prepend(mode);
    header.prepend(search);
  }

  function getItems() {
    const api = bridge();
    const source = api?.data?.() || {};
    const pages = [
      ["工作台", "首页", "今日待办、经营概览"],
      ["询盘处理", "接单", "客户询价、附件分析"],
      ["报价系统", "报价", "产品核价、报价历史"],
      ["跟单工单", "订单", "订单进度、客户跟进"],
      ["图片制作", "制图", "商品图、效果图、详情图"],
      ["生产中心", "生产", "工序、材料、质检、外协"],
      ["外协协作", "外协", "供应商、月结、验收"],
      ["经营报表", "报表", "收入、成本、利润复盘"],
      ["更多", "更多设置", "账号、团队、渠道、备份"]
    ].map(([id, title, subtitle], index) => ({
      kind:"page", id, title, subtitle, keywords:`${id} ${title} ${subtitle}`, recent:100 - index
    }));
    const tasks = (Array.isArray(source.tasks) ? source.tasks : []).map(task => ({
      kind:"task",
      id:text(task.id),
      title:`${api?.displayTaskId?.(task) || text(task.id)} · ${text(task.customer || task.title || "未命名订单")}`,
      subtitle:`${text(task.title || "产品待补充")} · ${api?.taskPhase?.(task) || "待处理"} · ${text(task.status || "待处理")}`,
      keywords:text(`${task.customer || ""} ${task.title || ""} ${task.owner || ""} ${task.nextAction || ""} ${task.due || ""}`),
      recent:Number(new Date(task.updatedAt || task.createdAt || 0)) || 0
    }));
    const customers = (Array.isArray(source.customers) ? source.customers : []).map(profile => ({
      kind:"customer",
      id:text(profile.company),
      title:text(profile.company || "未命名客户"),
      subtitle:`${text(profile.contact || "联系人未填")} · ${text(profile.dealStatus || "待跟进")}`,
      keywords:text(`${profile.need || ""} ${profile.preference || ""} ${profile.level || ""}`),
      recent:Number(new Date(profile.updatedAt || 0)) || 0
    }));
    const quotes = (Array.isArray(source.quotes) ? source.quotes : []).map(record => ({
      kind:"quote",
      id:text(api?.quoteKey?.(record)),
      title:`${text(record.customer || "客户")} · ${text(record.product || "未命名产品")}`,
      subtitle:`报价 ¥${Number(record.total || 0).toFixed(0)} · ${Number(record.qty || 0).toLocaleString("zh-CN")} 个`,
      keywords:text(`${record.quoteNo || ""} ${record.size || ""} ${record.material || ""} ${record.process || ""}`),
      recent:Number(new Date(record.createdAt || record.time || 0)) || 0
    }));
    return [...tasks, ...customers, ...quotes, ...pages].filter(item => item.kind && item.title);
  }

  function resultKindLabel(kind) {
    return ({ task:"订单", customer:"客户", quote:"报价", page:"功能" })[kind] || "记录";
  }

  function renderResults(query = "") {
    const results = byId("usabilitySearchResults");
    if (!results) return;
    const keyword = text(query).toLowerCase();
    state.items = getItems();
    state.filtered = state.items.filter(item => {
      if (!keyword) return true;
      return `${item.title} ${item.subtitle} ${item.keywords}`.toLowerCase().includes(keyword);
    }).sort((left, right) => {
      if (keyword) {
        const leftStarts = left.title.toLowerCase().startsWith(keyword) ? 1 : 0;
        const rightStarts = right.title.toLowerCase().startsWith(keyword) ? 1 : 0;
        if (leftStarts !== rightStarts) return rightStarts - leftStarts;
      }
      return right.recent - left.recent;
    }).slice(0, keyword ? 24 : 12);
    state.activeIndex = state.filtered.length ? 0 : -1;
    byId("usabilitySearchResultTitle").textContent = keyword ? `搜索结果 · ${state.filtered.length} 条` : "最近业务与功能";
    results.replaceChildren();
    if (!state.filtered.length) {
      const empty = document.createElement("div");
      empty.className = "usability-search-empty";
      empty.textContent = "没有找到对应资料。可以换客户名、订单号、产品名或直接使用上方快捷新建。";
      results.appendChild(empty);
      return;
    }
    state.filtered.forEach((item, index) => {
      const button = document.createElement("button");
      button.type = "button";
      button.className = `usability-search-result${index === state.activeIndex ? " is-active" : ""}`;
      button.dataset.index = String(index);
      const badge = document.createElement("b");
      badge.className = "usability-search-kind";
      badge.textContent = resultKindLabel(item.kind);
      const copy = document.createElement("span");
      const title = document.createElement("strong");
      title.textContent = item.title;
      const subtitle = document.createElement("span");
      subtitle.textContent = item.subtitle || "点击打开";
      copy.append(title, subtitle);
      const arrow = document.createElement("em");
      arrow.textContent = "打开 →";
      button.append(badge, copy, arrow);
      button.addEventListener("click", () => openResult(item));
      button.addEventListener("mouseenter", () => {
        state.activeIndex = index;
        updateActiveResult();
      });
      results.appendChild(button);
    });
  }

  function updateActiveResult() {
    document.querySelectorAll(".usability-search-result").forEach((button, index) => {
      button.classList.toggle("is-active", index === state.activeIndex);
    });
    document.querySelector(`.usability-search-result[data-index="${state.activeIndex}"]`)?.scrollIntoView({ block:"nearest" });
  }

  function handleSearchKeys(event) {
    if (event.key === "ArrowDown" && state.filtered.length) {
      event.preventDefault();
      state.activeIndex = (state.activeIndex + 1) % state.filtered.length;
      updateActiveResult();
    } else if (event.key === "ArrowUp" && state.filtered.length) {
      event.preventDefault();
      state.activeIndex = (state.activeIndex - 1 + state.filtered.length) % state.filtered.length;
      updateActiveResult();
    } else if (event.key === "Enter" && state.activeIndex >= 0) {
      event.preventDefault();
      openResult(state.filtered[state.activeIndex]);
    } else if (event.key === "Escape") {
      closeSearch();
    }
  }

  function openResult(item) {
    const api = bridge();
    if (item.kind === "task") api?.openTask?.(item.id);
    else if (item.kind === "customer") api?.openCustomer?.(item.id);
    else if (item.kind === "quote") api?.openQuote?.(item.id);
    else if (item.kind === "page") api?.openPage?.(item.id);
    closeSearch();
  }

  function openSearch() {
    buildLayer();
    const layer = byId("usabilitySearchLayer");
    layer.classList.add("is-open");
    document.body.style.overflow = "hidden";
    const input = byId("usabilitySearchInput");
    input.value = "";
    renderResults("");
    window.setTimeout(() => input.focus(), 20);
  }

  function closeSearch() {
    byId("usabilitySearchLayer")?.classList.remove("is-open");
    document.body.style.overflow = "";
    byId("usabilitySearchButton")?.focus();
  }

  function currentMode() {
    const saved = bridge()?.getMode?.() || localStorage.getItem(MODE_KEY) || "basic";
    return saved === "professional" ? "professional" : "basic";
  }

  function markAdvancedControls() {
    ["homeImageModel", "homeImageRatio", "homeImageQuality"].forEach(id => {
      byId(id)?.closest(".image-studio-field")?.classList.add("usability-advanced-control");
    });
    [
      byId("jlVectorTypeSettings"),
      byId("jlVectorAdvancedSettings"),
      ...document.querySelectorAll(".quote-operation-price-advanced")
    ].filter(Boolean).forEach(element => element.classList.add("usability-advanced-control"));
  }

  function applyMode(mode, announce = false) {
    const normalized = mode === "professional" ? "professional" : "basic";
    document.body.dataset.usabilityMode = normalized;
    localStorage.setItem(MODE_KEY, normalized);
    bridge()?.setMode?.(normalized);
    const label = byId("usabilityModeLabel");
    if (label) label.textContent = normalized === "basic" ? " 基础模式" : " 专业模式";
    const button = byId("usabilityModeButton");
    if (button) {
      button.title = normalized === "basic"
        ? "当前只显示常用选项，点击切换到专业模式"
        : "当前显示全部专业设置，点击切换到基础模式";
    }
    if (announce && typeof window.notify === "function") {
      window.notify(normalized === "basic" ? "已切换到基础模式，只显示日常常用选项。" : "已切换到专业模式，全部参数已经显示。");
    }
  }

  function toggleMode() {
    applyMode(currentMode() === "basic" ? "professional" : "basic", true);
  }

  function enhanceTaskDetail(task, detailMode = "tracking") {
    const output = byId("taskDetailOutput");
    const context = output?.querySelector(".task-detail-context");
    if (!context || output.querySelector(".usability-order-switch")) return;
    const taskId = text(task?.id);
    const bar = document.createElement("nav");
    bar.className = "usability-order-switch";
    bar.setAttribute("aria-label", "订单工作视图");
    const label = document.createElement("span");
    label.textContent = "同一订单 · 无需重复录入";
    const tracking = document.createElement("button");
    tracking.type = "button";
    tracking.className = detailMode === "tracking" ? "is-active" : "";
    tracking.textContent = "客户与订单";
    tracking.addEventListener("click", () => bridge()?.openOrderView?.(taskId, "tracking"));
    const production = document.createElement("button");
    production.type = "button";
    production.className = detailMode === "production" ? "is-active" : "";
    production.textContent = "生产与外协";
    production.addEventListener("click", () => bridge()?.openOrderView?.(taskId, "production"));
    const outsource = document.createElement("button");
    outsource.type = "button";
    outsource.textContent = "外协协作";
    outsource.addEventListener("click", () => bridge()?.openOrderView?.(taskId, "outsource"));
    bar.append(label, tracking, production, outsource);
    context.after(bar);
  }

  function decorateLoadingNode(node) {
    if (!node || node.dataset.usabilityTimer === "1" || node.hidden || getComputedStyle(node).display === "none") return;
    // Image-generation cards already maintain their own persistent elapsed timer.
    // Adding another <em> inside that timer made the short "已用 9 秒" label
    // inherit the block layout and collapse into one Chinese character per line.
    if (node.querySelector("#homeVisualThinkingElapsed")) {
      node.dataset.usabilityTimer = "1";
      return;
    }
    node.dataset.usabilityTimer = "1";
    const start = Date.now();
    const elapsed = document.createElement("em");
    elapsed.className = "usability-elapsed";
    elapsed.textContent = "已用 0 秒";
    const target = node.querySelector(".ai-loading-copy") || node;
    target.appendChild(elapsed);
    const timer = window.setInterval(() => {
      if (!node.isConnected || node.hidden || getComputedStyle(node).display === "none") {
        window.clearInterval(timer);
        node.dataset.usabilityTimer = "0";
        elapsed.remove();
        return;
      }
      const seconds = Math.floor((Date.now() - start) / 1000);
      elapsed.textContent = `已用 ${seconds} 秒${seconds >= 45 ? " · 仍在处理，可先切换页面" : ""}`;
    }, 1000);
  }

  function watchLoadingStates() {
    const decorateAll = root => {
      if (root?.matches?.(".ai-loading, #jlVectorProcessing")) decorateLoadingNode(root);
      root?.querySelectorAll?.(".ai-loading, #jlVectorProcessing").forEach(decorateLoadingNode);
    };
    decorateAll(document);
    new MutationObserver(records => {
      records.forEach(record => {
        record.addedNodes.forEach(node => {
          if (node.nodeType === Node.ELEMENT_NODE) decorateAll(node);
        });
        if (record.type === "attributes") decorateAll(record.target);
      });
    }).observe(document.body, { childList:true, subtree:true, attributes:true, attributeFilter:["class","style","hidden"] });
  }

  function keepActiveNavVisible() {
    const nav = byId("nav");
    if (!nav) return;
    const observer = new MutationObserver(() => {
      nav.querySelector("button.active")?.scrollIntoView({ behavior:"smooth", block:"nearest", inline:"center" });
    });
    observer.observe(nav, { attributes:true, subtree:true, attributeFilter:["class"] });
  }

  function init() {
    buildLayer();
    installHeaderControls();
    markAdvancedControls();
    applyMode(currentMode());
    watchLoadingStates();
    keepActiveNavVisible();
    document.addEventListener("keydown", event => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
        event.preventDefault();
        openSearch();
      } else if (event.key === "Escape" && byId("usabilitySearchLayer")?.classList.contains("is-open")) {
        closeSearch();
      }
    });
    window.__jianglaiUsability = { enhanceTaskDetail, openSearch, applyMode, friendlyError };
  }

  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init, { once:true });
  else init();
})();
