(function () {
  "use strict";

  const IDENTITIES = new Set(["merchant", "factory", "both"]);
  const STORAGE_PREFIX = "jianglai_business_workspace_";
  let lastUserKey = "";
  let saving = false;

  function token() {
    try {
      return localStorage.getItem("formal_api_token") || "";
    } catch (_) {
      return "";
    }
  }

  function user() {
    return window.__currentUser || null;
  }

  function workspaceKey(currentUser) {
    return `${STORAGE_PREFIX}${currentUser?.company_id || "guest"}_${currentUser?.user_id || "user"}`;
  }

  function allowedWorkspaces(currentUser) {
    if (currentUser?.business_identity === "both") return ["both"];
    if (currentUser?.business_identity === "factory") return ["factory"];
    if (currentUser?.business_identity === "merchant") return ["merchant"];
    if (Array.isArray(currentUser?.workspaces) && currentUser.workspaces.length) {
      return currentUser.workspaces.filter(item => item === "merchant" || item === "factory");
    }
    return ["merchant"];
  }

  function savedWorkspace(currentUser) {
    const allowed = allowedWorkspaces(currentUser);
    let saved = "";
    try {
      saved = localStorage.getItem(workspaceKey(currentUser)) || "";
    } catch (_) {}
    return allowed.includes(saved) ? saved : allowed[0];
  }

  function ensureSwitcher() {
    let root = document.getElementById("businessWorkspaceSwitcher");
    if (root) return root;
    root = document.createElement("div");
    root.id = "businessWorkspaceSwitcher";
    root.className = "business-workspace-switcher";
    root.hidden = true;
    root.innerHTML = [
      "<span>当前工作台</span>",
      '<button type="button" data-workspace="merchant">接单经营</button>',
      '<button type="button" data-workspace="factory">生产加工</button>'
    ].join("");
    root.addEventListener("click", event => {
      const button = event.target.closest("[data-workspace]");
      if (button) setWorkspace(button.dataset.workspace, true);
    });
    const status = document.querySelector(".header-status");
    status?.prepend(root);
    return root;
  }

  function setNavForWorkspace(workspace) {
    document.querySelectorAll("#nav button[data-page]").forEach(button => {
      const page = button.dataset.page;
      const merchantHidden = page === "生产中心";
      const factoryHidden = ["询盘处理", "报价系统", "外协协作", "经营报表"].includes(page);
      const hidden = workspace === "merchant" && merchantHidden
        || workspace === "factory" && factoryHidden;
      button.classList.toggle("business-workspace-hidden", hidden);
      if (button.classList.contains("business-workspace-hidden")) {
        button.style.display = "none";
      } else if (button.style.display === "none") {
        button.style.removeProperty("display");
      }
    });
  }

  function setWorkspace(workspace, navigate) {
    const currentUser = user();
    const allowed = allowedWorkspaces(currentUser);
    if (!allowed.includes(workspace)) workspace = allowed[0];
    try {
      localStorage.setItem(workspaceKey(currentUser), workspace);
    } catch (_) {}
    document.body.dataset.businessWorkspace = workspace;
    const switcher = ensureSwitcher();
    switcher.querySelectorAll("[data-workspace]").forEach(button => {
      button.classList.toggle("is-active", button.dataset.workspace === workspace);
    });
    setNavForWorkspace(workspace);
    if (navigate && typeof window.showPage === "function") {
      window.showPage(workspace === "factory" ? "生产中心" : "工作台");
    }
  }

  function ensureSettingsControl() {
    let root = document.getElementById("businessIdentitySettings");
    if (root) return root;
    root = document.createElement("div");
    root.id = "businessIdentitySettings";
    root.className = "business-identity-settings";
    root.hidden = true;
    root.innerHTML = `
      <div>
        <strong>经营身份</strong>
        <span id="businessIdentitySettingsValue">尚未选择</span>
      </div>
      <button class="btn light" type="button">修改经营身份</button>`;
    root.querySelector("button")?.addEventListener("click", () => {
      const gate = ensureGate();
      gate.dataset.editing = "true";
      gate.hidden = false;
      updateGateSelection(user()?.business_identity || "");
    });
    document.getElementById("currentStaffSummary")?.insertAdjacentElement("afterend", root);
    return root;
  }

  function updateGateSelection(identity) {
    document.querySelectorAll("#businessIdentityGate [data-identity]").forEach(button => {
      button.classList.toggle("is-selected", button.dataset.identity === identity);
    });
    const cancel = document.querySelector("#businessIdentityGate [data-identity-cancel]");
    if (cancel) cancel.hidden = !identity;
  }

  function ensureGate() {
    let gate = document.getElementById("businessIdentityGate");
    if (gate) return gate;
    gate = document.createElement("div");
    gate.id = "businessIdentityGate";
    gate.className = "business-identity-gate";
    gate.hidden = true;
    gate.innerHTML = `
      <section class="business-identity-dialog" role="dialog" aria-modal="true" aria-labelledby="businessIdentityTitle">
        <h2 id="businessIdentityTitle">先选择你的经营身份</h2>
        <p>这里只决定首页和常用入口，不会删除现有客户、报价或生产数据，以后老板仍可修改。</p>
        <div class="business-identity-options">
          <button class="business-identity-option" type="button" data-identity="merchant"><b>接单经营</b><strong>我主要负责接单</strong><span>客户询盘、报价、跟单，以及把生产要求发给合作工厂。</span></button>
          <button class="business-identity-option" type="button" data-identity="factory"><b>生产加工</b><strong>我是生产厂家</strong><span>接收生产资料，确认工艺、排产、质检和交付。</span></button>
          <button class="business-identity-option" type="button" data-identity="both"><b>接单＋生产</b><strong>两种业务都有</strong><span>接单和生产两套功能同时显示，不需要来回切换。</span></button>
        </div>
        <div class="business-identity-message" id="businessIdentityMessage" aria-live="polite"></div>
        <div class="business-identity-dialog-actions"><button class="btn light" type="button" data-identity-cancel hidden>取消修改</button></div>
      </section>`;
    gate.addEventListener("click", event => {
      const button = event.target.closest("[data-identity]");
      if (button) saveIdentity(button.dataset.identity);
      if (event.target.closest("[data-identity-cancel]") && user()?.business_identity) {
        gate.hidden = true;
      }
    });
    document.body.appendChild(gate);
    return gate;
  }

  async function saveIdentity(identity) {
    if (saving || !IDENTITIES.has(identity)) return;
    const message = document.getElementById("businessIdentityMessage");
    saving = true;
    if (message) message.textContent = "正在保存经营身份…";
    document.querySelectorAll("#businessIdentityGate button").forEach(button => { button.disabled = true; });
    try {
      const response = await fetch("/api/business-identity", {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${token()}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ business_identity: identity })
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || payload.ok === false) throw new Error(payload.error || "经营身份保存失败");
      const currentUser = user();
      if (currentUser) {
        currentUser.business_identity = payload.business_identity;
        currentUser.business_identity_label = payload.business_identity_label;
        currentUser.workspaces = payload.workspaces;
      }
      const gate = ensureGate();
      gate.hidden = true;
      gate.dataset.editing = "";
      applyUser(currentUser, true);
    } catch (error) {
      if (message) message.textContent = error.message || "经营身份保存失败，请重试";
    } finally {
      saving = false;
      document.querySelectorAll("#businessIdentityGate button").forEach(button => { button.disabled = false; });
    }
  }

  function applyUser(currentUser, navigate) {
    if (!currentUser) {
      ensureGate().hidden = true;
      ensureSwitcher().hidden = true;
      ensureSettingsControl().hidden = true;
      return;
    }
    const identity = currentUser.business_identity || "";
    const isOwner = currentUser.is_owner === true || currentUser.role === "owner";
    const settings = ensureSettingsControl();
    settings.hidden = !isOwner;
    const settingsValue = document.getElementById("businessIdentitySettingsValue");
    if (settingsValue) settingsValue.textContent = currentUser.business_identity_label || {
      merchant: "接单商家",
      factory: "生产厂家",
      both: "接单＋生产"
    }[identity] || "尚未选择";
    if (!identity && isOwner) {
      const gate = ensureGate();
      gate.dataset.editing = "";
      gate.hidden = false;
      updateGateSelection("");
      ensureSwitcher().hidden = true;
      return;
    }
    ensureGate().hidden = true;
    const allowed = allowedWorkspaces(currentUser);
    const switcher = ensureSwitcher();
    switcher.hidden = true;
    setWorkspace(savedWorkspace(currentUser), navigate);
  }

  function observeUser() {
    const currentUser = user();
    const nextKey = currentUser
      ? `${currentUser.user_id || ""}:${currentUser.company_id || ""}:${currentUser.business_identity || ""}`
      : "";
    if (nextKey === lastUserKey) return;
    lastUserKey = nextKey;
    applyUser(currentUser, true);
  }

  window.BusinessWorkspace = { applyUser, setWorkspace, saveIdentity };
  document.addEventListener("DOMContentLoaded", () => {
    ensureGate();
    ensureSwitcher();
    ensureSettingsControl();
    observeUser();
    window.setInterval(observeUser, 500);
  });
})();
