function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useState, useEffect } from 'react';
import { Switch, Empty } from 'antd';
import { Button } from '@pisell/materials';
import { HolderOutlined, SettingOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import classNames from 'classnames';
import { locales } from '@pisell/utils';
import { AuthMethodCategory } from "./types";
import { getDefaultAuthMethods } from "./constants";
import localeTexts from "./locales";
import useEngineContext from "../../../../hooks/useEngineContext";
import "./AuthMethods.less";
var SortableItem = function SortableItem(_ref) {
  var method = _ref.method,
    onToggle = _ref.onToggle,
    onSettings = _ref.onSettings,
    onConfigClick = _ref.onConfigClick,
    _ref$enableSetting = _ref.enableSetting,
    enableSetting = _ref$enableSetting === void 0 ? true : _ref$enableSetting;
  var _useSortable = useSortable({
      id: method.id
    }),
    attributes = _useSortable.attributes,
    listeners = _useSortable.listeners,
    setNodeRef = _useSortable.setNodeRef,
    transform = _useSortable.transform,
    transition = _useSortable.transition,
    isDragging = _useSortable.isDragging;
  var style = {
    transform: CSS.Transform.toString(transform),
    transition: transition
  };
  var getCategoryClassName = function getCategoryClassName(category) {
    var _category$toLowerCase;
    return category === null || category === void 0 || (_category$toLowerCase = category.toLowerCase()) === null || _category$toLowerCase === void 0 ? void 0 : _category$toLowerCase.replace(/[^a-z0-9]/g, '-');
  };
  var getCategoryText = function getCategoryText(category) {
    var categoryMap = _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, AuthMethodCategory.GENERAL, 'auth.category.general'), AuthMethodCategory.PASSWORD_FREE, 'auth.category.password-free'), AuthMethodCategory.AUTH_FREE, 'auth.category.auth-free'), AuthMethodCategory.OAUTH, 'auth.category.oauth');
    return locales.getText(categoryMap[category] || category);
  };
  return /*#__PURE__*/React.createElement("div", {
    ref: setNodeRef,
    style: style,
    className: classNames('auth-methods-item', {
      'auth-methods-dragging': isDragging
    })
  }, /*#__PURE__*/React.createElement("div", _extends({
    className: "auth-methods-item-drag"
  }, attributes, listeners), /*#__PURE__*/React.createElement(HolderOutlined, null)), /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-body"
  }, /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-icon"
  }, method.icon), /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-header"
  }, /*#__PURE__*/React.createElement("span", {
    className: "auth-methods-item-title"
  }, method.title), /*#__PURE__*/React.createElement("span", {
    className: classNames('auth-methods-item-category', getCategoryClassName(method.category))
  }, getCategoryText(method.category))), /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-description"
  }, method.description), method.configLink && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    style: {
      marginTop: 8,
      fontSize: 12,
      color: '#8c8c8c',
      display: 'flex',
      alignItems: 'center',
      gap: 4
    }
  }, /*#__PURE__*/React.createElement(InfoCircleOutlined, {
    style: {
      marginRight: 4
    }
  }), locales.getText(method.configLink), /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-config-link",
    onClick: onConfigClick
  }, /*#__PURE__*/React.createElement("span", null, locales.getText('auth.oauth.config.link')))))), /*#__PURE__*/React.createElement("div", {
    className: "auth-methods-item-actions"
  }, enableSetting && method.hasSettings && /*#__PURE__*/React.createElement(Button, {
    type: "default",
    icon: /*#__PURE__*/React.createElement(SettingOutlined, null),
    onClick: function onClick() {
      return onSettings();
    }
  }, locales.getText('auth.button.settings')), /*#__PURE__*/React.createElement(Switch, {
    checked: method.enabled,
    onChange: onToggle,
    disabled: method.disableToggle
  }))));
};
var AuthMethods = function AuthMethods(_ref2) {
  var _context$engine;
  var className = _ref2.className,
    style = _ref2.style,
    initialMethods = _ref2.methods,
    onOrderChange = _ref2.onOrderChange,
    onToggle = _ref2.onToggle,
    onSettings = _ref2.onSettings,
    onConfigClick = _ref2.onConfigClick,
    _ref2$enableSetting = _ref2.enableSetting,
    enableSetting = _ref2$enableSetting === void 0 ? true : _ref2$enableSetting;
  var context = useEngineContext();
  locales.init(localeTexts, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en');
  var _useState = useState(initialMethods || getDefaultAuthMethods()),
    _useState2 = _slicedToArray(_useState, 2),
    methods = _useState2[0],
    setMethods = _useState2[1];

  // 同步父组件传入的 methods
  useEffect(function () {
    if (initialMethods && initialMethods.length > 0) {
      console.log('AuthMethods 组件同步父组件数据:', initialMethods);
      // 确保按照 sort 字段排序
      var sortedMethods = _toConsumableArray(initialMethods).sort(function (a, b) {
        var _a$sort, _b$sort;
        var sortA = (_a$sort = a.sort) !== null && _a$sort !== void 0 ? _a$sort : 0;
        var sortB = (_b$sort = b.sort) !== null && _b$sort !== void 0 ? _b$sort : 0;
        return sortA - sortB;
      });
      setMethods(sortedMethods);
    }
  }, [initialMethods]);
  var sensors = useSensors(useSensor(PointerSensor, {
    activationConstraint: {
      distance: 8
    }
  }), useSensor(KeyboardSensor, {
    coordinateGetter: sortableKeyboardCoordinates
  }));
  var handleDragEnd = function handleDragEnd(event) {
    var active = event.active,
      over = event.over;
    if (over && active.id !== over.id) {
      setMethods(function (items) {
        var oldIndex = items.findIndex(function (item) {
          return item.id === active.id;
        });
        var newIndex = items.findIndex(function (item) {
          return item.id === over.id;
        });
        var newItems = arrayMove(items, oldIndex, newIndex);

        // 更新每个 item 的 sort 字段以反映新的顺序
        var updatedItems = newItems.map(function (item, index) {
          return _objectSpread(_objectSpread({}, item), {}, {
            sort: index
          });
        });
        onOrderChange === null || onOrderChange === void 0 || onOrderChange(updatedItems);
        return updatedItems;
      });
    }
  };
  var handleToggle = function handleToggle(method, enabled) {
    console.log('AuthMethods handleToggle:', method.id, enabled);
    setMethods(function (items) {
      return items.map(function (item) {
        return item.id === method.id ? _objectSpread(_objectSpread({}, item), {}, {
          enabled: enabled
        }) : item;
      });
    });
    onToggle === null || onToggle === void 0 || onToggle(method, enabled);
  };
  var handleSettings = function handleSettings(method) {
    onSettings === null || onSettings === void 0 || onSettings(method);
  };
  var handleConfigClick = function handleConfigClick(method) {
    onConfigClick === null || onConfigClick === void 0 || onConfigClick(method);
  };
  if (!methods || methods.length === 0) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('auth-methods', className),
      style: style
    }, /*#__PURE__*/React.createElement("div", {
      className: "auth-methods-empty"
    }, /*#__PURE__*/React.createElement(Empty, {
      description: "No authentication methods available"
    })));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('auth-methods', className),
    style: style
  }, /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    collisionDetection: closestCenter,
    onDragEnd: handleDragEnd
  }, /*#__PURE__*/React.createElement(SortableContext, {
    items: methods.map(function (m) {
      return m.id;
    }),
    strategy: verticalListSortingStrategy
  }, methods.map(function (method) {
    return /*#__PURE__*/React.createElement(SortableItem, {
      key: method.id,
      method: method,
      onToggle: function onToggle(enabled) {
        return handleToggle(method, enabled);
      },
      onSettings: function onSettings() {
        return handleSettings(method);
      },
      onConfigClick: method.configLink ? function () {
        return handleConfigClick(method);
      } : undefined,
      enableSetting: enableSetting
    });
  }))));
};
export default AuthMethods;
export { default as SettingList } from "./SettingList";
export { AuthMethodType, AuthMethodCategory } from "./types";