var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/authentication/admin/ChannelAuthSetting/AuthenticationMethods/index.tsx
var AuthenticationMethods_exports = {};
__export(AuthenticationMethods_exports, {
  default: () => AuthenticationMethods_default
});
module.exports = __toCommonJS(AuthenticationMethods_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_icons = require("@ant-design/icons");
var import_classnames = __toESM(require("classnames"));
var import_utils = require("@pisell/utils");
var import_locales = __toESM(require("./locales"));
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var import_AuthMethods = __toESM(require("../../AuthMethods"));
var import_constants = require("../../AuthMethods/constants");
var import_AuthenticationMethods = require("./AuthenticationMethods.less");
var { Title, Paragraph, Text } = import_antd.Typography;
var convertApiDataToComponent = (apiData) => {
  const { method } = apiData;
  const processedKeys = /* @__PURE__ */ new Set();
  const authMethods = Object.keys(method).map((key) => {
    processedKeys.add(key);
    const methodData = method[key];
    const methodId = key === "phone" ? "phone" : key;
    const baseMethod = (0, import_constants.getDefaultAuthMethods)().find((m) => m.id === methodId);
    if (!baseMethod) {
      return null;
    }
    return {
      ...baseMethod,
      enabled: methodData.enabled,
      sort: methodData.sort
    };
  }).filter(Boolean);
  (0, import_constants.getDefaultAuthMethods)().forEach((defaultMethod) => {
    if (!processedKeys.has(defaultMethod.id)) {
      authMethods.push({
        ...defaultMethod,
        enabled: false
      });
    }
  });
  authMethods.sort((a, b) => {
    const sortA = a.sort ?? 0;
    const sortB = b.sort ?? 0;
    return sortA - sortB;
  });
  const globalMethods = authMethods.map((method2) => {
    const methodKey = method2.id === "phone" ? "phoneNumber" : method2.id;
    const labelMap = {
      email: { en: "Email", "zh-CN": "邮箱", "zh-HK": "郵箱", ja: "メール", pt: "E-mail" },
      phone: { en: "Phone Number", "zh-CN": "手机号", "zh-HK": "手機號", ja: "電話番号", pt: "Número de Telefone" },
      facebook: { en: "Facebook", "zh-CN": "Facebook", "zh-HK": "Facebook", ja: "Facebook", pt: "Facebook" },
      apple: { en: "Apple", "zh-CN": "Apple", "zh-HK": "Apple", ja: "Apple", pt: "Apple" },
      guest: { en: "Guest", "zh-CN": "访客", "zh-HK": "訪客", ja: "ゲスト", pt: "Convidado" }
    };
    return {
      method: methodKey,
      enabled: method2.enabled,
      label: labelMap[method2.id] || { en: method2.id, "zh-CN": method2.id, "zh-HK": method2.id }
    };
  });
  return { authMethods, globalMethods };
};
var mockGlobalMethods = [
  {
    method: "email",
    enabled: true,
    label: {
      en: "Email",
      "zh-CN": "邮箱",
      "zh-HK": "郵箱",
      ja: "メール",
      pt: "E-mail"
    }
  },
  {
    method: "phoneNumber",
    enabled: true,
    label: {
      en: "Phone Number",
      "zh-CN": "手机号",
      "zh-HK": "手機號",
      ja: "電話番号",
      pt: "Número de Telefone"
    }
  },
  {
    method: "facebook",
    enabled: true,
    label: {
      en: "Facebook",
      "zh-CN": "Facebook",
      "zh-HK": "Facebook",
      ja: "Facebook",
      pt: "Facebook"
    }
  },
  {
    method: "apple",
    enabled: true,
    label: {
      en: "Apple",
      "zh-CN": "Apple",
      "zh-HK": "Apple",
      ja: "Apple",
      pt: "Apple"
    }
  }
];
var AuthenticationMethods = ({
  className,
  style,
  value,
  onChange,
  globalMethods = mockGlobalMethods,
  onConfigureGlobal
}) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  import_utils.locales.init(import_locales.default, ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en");
  const { request, data, history } = context.appHelper.utils.getApp();
  const dataKey = "auth.customer";
  const [tenantId, setTenantId] = (0, import_react.useState)(null);
  const [loading, setLoading] = (0, import_react.useState)(true);
  const [mode, setMode] = (0, import_react.useState)("default");
  const [authMethods, setAuthMethods] = (0, import_react.useState)((0, import_constants.getDefaultAuthMethods)());
  const [fetchedGlobalMethods, setFetchedGlobalMethods] = (0, import_react.useState)(mockGlobalMethods);
  (0, import_react.useEffect)(() => {
    var _a2;
    const coreData = data.storage.getStorage("core");
    if (coreData) {
      try {
        const coreDataJson = JSON.parse(coreData);
        if ((_a2 = coreDataJson == null ? void 0 : coreDataJson.tenant) == null ? void 0 : _a2.id) {
          setTenantId(coreDataJson.tenant.id);
        }
      } catch (error) {
        console.error("Error parsing core data:", error);
      }
    }
  }, [data.storage]);
  (0, import_react.useEffect)(() => {
    if (tenantId) {
      setLoading(true);
      request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`).then((res) => {
        var _a2, _b2;
        console.log("res_customer_auth_methods", res);
        if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.length) {
          const data2 = (_b2 = res.data[0]) == null ? void 0 : _b2.value;
          const { authMethods: convertedAuthMethods, globalMethods: convertedGlobalMethods } = convertApiDataToComponent(data2);
          setFetchedGlobalMethods(convertedGlobalMethods);
          console.log("Converted data:", {
            authMethods: convertedAuthMethods,
            globalMethods: convertedGlobalMethods
          });
        }
        setLoading(false);
      }).catch((error) => {
        console.error("Error fetching tenant data:", error);
        setLoading(false);
      });
    }
  }, [tenantId, request]);
  (0, import_react.useEffect)(() => {
    if (value) {
      setMode(value.mode || "default");
      console.log("同步外部value - 输入的 value.methods:", value.methods);
      const updatedMethods = (0, import_constants.getDefaultAuthMethods)().map((method, index) => {
        var _a2;
        const methodKey = method.id === "phone" ? "phoneNumber" : method.id;
        const config = (_a2 = value.methods) == null ? void 0 : _a2[methodKey];
        if (config && typeof config === "object" && "enabled" in config) {
          return {
            ...method,
            enabled: config.enabled ?? method.enabled,
            sort: config.sort ?? index
          };
        }
        return {
          ...method,
          sort: method.sort ?? index
        };
      }).sort((a, b) => {
        const sortA = a.sort ?? 0;
        const sortB = b.sort ?? 0;
        return sortA - sortB;
      });
      console.log("同步外部value - 生成的 updatedMethods:", updatedMethods);
      setAuthMethods(updatedMethods);
    }
  }, [value]);
  const convertAuthMethodsToConfig = (methods) => {
    console.log("convertAuthMethodsToConfig - 输入的 methods:", methods);
    const config = {};
    methods.forEach((method, index) => {
      const key = method.id === "phone" ? "phoneNumber" : method.id;
      config[key] = {
        enabled: method.enabled,
        sort: method.sort ?? index
        // 优先使用 method.sort，如果没有则使用 index
      };
    });
    console.log("convertAuthMethodsToConfig - 输出的 config:", config);
    return config;
  };
  const handleModeChange = (e) => {
    setMode(e.target.value);
    onChange == null ? void 0 : onChange({
      mode: e.target.value,
      methods: convertAuthMethodsToConfig(authMethods)
    });
  };
  const handleConfigureGlobal = () => {
    history.push("/system-settings/auth/customer");
  };
  const handleOAuthConfig = () => {
    history.push("/system-settings/auth/oauth-config");
  };
  const handleAuthMethodsOrderChange = (methods) => {
    console.log("handleAuthMethodsOrderChange", methods);
    setAuthMethods(methods);
    onChange == null ? void 0 : onChange({
      mode,
      methods: convertAuthMethodsToConfig(methods)
    });
  };
  const handleAuthMethodsToggle = (method, enabled) => {
    const updatedMethods = authMethods.map((m) => m.id === method.id ? { ...m, enabled } : m);
    setAuthMethods(updatedMethods);
    setTimeout(() => {
      onChange == null ? void 0 : onChange({
        mode,
        methods: convertAuthMethodsToConfig(updatedMethods)
      });
    }, 0);
  };
  const renderMethodTag = (method) => {
    var _a2, _b2;
    const statusText = method.enabled ? import_utils.locales.getText("auth.methods.status.enabled") : import_utils.locales.getText("auth.methods.status.disabled");
    const locale = ((_b2 = (_a2 = context == null ? void 0 : context.engine) == null ? void 0 : _a2.props) == null ? void 0 : _b2.locale) || "en";
    const label = method.label[locale] || method.label.en;
    return /* @__PURE__ */ import_react.default.createElement("div", { key: method.method, className: "auth-method-item" }, /* @__PURE__ */ import_react.default.createElement("span", { className: `auth-method-status ${method.enabled ? "enabled" : "disabled"}` }, statusText), /* @__PURE__ */ import_react.default.createElement(Text, null, label));
  };
  if (loading) {
    return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("authentication-methods", className), style: { ...style, display: "flex", justifyContent: "center", alignItems: "center", minHeight: "400px" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { size: "large" }));
  }
  return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("authentication-methods", className), style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-upper" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 2, className: "authentication-methods-title" }, import_utils.locales.getText("auth.methods.title"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-mode" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Radio.Group, { value: mode, onChange: handleModeChange }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-mode-wrapper" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-mode-option" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Radio, { value: "default" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-mode-content" }, /* @__PURE__ */ import_react.default.createElement(Text, { strong: true, className: "authentication-methods-mode-title" }, import_utils.locales.getText("auth.methods.mode.default.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "authentication-methods-mode-description" }, import_utils.locales.getText("auth.methods.mode.default.description")), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      type: "link",
      className: "authentication-methods-configure-link",
      onClick: handleConfigureGlobal,
      style: { padding: 0, height: "auto" }
    },
    import_utils.locales.getText("auth.methods.mode.default.configure")
  )))), /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-mode-option" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Radio, { value: "custom" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-mode-content" }, /* @__PURE__ */ import_react.default.createElement(Text, { strong: true, className: "authentication-methods-mode-title" }, import_utils.locales.getText("auth.methods.mode.custom.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "authentication-methods-mode-description" }, import_utils.locales.getText("auth.methods.mode.custom.description"))))))))), /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-middle" }, mode === "default" && /* @__PURE__ */ import_react.default.createElement(
    import_antd.Alert,
    {
      message: import_utils.locales.getText("auth.methods.preview.title"),
      description: import_utils.locales.getText("auth.methods.preview.description"),
      type: "info",
      showIcon: true,
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.InfoCircleOutlined, null)
    }
  ), mode === "custom" && /* @__PURE__ */ import_react.default.createElement(
    import_antd.Alert,
    {
      message: import_utils.locales.getText("auth.methods.custom.warning.title"),
      description: import_utils.locales.getText("auth.methods.custom.warning.description"),
      type: "warning",
      showIcon: true
    }
  )), /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-lower" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-customer" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-customer-left" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-customer-header" }, /* @__PURE__ */ import_react.default.createElement(import_icons.UserOutlined, { className: "authentication-methods-customer-icon" }), /* @__PURE__ */ import_react.default.createElement(Title, { level: 4, className: "authentication-methods-customer-title" }, import_utils.locales.getText("auth.methods.customer.title"))), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "authentication-methods-customer-description" }, import_utils.locales.getText("auth.methods.customer.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-customer-right" }, mode === "default" ? (
    // Default mode: Show inherited methods list
    /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-inherited" }, /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "authentication-methods-inherited-title" }, import_utils.locales.getText("auth.methods.preview.inherited")), /* @__PURE__ */ import_react.default.createElement("div", { className: "authentication-methods-list" }, fetchedGlobalMethods.map(renderMethodTag)))
  ) : (
    // Custom mode: Show AuthMethods component
    /* @__PURE__ */ import_react.default.createElement(
      import_AuthMethods.default,
      {
        methods: authMethods,
        onOrderChange: handleAuthMethodsOrderChange,
        onToggle: handleAuthMethodsToggle,
        onConfigClick: handleOAuthConfig,
        enableSetting: false
      }
    )
  )))));
};
var AuthenticationMethods_default = AuthenticationMethods;
