UNPKG

reactchessts

Version:

React TypeScript chess development toolkit

2,046 lines • 86.5 kB
import require$$0, { useState, useCallback, useEffect, createContext, useContext, memo, useRef, useMemo } from "react";
import { createPortal } from "react-dom";
import { Chess } from "chess.js";
var jsxRuntime = { exports: {} };
var reactJsxRuntime_production_min = {};
/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactJsxRuntime_production_min;
function requireReactJsxRuntime_production_min() {
  if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
  hasRequiredReactJsxRuntime_production_min = 1;
  var f = require$$0, k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true };
  function q(c, a, g) {
    var b, d = {}, e = null, h = null;
    void 0 !== g && (e = "" + g);
    void 0 !== a.key && (e = "" + a.key);
    void 0 !== a.ref && (h = a.ref);
    for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
    if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]);
    return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current };
  }
  reactJsxRuntime_production_min.Fragment = l;
  reactJsxRuntime_production_min.jsx = q;
  reactJsxRuntime_production_min.jsxs = q;
  return reactJsxRuntime_production_min;
}
var reactJsxRuntime_development = {};
/**
 * @license React
 * react-jsx-runtime.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hasRequiredReactJsxRuntime_development;
function requireReactJsxRuntime_development() {
  if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
  hasRequiredReactJsxRuntime_development = 1;
  if (process.env.NODE_ENV !== "production") {
    (function() {
      var React = require$$0;
      var REACT_ELEMENT_TYPE = Symbol.for("react.element");
      var REACT_PORTAL_TYPE = Symbol.for("react.portal");
      var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
      var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
      var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
      var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
      var REACT_CONTEXT_TYPE = Symbol.for("react.context");
      var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
      var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
      var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
      var REACT_MEMO_TYPE = Symbol.for("react.memo");
      var REACT_LAZY_TYPE = Symbol.for("react.lazy");
      var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
      var FAUX_ITERATOR_SYMBOL = "@@iterator";
      function getIteratorFn(maybeIterable) {
        if (maybeIterable === null || typeof maybeIterable !== "object") {
          return null;
        }
        var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
        if (typeof maybeIterator === "function") {
          return maybeIterator;
        }
        return null;
      }
      var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      function error(format) {
        {
          {
            for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
              args[_key2 - 1] = arguments[_key2];
            }
            printWarning("error", format, args);
          }
        }
      }
      function printWarning(level, format, args) {
        {
          var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
          var stack = ReactDebugCurrentFrame2.getStackAddendum();
          if (stack !== "") {
            format += "%s";
            args = args.concat([stack]);
          }
          var argsWithFormat = args.map(function(item) {
            return String(item);
          });
          argsWithFormat.unshift("Warning: " + format);
          Function.prototype.apply.call(console[level], console, argsWithFormat);
        }
      }
      var enableScopeAPI = false;
      var enableCacheElement = false;
      var enableTransitionTracing = false;
      var enableLegacyHidden = false;
      var enableDebugTracing = false;
      var REACT_MODULE_REFERENCE;
      {
        REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
      }
      function isValidElementType(type) {
        if (typeof type === "string" || typeof type === "function") {
          return true;
        }
        if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
          return true;
        }
        if (typeof type === "object" && type !== null) {
          if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
          // types supported by any Flight configuration anywhere since
          // we don't know which Flight build this will end up being used
          // with.
          type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) {
            return true;
          }
        }
        return false;
      }
      function getWrappedName(outerType, innerType, wrapperName) {
        var displayName = outerType.displayName;
        if (displayName) {
          return displayName;
        }
        var functionName = innerType.displayName || innerType.name || "";
        return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
      }
      function getContextName(type) {
        return type.displayName || "Context";
      }
      function getComponentNameFromType(type) {
        if (type == null) {
          return null;
        }
        {
          if (typeof type.tag === "number") {
            error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
          }
        }
        if (typeof type === "function") {
          return type.displayName || type.name || null;
        }
        if (typeof type === "string") {
          return type;
        }
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
        }
        if (typeof type === "object") {
          switch (type.$$typeof) {
            case REACT_CONTEXT_TYPE:
              var context = type;
              return getContextName(context) + ".Consumer";
            case REACT_PROVIDER_TYPE:
              var provider = type;
              return getContextName(provider._context) + ".Provider";
            case REACT_FORWARD_REF_TYPE:
              return getWrappedName(type, type.render, "ForwardRef");
            case REACT_MEMO_TYPE:
              var outerName = type.displayName || null;
              if (outerName !== null) {
                return outerName;
              }
              return getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE: {
              var lazyComponent = type;
              var payload = lazyComponent._payload;
              var init = lazyComponent._init;
              try {
                return getComponentNameFromType(init(payload));
              } catch (x) {
                return null;
              }
            }
          }
        }
        return null;
      }
      var assign = Object.assign;
      var disabledDepth = 0;
      var prevLog;
      var prevInfo;
      var prevWarn;
      var prevError;
      var prevGroup;
      var prevGroupCollapsed;
      var prevGroupEnd;
      function disabledLog() {
      }
      disabledLog.__reactDisabledLog = true;
      function disableLogs() {
        {
          if (disabledDepth === 0) {
            prevLog = console.log;
            prevInfo = console.info;
            prevWarn = console.warn;
            prevError = console.error;
            prevGroup = console.group;
            prevGroupCollapsed = console.groupCollapsed;
            prevGroupEnd = console.groupEnd;
            var props = {
              configurable: true,
              enumerable: true,
              value: disabledLog,
              writable: true
            };
            Object.defineProperties(console, {
              info: props,
              log: props,
              warn: props,
              error: props,
              group: props,
              groupCollapsed: props,
              groupEnd: props
            });
          }
          disabledDepth++;
        }
      }
      function reenableLogs() {
        {
          disabledDepth--;
          if (disabledDepth === 0) {
            var props = {
              configurable: true,
              enumerable: true,
              writable: true
            };
            Object.defineProperties(console, {
              log: assign({}, props, {
                value: prevLog
              }),
              info: assign({}, props, {
                value: prevInfo
              }),
              warn: assign({}, props, {
                value: prevWarn
              }),
              error: assign({}, props, {
                value: prevError
              }),
              group: assign({}, props, {
                value: prevGroup
              }),
              groupCollapsed: assign({}, props, {
                value: prevGroupCollapsed
              }),
              groupEnd: assign({}, props, {
                value: prevGroupEnd
              })
            });
          }
          if (disabledDepth < 0) {
            error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
          }
        }
      }
      var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
      var prefix;
      function describeBuiltInComponentFrame(name, source, ownerFn) {
        {
          if (prefix === void 0) {
            try {
              throw Error();
            } catch (x) {
              var match = x.stack.trim().match(/\n( *(at )?)/);
              prefix = match && match[1] || "";
            }
          }
          return "\n" + prefix + name;
        }
      }
      var reentry = false;
      var componentFrameCache;
      {
        var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
        componentFrameCache = new PossiblyWeakMap();
      }
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) {
          return "";
        }
        {
          var frame = componentFrameCache.get(fn);
          if (frame !== void 0) {
            return frame;
          }
        }
        var control;
        reentry = true;
        var previousPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var previousDispatcher;
        {
          previousDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = null;
          disableLogs();
        }
        try {
          if (construct) {
            var Fake = function() {
              throw Error();
            };
            Object.defineProperty(Fake.prototype, "props", {
              set: function() {
                throw Error();
              }
            });
            if (typeof Reflect === "object" && Reflect.construct) {
              try {
                Reflect.construct(Fake, []);
              } catch (x) {
                control = x;
              }
              Reflect.construct(fn, [], Fake);
            } else {
              try {
                Fake.call();
              } catch (x) {
                control = x;
              }
              fn.call(Fake.prototype);
            }
          } else {
            try {
              throw Error();
            } catch (x) {
              control = x;
            }
            fn();
          }
        } catch (sample) {
          if (sample && control && typeof sample.stack === "string") {
            var sampleLines = sample.stack.split("\n");
            var controlLines = control.stack.split("\n");
            var s = sampleLines.length - 1;
            var c = controlLines.length - 1;
            while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
              c--;
            }
            for (; s >= 1 && c >= 0; s--, c--) {
              if (sampleLines[s] !== controlLines[c]) {
                if (s !== 1 || c !== 1) {
                  do {
                    s--;
                    c--;
                    if (c < 0 || sampleLines[s] !== controlLines[c]) {
                      var _frame = "\n" + sampleLines[s].replace(" at new ", " at ");
                      if (fn.displayName && _frame.includes("<anonymous>")) {
                        _frame = _frame.replace("<anonymous>", fn.displayName);
                      }
                      {
                        if (typeof fn === "function") {
                          componentFrameCache.set(fn, _frame);
                        }
                      }
                      return _frame;
                    }
                  } while (s >= 1 && c >= 0);
                }
                break;
              }
            }
          }
        } finally {
          reentry = false;
          {
            ReactCurrentDispatcher.current = previousDispatcher;
            reenableLogs();
          }
          Error.prepareStackTrace = previousPrepareStackTrace;
        }
        var name = fn ? fn.displayName || fn.name : "";
        var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
        {
          if (typeof fn === "function") {
            componentFrameCache.set(fn, syntheticFrame);
          }
        }
        return syntheticFrame;
      }
      function describeFunctionComponentFrame(fn, source, ownerFn) {
        {
          return describeNativeComponentFrame(fn, false);
        }
      }
      function shouldConstruct(Component) {
        var prototype = Component.prototype;
        return !!(prototype && prototype.isReactComponent);
      }
      function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
        if (type == null) {
          return "";
        }
        if (typeof type === "function") {
          {
            return describeNativeComponentFrame(type, shouldConstruct(type));
          }
        }
        if (typeof type === "string") {
          return describeBuiltInComponentFrame(type);
        }
        switch (type) {
          case REACT_SUSPENSE_TYPE:
            return describeBuiltInComponentFrame("Suspense");
          case REACT_SUSPENSE_LIST_TYPE:
            return describeBuiltInComponentFrame("SuspenseList");
        }
        if (typeof type === "object") {
          switch (type.$$typeof) {
            case REACT_FORWARD_REF_TYPE:
              return describeFunctionComponentFrame(type.render);
            case REACT_MEMO_TYPE:
              return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
            case REACT_LAZY_TYPE: {
              var lazyComponent = type;
              var payload = lazyComponent._payload;
              var init = lazyComponent._init;
              try {
                return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
              } catch (x) {
              }
            }
          }
        }
        return "";
      }
      var hasOwnProperty = Object.prototype.hasOwnProperty;
      var loggedTypeFailures = {};
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame.setExtraStackFrame(null);
          }
        }
      }
      function checkPropTypes(typeSpecs, values, location, componentName, element) {
        {
          var has = Function.call.bind(hasOwnProperty);
          for (var typeSpecName in typeSpecs) {
            if (has(typeSpecs, typeSpecName)) {
              var error$1 = void 0;
              try {
                if (typeof typeSpecs[typeSpecName] !== "function") {
                  var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                  err.name = "Invariant Violation";
                  throw err;
                }
                error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
              } catch (ex) {
                error$1 = ex;
              }
              if (error$1 && !(error$1 instanceof Error)) {
                setCurrentlyValidatingElement(element);
                error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
                setCurrentlyValidatingElement(null);
              }
              if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                loggedTypeFailures[error$1.message] = true;
                setCurrentlyValidatingElement(element);
                error("Failed %s type: %s", location, error$1.message);
                setCurrentlyValidatingElement(null);
              }
            }
          }
        }
      }
      var isArrayImpl = Array.isArray;
      function isArray(a) {
        return isArrayImpl(a);
      }
      function typeName(value) {
        {
          var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
          var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          return type;
        }
      }
      function willCoercionThrow(value) {
        {
          try {
            testStringCoercion(value);
            return false;
          } catch (e) {
            return true;
          }
        }
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkKeyStringCoercion(value) {
        {
          if (willCoercionThrow(value)) {
            error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
      var RESERVED_PROPS = {
        key: true,
        ref: true,
        __self: true,
        __source: true
      };
      var specialPropKeyWarningShown;
      var specialPropRefWarningShown;
      function hasValidRef(config) {
        {
          if (hasOwnProperty.call(config, "ref")) {
            var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
            if (getter && getter.isReactWarning) {
              return false;
            }
          }
        }
        return config.ref !== void 0;
      }
      function hasValidKey(config) {
        {
          if (hasOwnProperty.call(config, "key")) {
            var getter = Object.getOwnPropertyDescriptor(config, "key").get;
            if (getter && getter.isReactWarning) {
              return false;
            }
          }
        }
        return config.key !== void 0;
      }
      function warnIfStringRefCannotBeAutoConverted(config, self) {
        {
          if (typeof config.ref === "string" && ReactCurrentOwner.current && self) ;
        }
      }
      function defineKeyPropWarningGetter(props, displayName) {
        {
          var warnAboutAccessingKey = function() {
            if (!specialPropKeyWarningShown) {
              specialPropKeyWarningShown = true;
              error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
            }
          };
          warnAboutAccessingKey.isReactWarning = true;
          Object.defineProperty(props, "key", {
            get: warnAboutAccessingKey,
            configurable: true
          });
        }
      }
      function defineRefPropWarningGetter(props, displayName) {
        {
          var warnAboutAccessingRef = function() {
            if (!specialPropRefWarningShown) {
              specialPropRefWarningShown = true;
              error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
            }
          };
          warnAboutAccessingRef.isReactWarning = true;
          Object.defineProperty(props, "ref", {
            get: warnAboutAccessingRef,
            configurable: true
          });
        }
      }
      var ReactElement = function(type, key, ref, self, source, owner, props) {
        var element = {
          // This tag allows us to uniquely identify this as a React Element
          $$typeof: REACT_ELEMENT_TYPE,
          // Built-in properties that belong on the element
          type,
          key,
          ref,
          props,
          // Record the component responsible for creating this element.
          _owner: owner
        };
        {
          element._store = {};
          Object.defineProperty(element._store, "validated", {
            configurable: false,
            enumerable: false,
            writable: true,
            value: false
          });
          Object.defineProperty(element, "_self", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: self
          });
          Object.defineProperty(element, "_source", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: source
          });
          if (Object.freeze) {
            Object.freeze(element.props);
            Object.freeze(element);
          }
        }
        return element;
      };
      function jsxDEV(type, config, maybeKey, source, self) {
        {
          var propName;
          var props = {};
          var key = null;
          var ref = null;
          if (maybeKey !== void 0) {
            {
              checkKeyStringCoercion(maybeKey);
            }
            key = "" + maybeKey;
          }
          if (hasValidKey(config)) {
            {
              checkKeyStringCoercion(config.key);
            }
            key = "" + config.key;
          }
          if (hasValidRef(config)) {
            ref = config.ref;
            warnIfStringRefCannotBeAutoConverted(config, self);
          }
          for (propName in config) {
            if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
              props[propName] = config[propName];
            }
          }
          if (type && type.defaultProps) {
            var defaultProps = type.defaultProps;
            for (propName in defaultProps) {
              if (props[propName] === void 0) {
                props[propName] = defaultProps[propName];
              }
            }
          }
          if (key || ref) {
            var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
            if (key) {
              defineKeyPropWarningGetter(props, displayName);
            }
            if (ref) {
              defineRefPropWarningGetter(props, displayName);
            }
          }
          return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
        }
      }
      var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
      var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement$1(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame$1.setExtraStackFrame(null);
          }
        }
      }
      var propTypesMisspellWarningShown;
      {
        propTypesMisspellWarningShown = false;
      }
      function isValidElement(object) {
        {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
      }
      function getDeclarationErrorAddendum() {
        {
          if (ReactCurrentOwner$1.current) {
            var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
            if (name) {
              return "\n\nCheck the render method of `" + name + "`.";
            }
          }
          return "";
        }
      }
      function getSourceInfoErrorAddendum(source) {
        {
          return "";
        }
      }
      var ownerHasKeyUseWarning = {};
      function getCurrentComponentErrorInfo(parentType) {
        {
          var info = getDeclarationErrorAddendum();
          if (!info) {
            var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
            if (parentName) {
              info = "\n\nCheck the top-level render call using <" + parentName + ">.";
            }
          }
          return info;
        }
      }
      function validateExplicitKey(element, parentType) {
        {
          if (!element._store || element._store.validated || element.key != null) {
            return;
          }
          element._store.validated = true;
          var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
          if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
            return;
          }
          ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
          var childOwner = "";
          if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
            childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
          }
          setCurrentlyValidatingElement$1(element);
          error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
          setCurrentlyValidatingElement$1(null);
        }
      }
      function validateChildKeys(node, parentType) {
        {
          if (typeof node !== "object") {
            return;
          }
          if (isArray(node)) {
            for (var i = 0; i < node.length; i++) {
              var child = node[i];
              if (isValidElement(child)) {
                validateExplicitKey(child, parentType);
              }
            }
          } else if (isValidElement(node)) {
            if (node._store) {
              node._store.validated = true;
            }
          } else if (node) {
            var iteratorFn = getIteratorFn(node);
            if (typeof iteratorFn === "function") {
              if (iteratorFn !== node.entries) {
                var iterator = iteratorFn.call(node);
                var step;
                while (!(step = iterator.next()).done) {
                  if (isValidElement(step.value)) {
                    validateExplicitKey(step.value, parentType);
                  }
                }
              }
            }
          }
        }
      }
      function validatePropTypes(element) {
        {
          var type = element.type;
          if (type === null || type === void 0 || typeof type === "string") {
            return;
          }
          var propTypes;
          if (typeof type === "function") {
            propTypes = type.propTypes;
          } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
          // Inner props are checked in the reconciler.
          type.$$typeof === REACT_MEMO_TYPE)) {
            propTypes = type.propTypes;
          } else {
            return;
          }
          if (propTypes) {
            var name = getComponentNameFromType(type);
            checkPropTypes(propTypes, element.props, "prop", name, element);
          } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
            propTypesMisspellWarningShown = true;
            var _name = getComponentNameFromType(type);
            error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
          }
          if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
            error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
          }
        }
      }
      function validateFragmentProps(fragment) {
        {
          var keys = Object.keys(fragment.props);
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (key !== "children" && key !== "key") {
              setCurrentlyValidatingElement$1(fragment);
              error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
              setCurrentlyValidatingElement$1(null);
              break;
            }
          }
          if (fragment.ref !== null) {
            setCurrentlyValidatingElement$1(fragment);
            error("Invalid attribute `ref` supplied to `React.Fragment`.");
            setCurrentlyValidatingElement$1(null);
          }
        }
      }
      var didWarnAboutKeySpread = {};
      function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
        {
          var validType = isValidElementType(type);
          if (!validType) {
            var info = "";
            if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
              info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            }
            var sourceInfo = getSourceInfoErrorAddendum();
            if (sourceInfo) {
              info += sourceInfo;
            } else {
              info += getDeclarationErrorAddendum();
            }
            var typeString;
            if (type === null) {
              typeString = "null";
            } else if (isArray(type)) {
              typeString = "array";
            } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
              typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
              info = " Did you accidentally export a JSX literal instead of a component?";
            } else {
              typeString = typeof type;
            }
            error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
          }
          var element = jsxDEV(type, props, key, source, self);
          if (element == null) {
            return element;
          }
          if (validType) {
            var children = props.children;
            if (children !== void 0) {
              if (isStaticChildren) {
                if (isArray(children)) {
                  for (var i = 0; i < children.length; i++) {
                    validateChildKeys(children[i], type);
                  }
                  if (Object.freeze) {
                    Object.freeze(children);
                  }
                } else {
                  error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
                }
              } else {
                validateChildKeys(children, type);
              }
            }
          }
          {
            if (hasOwnProperty.call(props, "key")) {
              var componentName = getComponentNameFromType(type);
              var keys = Object.keys(props).filter(function(k) {
                return k !== "key";
              });
              var beforeExample = keys.length > 0 ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
              if (!didWarnAboutKeySpread[componentName + beforeExample]) {
                var afterExample = keys.length > 0 ? "{" + keys.join(": ..., ") + ": ...}" : "{}";
                error('A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
                didWarnAboutKeySpread[componentName + beforeExample] = true;
              }
            }
          }
          if (type === REACT_FRAGMENT_TYPE) {
            validateFragmentProps(element);
          } else {
            validatePropTypes(element);
          }
          return element;
        }
      }
      function jsxWithValidationStatic(type, props, key) {
        {
          return jsxWithValidation(type, props, key, true);
        }
      }
      function jsxWithValidationDynamic(type, props, key) {
        {
          return jsxWithValidation(type, props, key, false);
        }
      }
      var jsx = jsxWithValidationDynamic;
      var jsxs = jsxWithValidationStatic;
      reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
      reactJsxRuntime_development.jsx = jsx;
      reactJsxRuntime_development.jsxs = jsxs;
    })();
  }
  return reactJsxRuntime_development;
}
if (process.env.NODE_ENV === "production") {
  jsxRuntime.exports = requireReactJsxRuntime_production_min();
} else {
  jsxRuntime.exports = requireReactJsxRuntime_development();
}
var jsxRuntimeExports = jsxRuntime.exports;
const UNICODE_PIECES = {
  wp: "♙",
  wn: "♘",
  wb: "♗",
  wr: "♖",
  wq: "♕",
  wk: "♔",
  bp: "♟",
  bn: "♞",
  bb: "♝",
  br: "♜",
  bq: "♛",
  bk: "♚"
};
const DEFAULT_PIECES = [
  "wp",
  "wn",
  "wb",
  "wr",
  "wq",
  "wk",
  "bp",
  "bn",
  "bb",
  "br",
  "bq",
  "bk"
];
const PIECE_NAMES = {
  p: "pawn",
  n: "knight",
  b: "bishop",
  r: "rook",
  q: "queen",
  k: "king"
};
const wp = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cpath%20d='m%2022.5,9%20c%20-2.21,0%20-4,1.79%20-4,4%200,0.89%200.29,1.71%200.78,2.38%20C%2017.33,16.5%2016,18.59%2016,21%20c%200,2.03%200.94,3.84%202.41,5.03%20C%2015.41,27.09%2011,31.58%2011,39.5%20H%2034%20C%2034,31.58%2029.59,27.09%2026.59,26.03%2028.06,24.84%2029,23.03%2029,21%2029,18.59%2027.67,16.5%2025.72,15.38%2026.21,14.71%2026.5,13.89%2026.5,13%20c%200,-2.21%20-1.79,-4%20-4,-4%20z'%20style='opacity:1;%20fill:%23ffffff;%20fill-opacity:1;%20fill-rule:nonzero;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;%20stroke-linejoin:miter;%20stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'/%3e%3c/svg%3e";
const wn = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='opacity:1;%20fill:none;%20fill-opacity:1;%20fill-rule:evenodd;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%20transform='translate(0,0.3)'%3e%3cpath%20d='M%2022,10%20C%2032.5,11%2038.5,18%2038,39%20L%2015,39%20C%2015,30%2025,32.5%2023,18'%20style='fill:%23ffffff;%20stroke:%23000000;'%20/%3e%3cpath%20d='M%2024,18%20C%2024.38,20.91%2018.45,25.37%2016,27%20C%2013,29%2013.18,31.34%2011,31%20C%209.958,30.06%2012.41,27.96%2011,28%20C%2010,28%2011.19,29.23%2010,30%20C%209,30%205.997,31%206,26%20C%206,24%2012,14%2012,14%20C%2012,14%2013.89,12.1%2014,10.5%20C%2013.27,9.506%2013.5,8.5%2013.5,7.5%20C%2014.5,6.5%2016.5,10%2016.5,10%20L%2018.5,10%20C%2018.5,10%2019.28,8.008%2021,7%20C%2022,7%2022,10%2022,10'%20style='fill:%23ffffff;%20stroke:%23000000;'%20/%3e%3cpath%20d='M%209.5%2025.5%20A%200.5%200.5%200%201%201%208.5,25.5%20A%200.5%200.5%200%201%201%209.5%2025.5%20z'%20style='fill:%23000000;%20stroke:%23000000;'%20/%3e%3cpath%20d='M%2015%2015.5%20A%200.5%201.5%200%201%201%2014,15.5%20A%200.5%201.5%200%201%201%2015%2015.5%20z'%20transform='matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)'%20style='fill:%23000000;%20stroke:%23000000;'%20/%3e%3c/g%3e%3c/svg%3e";
const wb = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='opacity:1;%20fill:none;%20fill-rule:evenodd;%20fill-opacity:1;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;%20stroke-linejoin:round;%20stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%20transform='translate(0,0.6)'%3e%3cg%20style='fill:%23ffffff;%20stroke:%23000000;%20stroke-linecap:butt;'%3e%3cpath%20d='M%209,36%20C%2012.39,35.03%2019.11,36.43%2022.5,34%20C%2025.89,36.43%2032.61,35.03%2036,36%20C%2036,36%2037.65,36.54%2039,38%20C%2038.32,38.97%2037.35,38.99%2036,38.5%20C%2032.61,37.53%2025.89,38.96%2022.5,37.5%20C%2019.11,38.96%2012.39,37.53%209,38.5%20C%207.65,38.99%206.68,38.97%206,38%20C%207.35,36.54%209,36%209,36%20z'/%3e%3cpath%20d='M%2015,32%20C%2017.5,34.5%2027.5,34.5%2030,32%20C%2030.5,30.5%2030,30%2030,30%20C%2030,27.5%2027.5,26%2027.5,26%20C%2033,24.5%2033.5,14.5%2022.5,10.5%20C%2011.5,14.5%2012,24.5%2017.5,26%20C%2017.5,26%2015,27.5%2015,30%20C%2015,30%2014.5,30.5%2015,32%20z'/%3e%3cpath%20d='M%2025%208%20A%202.5%202.5%200%201%201%2020,8%20A%202.5%202.5%200%201%201%2025%208%20z'/%3e%3c/g%3e%3cpath%20d='M%2017.5,26%20L%2027.5,26%20M%2015,30%20L%2030,30%20M%2022.5,15.5%20L%2022.5,20.5%20M%2020,18%20L%2025,18'%20style='fill:none;%20stroke:%23000000;%20stroke-linejoin:miter;'/%3e%3c/g%3e%3c/svg%3e";
const wr = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='opacity:1;%20fill:%23ffffff;%20fill-opacity:1;%20fill-rule:evenodd;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%20transform='translate(0,0.3)'%3e%3cpath%20d='M%209,39%20L%2036,39%20L%2036,36%20L%209,36%20L%209,39%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2012,36%20L%2012,32%20L%2033,32%20L%2033,36%20L%2012,36%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2011,14%20L%2011,9%20L%2015,9%20L%2015,11%20L%2020,11%20L%2020,9%20L%2025,9%20L%2025,11%20L%2030,11%20L%2030,9%20L%2034,9%20L%2034,14'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2034,14%20L%2031,17%20L%2014,17%20L%2011,14'%20/%3e%3cpath%20d='M%2031,17%20L%2031,29.5%20L%2014,29.5%20L%2014,17'%20style='stroke-linecap:butt;%20stroke-linejoin:miter;'%20/%3e%3cpath%20d='M%2031,29.5%20L%2032.5,32%20L%2012.5,32%20L%2014,29.5'%20/%3e%3cpath%20d='M%2011,14%20L%2034,14'%20style='fill:none;%20stroke:%23000000;%20stroke-linejoin:miter;'%20/%3e%3c/g%3e%3c/svg%3e";
const wq = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='fill:%23ffffff;stroke:%23000000;stroke-width:1.5;stroke-linejoin:round'%3e%3cpath%20d='M%209,26%20C%2017.5,24.5%2030,24.5%2036,26%20L%2038.5,13.5%20L%2031,25%20L%2030.7,10.9%20L%2025.5,24.5%20L%2022.5,10%20L%2019.5,24.5%20L%2014.3,10.9%20L%2014,25%20L%206.5,13.5%20L%209,26%20z'/%3e%3cpath%20d='M%209,26%20C%209,28%2010.5,28%2011.5,30%20C%2012.5,31.5%2012.5,31%2012,33.5%20C%2010.5,34.5%2011,36%2011,36%20C%209.5,37.5%2011,38.5%2011,38.5%20C%2017.5,39.5%2027.5,39.5%2034,38.5%20C%2034,38.5%2035.5,37.5%2034,36%20C%2034,36%2034.5,34.5%2033,33.5%20C%2032.5,31%2032.5,31.5%2033.5,30%20C%2034.5,28%2036,28%2036,26%20C%2027.5,24.5%2017.5,24.5%209,26%20z'/%3e%3cpath%20d='M%2011.5,30%20C%2015,29%2030,29%2033.5,30'%20style='fill:none'/%3e%3cpath%20d='M%2012,33.5%20C%2018,32.5%2027,32.5%2033,33.5'%20style='fill:none'/%3e%3ccircle%20cx='6'%20cy='12'%20r='2'%20/%3e%3ccircle%20cx='14'%20cy='9'%20r='2'%20/%3e%3ccircle%20cx='22.5'%20cy='8'%20r='2'%20/%3e%3ccircle%20cx='31'%20cy='9'%20r='2'%20/%3e%3ccircle%20cx='39'%20cy='12'%20r='2'%20/%3e%3c/g%3e%3c/svg%3e";
const wk = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='45'%20height='45'%3e%3cg%20fill='none'%20fill-rule='evenodd'%20stroke='%23000'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.5'%3e%3cpath%20stroke-linejoin='miter'%20d='M22.5%2011.63V6M20%208h5'/%3e%3cpath%20fill='%23fff'%20stroke-linecap='butt'%20stroke-linejoin='miter'%20d='M22.5%2025s4.5-7.5%203-10.5c0%200-1-2.5-3-2.5s-3%202.5-3%202.5c-1.5%203%203%2010.5%203%2010.5'/%3e%3cpath%20fill='%23fff'%20d='M12.5%2037c5.5%203.5%2014.5%203.5%2020%200v-7s9-4.5%206-10.5c-4-6.5-13.5-3.5-16%204V27v-3.5c-2.5-7.5-12-10.5-16-4-3%206%206%2010.5%206%2010.5v7'/%3e%3cpath%20d='M12.5%2030c5.5-3%2014.5-3%2020%200m-20%203.5c5.5-3%2014.5-3%2020%200m-20%203.5c5.5-3%2014.5-3%2020%200'/%3e%3c/g%3e%3c/svg%3e";
const bp = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cpath%20d='m%2022.5,9%20c%20-2.21,0%20-4,1.79%20-4,4%200,0.89%200.29,1.71%200.78,2.38%20C%2017.33,16.5%2016,18.59%2016,21%20c%200,2.03%200.94,3.84%202.41,5.03%20C%2015.41,27.09%2011,31.58%2011,39.5%20H%2034%20C%2034,31.58%2029.59,27.09%2026.59,26.03%2028.06,24.84%2029,23.03%2029,21%2029,18.59%2027.67,16.5%2025.72,15.38%2026.21,14.71%2026.5,13.89%2026.5,13%20c%200,-2.21%20-1.79,-4%20-4,-4%20z'%20style='opacity:1;%20fill:%23000000;%20fill-opacity:1;%20fill-rule:nonzero;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;%20stroke-linejoin:miter;%20stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'/%3e%3c/svg%3e";
const bn = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='opacity:1;%20fill:none;%20fill-opacity:1;%20fill-rule:evenodd;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%20transform='translate(0,0.3)'%3e%3cpath%20d='M%2022,10%20C%2032.5,11%2038.5,18%2038,39%20L%2015,39%20C%2015,30%2025,32.5%2023,18'%20style='fill:%23000000;%20stroke:%23000000;'%20/%3e%3cpath%20d='M%2024,18%20C%2024.38,20.91%2018.45,25.37%2016,27%20C%2013,29%2013.18,31.34%2011,31%20C%209.958,30.06%2012.41,27.96%2011,28%20C%2010,28%2011.19,29.23%2010,30%20C%209,30%205.997,31%206,26%20C%206,24%2012,14%2012,14%20C%2012,14%2013.89,12.1%2014,10.5%20C%2013.27,9.506%2013.5,8.5%2013.5,7.5%20C%2014.5,6.5%2016.5,10%2016.5,10%20L%2018.5,10%20C%2018.5,10%2019.28,8.008%2021,7%20C%2022,7%2022,10%2022,10'%20style='fill:%23000000;%20stroke:%23000000;'%20/%3e%3cpath%20d='M%209.5%2025.5%20A%200.5%200.5%200%201%201%208.5,25.5%20A%200.5%200.5%200%201%201%209.5%2025.5%20z'%20style='fill:%23ffffff;%20stroke:%23ffffff;'%20/%3e%3cpath%20d='M%2015%2015.5%20A%200.5%201.5%200%201%201%2014,15.5%20A%200.5%201.5%200%201%201%2015%2015.5%20z'%20transform='matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)'%20style='fill:%23ffffff;%20stroke:%23ffffff;'%20/%3e%3cpath%20d='M%2024.55,10.4%20L%2024.1,11.85%20L%2024.6,12%20C%2027.75,13%2030.25,14.49%2032.5,18.75%20C%2034.75,23.01%2035.75,29.06%2035.25,39%20L%2035.2,39.5%20L%2037.45,39.5%20L%2037.5,39%20C%2038,28.94%2036.62,22.15%2034.25,17.66%20C%2031.88,13.17%2028.46,11.02%2025.06,10.5%20L%2024.55,10.4%20z%20'%20style='fill:%23ffffff;%20stroke:none;'%20/%3e%3c/g%3e%3c/svg%3e";
const bb = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='opacity:1;%20fill:none;%20fill-rule:evenodd;%20fill-opacity:1;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;%20stroke-linejoin:round;%20stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%20transform='translate(0,0.6)'%3e%3cg%20style='fill:%23000000;%20stroke:%23000000;%20stroke-linecap:butt;'%3e%3cpath%20d='M%209,36%20C%2012.39,35.03%2019.11,36.43%2022.5,34%20C%2025.89,36.43%2032.61,35.03%2036,36%20C%2036,36%2037.65,36.54%2039,38%20C%2038.32,38.97%2037.35,38.99%2036,38.5%20C%2032.61,37.53%2025.89,38.96%2022.5,37.5%20C%2019.11,38.96%2012.39,37.53%209,38.5%20C%207.65,38.99%206.68,38.97%206,38%20C%207.35,36.54%209,36%209,36%20z'/%3e%3cpath%20d='M%2015,32%20C%2017.5,34.5%2027.5,34.5%2030,32%20C%2030.5,30.5%2030,30%2030,30%20C%2030,27.5%2027.5,26%2027.5,26%20C%2033,24.5%2033.5,14.5%2022.5,10.5%20C%2011.5,14.5%2012,24.5%2017.5,26%20C%2017.5,26%2015,27.5%2015,30%20C%2015,30%2014.5,30.5%2015,32%20z'/%3e%3cpath%20d='M%2025%208%20A%202.5%202.5%200%201%201%2020,8%20A%202.5%202.5%200%201%201%2025%208%20z'/%3e%3c/g%3e%3cpath%20d='M%2017.5,26%20L%2027.5,26%20M%2015,30%20L%2030,30%20M%2022.5,15.5%20L%2022.5,20.5%20M%2020,18%20L%2025,18'%20style='fill:none;%20stroke:%23ffffff;%20stroke-linejoin:miter;'/%3e%3c/g%3e%3c/svg%3e";
const br = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='opacity:1;%20fill:%23000000;%20fill-opacity:1;%20fill-rule:evenodd;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%20transform='translate(0,0.3)'%3e%3cpath%20d='M%209,39%20L%2036,39%20L%2036,36%20L%209,36%20L%209,39%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2012.5,32%20L%2014,29.5%20L%2031,29.5%20L%2032.5,32%20L%2012.5,32%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2012,36%20L%2012,32%20L%2033,32%20L%2033,36%20L%2012,36%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2014,29.5%20L%2014,16.5%20L%2031,16.5%20L%2031,29.5%20L%2014,29.5%20z%20'%20style='stroke-linecap:butt;stroke-linejoin:miter;'%20/%3e%3cpath%20d='M%2014,16.5%20L%2011,14%20L%2034,14%20L%2031,16.5%20L%2014,16.5%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2011,14%20L%2011,9%20L%2015,9%20L%2015,11%20L%2020,11%20L%2020,9%20L%2025,9%20L%2025,11%20L%2030,11%20L%2030,9%20L%2034,9%20L%2034,14%20L%2011,14%20z%20'%20style='stroke-linecap:butt;'%20/%3e%3cpath%20d='M%2012,35.5%20L%2033,35.5%20L%2033,35.5'%20style='fill:none;%20stroke:%23ffffff;%20stroke-width:1;%20stroke-linejoin:miter;'%20/%3e%3cpath%20d='M%2013,31.5%20L%2032,31.5'%20style='fill:none;%20stroke:%23ffffff;%20stroke-width:1;%20stroke-linejoin:miter;'%20/%3e%3cpath%20d='M%2014,29.5%20L%2031,29.5'%20style='fill:none;%20stroke:%23ffffff;%20stroke-width:1;%20stroke-linejoin:miter;'%20/%3e%3cpath%20d='M%2014,16.5%20L%2031,16.5'%20style='fill:none;%20stroke:%23ffffff;%20stroke-width:1;%20stroke-linejoin:miter;'%20/%3e%3cpath%20d='M%2011,14%20L%2034,14'%20style='fill:none;%20stroke:%23ffffff;%20stroke-width:1;%20stroke-linejoin:miter;'%20/%3e%3c/g%3e%3c/svg%3e";
const bq = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='fill:%23000000;stroke:%23000000;stroke-width:1.5;stroke-linejoin:round'%3e%3cpath%20d='M%209,26%20C%2017.5,24.5%2030,24.5%2036,26%20L%2038.5,13.5%20L%2031,25%20L%2030.7,10.9%20L%2025.5,24.5%20L%2022.5,10%20L%2019.5,24.5%20L%2014.3,10.9%20L%2014,25%20L%206.5,13.5%20L%209,26%20z'/%3e%3cpath%20d='m%209,26%20c%200,2%201.5,2%202.5,4%201,1.5%201,1%200.5,3.5%20-1.5,1%20-1,2.5%20-1,2.5%20-1.5,1.5%200,2.5%200,2.5%206.5,1%2016.5,1%2023,0%200,0%201.5,-1%200,-2.5%200,0%200.5,-1.5%20-1,-2.5%20-0.5,-2.5%20-0.5,-2%200.5,-3.5%201,-2%202.5,-2%202.5,-4%20-8.5,-1.5%20-18.5,-1.5%20-27,0%20z'/%3e%3cpath%20d='M%2011.5,30%20C%2015,29%2030,29%2033.5,30'%20style='fill:none'/%3e%3cpath%20d='m%2012,33.5%20c%206,-1%2015,-1%2021,0'%20style='fill:none'/%3e%3ccircle%20cx='6'%20cy='12'%20r='2'/%3e%3ccircle%20cx='14'%20cy='9'%20r='2'/%3e%3ccircle%20cx='22.5'%20cy='8'%20r='2'/%3e%3ccircle%20cx='31'%20cy='9'%20r='2'/%3e%3ccircle%20cx='39'%20cy='12'%20r='2'/%3e%3cpath%20d='M%2011,38.5%20A%2035,35%201%200%200%2034,38.5'%20style='fill:none'/%3e%3cg%20style='fill:none;stroke:%23ffffff'%3e%3cpath%20d='M%2011,29%20A%2035,35%201%200%201%2034,29'/%3e%3cpath%20d='M%2012.5,31.5%20L%2032.5,31.5'/%3e%3cpath%20d='M%2011.5,34.5%20A%2035,35%201%200%200%2033.5,34.5'/%3e%3cpath%20d='M%2010.5,37.5%20A%2035,35%201%200%200%2034.5,37.5'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e";
const bk = "data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20width='45'%20height='45'%3e%3cg%20style='fill:none;%20fill-opacity:1;%20fill-rule:evenodd;%20stroke:%23000000;%20stroke-width:1.5;%20stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;%20stroke-dasharray:none;%20stroke-opacity:1;'%3e%3cpath%20d='M%2022.5,11.63%20L%2022.5,6'%20style='fill:none;%20stroke:%23000000;%20stroke-linejoin:miter;'%20id='path6570'/%3e%3cpath%20d='M%2022.5,25%20C%2022.5,25%2027,17.5%2025.5,14.5%20C%2025.5,14.5%2024.5,12%2022.5,12%20C%2020.5,12%2019.5,14.5%2019.5,14.5%20C%2018,17.5%2022.5,25%2022.5,25'%20style='fill:%23000000;fill-opacity:1;%20stroke-linecap:butt;%20stroke-linejoin:miter;'/%3e%3cpath%20d='M%2012.5,37%20C%2018,40.5%2027,40.5%2032.5,37%20L%2032.5,30%20C%2032.5,30%2041.5,25.5%2038.5,19.5%20C%2034.5,13%2025,16%2022.5,23.5%20L%2022.5,27%20L%2022.5,23.5%20C%2020,16%2010.5,13%206.5,19.5%20C%203.5,25.5%2012.5,30%2012.5,30%20L%2012.5,37'%20style='fill:%23000000;%20stroke:%23000000;'/%3e%3cpath%20d='M%2020,8%20L%2025,8'%20style='fill:none;%20stroke:%23000000;%20stroke-linejoin:miter;'/%3e%3cpath%20d='M%2032,29.5%20C%2032,29.5%2040.5,25.5%2038.03,19.85%20C%2034.15,14%2025,18%2022.5,24.5%20L%2022.5,26.6%20L%2022.5,24.5%20C%2020,18%2010.85,14%206.97,19.85%20C%204.5,25.5%2013,29.5%2013,29.5'%20style='fill:none;%20stroke:%23ffffff;'/%3e%3cpath%20d='M%2012.5,30%20C%2018,27%2027,27%2032.5,30%20M%2012.5,33.5%20C%2018,30.5%2027,30.5%2032.5,33.5%20M%2012.5,37%20C%2018,34%2027,34%2032.5,37'%20style='fill:none;%20stroke:%23ffffff;'/%3e%3c/g%3e%3c/svg%3e";
const PIECE_SVGS = {
  wp,
  wn,
  wb,
  wr,
  wq,
  wk,
  bp,
  bn,
  bb,
  br,
  bq,
  bk
};
const createEmptyPieceRecord = () => {
  const record = {};
  DEFAULT_PIECES.forEach((piece) => {
    record[piece] = "";
  });
  return record;
};
const PieceContext = createContext({
  currentTheme: "default",
  themes: {},
  loadTheme: async () => {
  },
  getPieceSvg: () => null,
  setCustomPiece: () => {
  },
  resetTheme: () => {
  },
  preloadTheme: async () => {
  },
  getThemeNames: () => [],
  isThemeLoaded: () => false
});
const usePieces = () => {
  const context = useContext(PieceContext);
  if (!context) {
    throw new Error("usePieces must be used within a PieceProvider");
  }
  return context;
};
function PieceProvider({
  children,
  defaultTheme = "default",
  customPieces = createEmptyPieceRecord(),
  preloadThemes = false
}) {
  const [themes, setThemes] = useState({
    default: {
      name: "default",
      pieces: PIECE_SVGS
    }
  });
  const [currentTheme, setCurrentTheme] = useState(defaultTheme);
  const [loadingThemes, setLoadingThemes] = useState(/* @__PURE__ */ new Set());
  const [loadedThemes, setLoadedThemes] = useState(/* @__PURE__ */ new Set(["default"]));
  const validatePieceSymbol = (piece) => {
    return Object.keys(PIECE_SVGS).includes(piece);
  };
  const loadTheme = async (name) => {
    if (themes[name] || loadingThemes.has(name)) return;
    if (name === "default") return;
    try {
      setLoadingThemes((prev) => /* @__PURE__ */ new Set([...prev, name]));
      let themePieces = createEmptyPieceRecord();
      if (name === "unicode") {
        themePieces = UNICODE_PIECES;
      } else {
        throw new Error(`Theme '${name}' not found`);
      }
      const theme = {
        name,
        pieces: themePieces
      };
      setThemes((prev) => ({
        ...prev,
        [name]: theme
      }));
      setLoadedThemes((prev) => /* @__PURE__ */ new Set([...prev, name]));
      setCurrentTheme(name);
    } catch (error) {
      console.error(`Failed to load theme: ${name}`, error);
      throw error;
    } finally {
      setLoadingThemes((prev) => {
        const next = new Set(prev);
        next.delete(name);
        return next;
      });
    }
  };
  const setCustomPiece = useCallback((piece, url) => {
    if (!validatePieceSymbol(piece)) {
      throw new Error(`Invalid piece symbol: ${piece}`);
    }
    setThemes((prev) => ({
      ...prev,
      [currentTheme]: {
        ...prev[currentTheme],
        pieces: {
          ...prev[currentTheme].pieces,
          [piece]: url
        }
      }
    }));
  }, [currentTheme]);
  const resetTheme = useCallback(() => {
    if (currentTheme === "default") {
      setThemes((prev) => ({
        ...prev,
        default: {
          name: "default",
          pieces: PIECE_SVGS
        }
      }));
    }
  }, [currentTheme]);
  const preloadTheme = async (name) => {
    if (loadedThemes.has(name)) return;
    await loadTheme(name);
  };
  const getPieceSvg = useCallback((piece) => {
    if (!validatePieceSymbol(piece)) {
      console.error(`Invalid piece symbol: ${piece}`);
      return null;
    }
    if (currentTheme === "default") {
      return PIECE_SVGS[piece] || null;
    }
    const theme = themes[currentTheme];
    if (!theme) {
      return PIECE_SVGS[piece] || null;
    }
    return theme.pieces[piece] || PIECE_SVGS[piece] || null;
  }, [themes, currentTheme]);
  const getThemeNames = useCallback(() => {
    return Object.keys(themes);
  }, [themes]);
  const isThemeLoaded = useCallback((name) => {
    return loadedThemes.has(name);
  }, [loadedThemes]);
  useEffect(() => {
    const init = async () => {
      try {
        await loadTheme("default");
        Object.entries(customPieces).forEach(([piece, url]) => {
          setCustomPiece(piece, url);
        });
        if (defaultTheme !== "default") {
          await loadTheme(defaultTheme);
        }
        if (preloadThemes) {
          await Promise.all([
            loadTheme("unicode")
            // Add more theme preloading here
          ]);
        }
      } catch (error) {
        console.error("Error initializing PieceProvider:", error);
      }
    };
    init();
  }, [defaultTheme, customPieces, preloadThemes, setCustomPiece]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(PieceContext.Provider, { value: {
    currentTheme,
    themes,
    loadTheme,
    getPieceSvg,
    setCustomPiece,
    resetTheme,
    preloadTheme,
    getThemeNames,
    isThemeLoaded
  }, children });
}
const Piece = memo(({
  piece,
  square,
  isDragging,
  _theme = "default"
}) => {
  var _a, _b;
  const { getPieceSvg } = usePieces();
  const pieceContent = getPieceSvg(piece);
  const pieceRef = useRef(null);
  const [dragPosition, setDragPosition] = useState(null);
  const initialPosition = useRef(null);
  const pieceName = PIECE_NAMES[piece[1]];
  const pieceColor = piece[0] === "w" ? "white" : "black";
  const ariaLabel = `${pieceColor} ${pieceName} on ${square}`;
  const updatePiecePosition = useCallback((e) => {
    if (!isDragging || !initialPosition.current) return;
    const { x: initialX, y: initialY, rect } = initialPosition.current;
    const offsetX = e.pageX - initialX;
    const offsetY = e.pageY - initialY;
    setDragPosition({
      x: rect.left + window.scrollX + offsetX,
      y: rect.top + window.scrollY + offsetY
    });
  }, [isDragging]);
  useEffect(() => {
    if (isDragging && pieceRef.current) {
      const rect = pieceRef.current.getBoundingClientRect();
      initialPosition.current = {
        x: window.scrollX + rect.left,
        y: window.scrollY + rect.top,
        rect
      };
      setDragPosition({
        x: window.scrollX + rect.left,
        y: window.scrollY + rect.top
      });
      const updateInitialMousePos = (e) => {
        if (initialPosition.current) {
          initialPosition.current.x = e.pageX;
          initialPosition.current.y = e.pageY;
          window.removeEventListener("mousemove", updateInitialMousePos);
        }
      };
      window.addEventListener("mousemove", updateInitialMousePos, { once: true });
      window.addEventListener("mousemove", updatePiecePosition);
    } else {
      setDragPosition(null);
    }
    return () => {
      window.removeEventListener("mousemove", updatePiecePosition);
      initialPosition.current = null;
    };
  }, [isDragging, updatePiecePosition]);
  const renderPiece = useCallback(() => {
    if (!pieceContent) return null;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "img",
      {
        src: pieceContent,
        alt: `${pieceColor} ${pieceName}`,
        className: "piece-svg no-drag",
        style: {
          position: "absolute",
          inset: 0,
          width: "100%",
          height: "100%",
          pointerEvents: "none",
          opacity: isDragging ? 0.8 : 1,
          filter: piece.startsWith("b") ? "brightness(0.2)" : "none",
          userSelect: "none"
        }
      }
    );
  }, [pieceContent, isDragging, piece, pieceColor, pieceName]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        ref: pieceRef,
        className: `piece ${isDragging ? "dragging" : ""}`,
        "data-piece": piece,
        "data-square": square,
        role: "piece",
        "aria-label": ariaLabel,
        style: {
          position: "absolute",
          inset: 0,
          width: "100%",
          height: "100%",
          cursor: isDragging ? "grabbing" : "grab",
          transition: isDragging ? "none" : "transform 0.2s ease",
          pointerEvents: isDragging ? "none" : "auto",
          touchAction: "none",
          willChange: "transform",
          transformOrigin: "center",
          zIndex: isDragging ? 9999 : 1,
          opacity: isDragging ? 0 : 1,
          backgroundColor: "transparent"
        },
        children: [
          !isDragging && renderPiece(),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "visually-hidden", children: ariaLabel })
        ]
      }
    ),
    isDragging && dragPosition && createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "dragged-piece",
          style: {
            position: "fixed",
            left: 0,
            top: 0,
            width: (_a = initialPosition.current) == null ? void 0 : _a.rect.width,
            height: (_b = initialPosition.current) == null ? void 0 : _b.rect.height,
            transform: `translate(${dragPosition.x}px, ${dragPosition.y}px)`,
            zIndex: 9999,
            pointerEvents: "none",
            willChange: "transform",
            backgroundColor: "transparent"
          },
          children: renderPiece()
        }
      ),
      document.body
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("style", { children: `
        .piece-svg {
          user-select: none;
          -webkit-user-drag: none;
        }
        
        .chess-board {
          position: relative;
        }

        .chess-board .square {
          position: relative;
          z-index: 1;
        }

        .piece {
          position: absolute;
          z-index: 2;
          transform-origin: center;
          background-color: transparent !important;
        }

        .piece.dragging {
          z-index: 9999;
          pointer-events: none;
        }

        .dragged-piece {
          pointer-events: none;
          transform-origin: center;
          background-color: transparent !important;
        }

        .visually-hidden {
          position: absolute;
          width: 1px;
          height: 1px;
          padding: 0;
          margin: -1px;
          overflow: hidden;
          clip: rect(0, 0, 0, 0);
          white-space: nowrap;
          border: 0;
        }

        .no-drag {
          -webkit-user-drag: none;
          -khtml-user-drag: none;
          -moz-user-drag: none;
          -o-user-drag: none;
          user-drag: none;
        }
      ` })
  ] });
});
Piece.displayName = "Piece";
const ChessContext = createContext(null);
const useChess = () => {
  const context = useContext(ChessContext);
  if (!context) {
    throw new Error("useChess must be used within a ChessProvider");
  }
  return context;
};
function ChessProvider({
  children,
  initialPosition = "start",
  enableUndo = true,
  onPositionChange,
  onGameEnd,
  persistState = false,
  defaultTheme = "default",
  customPieces = createEmptyPieceRecord(),
  preloadThemes = false
}) {
  const [game] = useState(() => new Chess(initialPosition === "start" ? void 0 : initialPosition));
  const [position, setPosition] = useState(game.fen());
  const [history, setHistory] = useState([]);
  const [positionHistory, setPositionHistory] = useState(/* @__PURE__ */ new Map());
  const [moveNumber, setMoveNumber] = useState(1);
  const redoStack = useRef([]);
  const [themes, setThemes] = useState({});
  const [currentTheme, setCurrentTheme] = useState(defaultTheme);
  const [loadingThemes, setLoadingThemes] = useState(/* @__PURE__ */ new Set());
  const [loadedThemes, setLoadedThemes] = useState(/* @__PURE__ */ new Set());
  const updateGameState = useCallback(() => {
    try {
      const newPosition = game.fen();
      setPosition(newPosition);
      setHistory(game.history({ verbose: true }).map((move) => move.san));
      setMoveNumber(Math.floor(game.moveNumber() / 2) + 1);
      const positionKey = newPosition.split(" ").slice(0, 4).join(" ");
      setPositionHistory((prev) => {
        const newMap = new Map(prev);
        newMap.set(positionKey, (newMap.get(positionKey) || 0) + 1);
        return newMap;
      });
      onPositionChange == null ? void 0 : onPositionChange(newPosition);
      if (game.isGameOver()) {
        const result = {
          winner: game.isCheckmate() ? game.turn() === "w" ? "black" : "white" : game.isDraw() ? "draw" : null,
          reason: game.isCheckmate() ? "checkmate" : game.isStalemate() ? "stalemate" : game.isInsufficientMaterial() ? "insufficient-material" : game.isThreefoldRepetition() ? "threefold-repetition" : game.isDraw() ? "fifty-move-rule" : null,
          score: game.isCheckmate() ? game.turn() === "w" ? "0-1" : "1-0" : "1/2-1/2"
        };
        onGameEnd == null ? void 0 : onGameEnd(result);
      }
      if (persistState) {
        localStorage.setItem("chess-game-state", JSON.stringify({
          fen: newPosition,
          history: game.history({ verbose: true }),
          moveNumber
        }));
      }
    } catch (error) {
      console.error("Error updating game state:", error);
    }
  }, [game, onPositionChange, onGameEnd, persistState, moveNumber]);
  const isThreefoldRepetition = useCallback(() => {
    const currentPosition = game.fen().split(" ").slice(0, 4).join(" ");
    return (positionHistory.get(currentPosition) || 0) >= 3;
  }, [game, positionHistory]);
  const isFiftyMoveRule = useCallback(() => {
    const [, , , , halfMoves] = game.fen().split(" ");
    return parseInt(halfMoves) >= 100;
  }, [game]);
  const isInsufficientMaterial = useCallback(() => {
    const pieces = game.board().flat().filter((piece) => piece !== null);
    if (pieces.length <= 3) {
      if (pieces.length === 2) return true;
      if (pieces.length === 3) {
        const nonKingPiece = pieces.find((piece) => (piece == null ? void 0 : piece.type) !== "k");
        return (nonKingPiece == null ? void 0 : nonKingPiece.type) === "b" || (nonKingPiece == null ? void 0 : nonKingPiece.type) === "n";
      }
    }
    return false;
  }, [game]);
  const getPossibleMoves = useCallback((square) => {
    try {
      const moves = game.moves({
        square,
        verbose: false
      });
      return moves.map((move) => {
        if (typeof move === "string") {
          if (move === "O-O" || move === "O-O-O") {
            const rank = game.turn() === "w" ? "1" : "8";
            return move === "O-O" ? `g${rank}` : `c${rank}`;
          }
          const match = move.match(/[a-h][1-8]/);
          return match ? match[0] : "";
        }
        return "";
      }).filter(Boolean);
    } catch (e) {
      console.error("Error getting possible moves:", e);
      return [];
    }
  }, [game]);
  const makeMove = useCallback((from, to, promotion) => {
    try {
      const result = game.move({ from, to, promotion });
      if (result) {
        updateGameState();
        return true;
      }
      return false;
    } catch (error) {
      console.error("Error making move:", error);
      return false;
    }
  }, [game, updateGameState]);
  const undo = useCallback(() => {
    if (!enableUndo) return false;
    const undoneMove = game.undo();
    if (undoneMove) {
      redoStack.current.push(undoneMove);
      updateGameState();
      return true;
    }
    return false;
  }, [game, updateGameState, enableUndo]);
  const redo = useCallback(() => {
    if (!enableUndo || redoStack.current.length === 0) return false;
    const moveToRedo = redoStack.current.pop();
    if (moveToRedo) {
      const success = game.move(moveToRedo);
      if (success) {
        updateGameState();
        return true;
      }
    }
    return false;
  }, [game, updateGameState, enableUndo]);
  const reset = useCallback(() => {
    game.reset();
    setPositionHistory(/* @__PURE__ */ new Map());
    updateGameState();
  }, [game, updateGameState]);
  const exportPGN = useCallback(() => {
    return game.pgn();
  }, [game]);
  const validateFen = useCallback((fen) => {
    try {
      const chess = new Chess();
      chess.load(fen);
      return true;
    } catch {
      return false;
    }
  }, []);
  const importPGN = useCallback((pgn) => {
    try {
      game.loadPgn(pgn);
      updateGameState();
      redoStack.current = [];
      return true;
    } catch (e) {
      console.error("Invalid PGN:", e);
      return false;
    }
  }, [game, updateGameState]);
  useEffect(() => {
    if (persistState) {
      const savedState = localStorage.getItem("chess-game-state");
      if (savedState) {
        try {
          const { fen, history: history2 } = JSON.parse(savedState);
          game.load(fen);
          updateGameState();
        } catch (error) {
          console.error("Error loading persisted state:", error);
        }
      }
    }
  }, [persistState, game, updateGameState]);
  const validatePieceSymbol = (piece) => {
    return Object.keys(PIECE_SVGS).includes(piece);
  };
  const loadTheme = async (name) => {
    if (themes[name] || loadingThemes.has(name)) return;
    try {
      setLoadingThemes((prev) => /* @__PURE__ */ new Set([...prev, name]));
      let themePieces = createEmptyPieceRecord();
      if (name === "default") {
        themePieces = PIECE_SVGS;
      } else if (name === "unicode") {
        themePieces = UNICODE_PIECES;
      } else {
        throw new Error(`Theme '${name}' not found`);
      }
      const theme = {
        name,
        pieces: themePieces
      };
      setThemes((prev) => ({
        ...prev,
        [name]: theme
      }));
      setLoadedThemes((prev) => /* @__PURE__ */ new Set([...prev, name]));
      setCurrentTheme(name);
    } catch (error) {
      console.error(`Failed to load theme: ${name}`, error);
      throw error;
    } finally {
      setLoadingThemes((prev) => {
        const next = new Set(prev);
        next.delete(name);
        return next;
      });
    }
  };
  const setCustomPiece = useCallback((piece, url) => {
    if (!validatePieceSymbol(piece)) {
      throw new Error(`Invalid piece symbol: ${piece}`);
    }
    setThemes((prev) => ({
      ...prev,
      [currentTheme]: {
        ...prev[currentTheme],
        pieces: {
          ...prev[currentTheme].pieces,
          [piece]: url
        }
      }
    }));
  }, [currentTheme]);
  const resetTheme = useCallback(() => {
    if (currentTheme === "default") {
      setThemes((prev) => ({
        ...prev,
        default: {
          name: "default",
          pieces: PIECE_SVGS
        }
      }));
    }
  }, [currentTheme]);
  const preloadTheme = async (name) => {
    if (loadedThemes.has(name)) return;
    await loadTheme(name);
  };
  const getPieceSvg = useCallback((piece) => {
    if (!validatePieceSymbol(piece)) {
      console.error(`Invalid piece symbol: ${piece}`);
      return null;
    }
    const theme = themes[currentTheme];
    if (!theme) {
      console.error(`Theme not loaded: ${currentTheme}`);
      return PIECE_SVGS[piece] || null;
    }
    return theme.pieces[piece] || PIECE_SVGS[piece] || null;
  }, [themes, currentTheme]);
  const getThemeNames = useCallback(() => {
    return Object.keys(themes);
  }, [themes]);
  const isThemeLoaded = useCallback((name) => {
    return loadedThemes.has(name);
  }, [loadedThemes]);
  useEffect(() => {
    const init = async () => {
      try {
        await loadTheme("default");
        Object.entries(customPieces).forEach(([piece, url]) => {
          setCustomPiece(piece, url);
        });
        if (defaultTheme !== "default") {
          await loadTheme(defaultTheme);
        }
        if (preloadThemes) {
          await Promise.all([
            loadTheme("unicode")
          ]);
        }
      } catch (error) {
        console.error("Error initializing themes:", error);
      }
    };
    init();
  }, [defaultTheme, customPieces, preloadThemes, setCustomPiece]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(ChessContext.Provider, { value: {
    // Chess context values
    game,
    position,
    isCheck: game.isCheck(),
    isCheckmate: game.isCheckmate(),
    isStalemate: game.isStalemate(),
    isDraw: game.isDraw(),
    isThreefoldRepetition: isThreefoldRepetition(),
    isFiftyMoveRule: isFiftyMoveRule(),
    isInsufficientMaterial: isInsufficientMaterial(),
    turn: game.turn(),
    history,
    moveNumber,
    pgn: game.pgn(),
    makeMove,
    undo,
    redo,
    reset,
    getPossibleMoves,
    exportPGN,
    importPGN,
    getGameState: () => ({
      isCheck: game.isCheck(),
      isCheckmate: game.isCheckmate(),
      isStalemate: game.isStalemate(),
      isDraw: game.isDraw(),
      turn: game.turn() === "w" ? "white" : "black",
      moveNumber,
      halfMoves: game.moveNumber(),
      fen: game.fen(),
      pgn: game.pgn()
    }),
    validateFen,
    // Piece context values
    currentTheme,
    themes,
    loadTheme,
    getPieceSvg,
    setCustomPiece,
    resetTheme,
    preloadTheme,
    getThemeNames,
    isThemeLoaded
  }, children });
}
const getNextSquare = (square, direction) => {
  const file = square.charCodeAt(0) - 97;
  const rank = 8 - parseInt(square[1]);
  let nextFile = file;
  let nextRank = rank;
  switch (direction) {
    case "up":
      nextRank--;
      break;
    case "down":
      nextRank++;
      break;
    case "left":
      nextFile--;
      break;
    case "right":
      nextFile++;
      break;
  }
  if (nextFile < 0 || nextFile > 7 || nextRank < 0 || nextRank > 7) return null;
  return `${String.fromCharCode(97 + nextFile)}${8 - nextRank}`;
};
function ChessBoard({
  onPieceDrop,
  orientation = "white",
  customSquareStyles = {}
}) {
  const {
    position,
    makeMove,
    getPossibleMoves,
    turn
  } = useChess();
  const [dragState, setDragState] = useState({
    piece: null,
    from: null,
    isDragging: false
  });
  const [selectedSquare, setSelectedSquare] = useState(null);
  const [highlightedSquares, setHighlightedSquares] = useState([]);
  const boardRef = useRef(null);
  const dragHandlersRef = useRef({
    handleMove: null,
    handleUp: null
  });
  const currentPosition = useMemo(() => {
    console.log("Parsing position:", position);
    const [fen] = position.split(" ");
    const rows = fen.split("/");
    const positionMap = {};
    rows.forEach((row, rowIndex) => {
      let colIndex = 0;
      for (let i = 0; i < row.length; i++) {
        const char = row[i];
        if (/\d/.test(char)) {
          colIndex += parseInt(char);
        } else {
          const square = `${String.fromCharCode(97 + colIndex)}${8 - rowIndex}`;
          const color = char === char.toUpperCase() ? "w" : "b";
          const piece = char.toLowerCase();
          positionMap[square] = `${color}${piece}`;
          colIndex++;
        }
      }
    });
    console.log("Parsed position map:", positionMap);
    return positionMap;
  }, [position]);
  const getSquareFromEvent = useCallback((e) => {
    if (!boardRef.current) return null;
    const rect = boardRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    if (x < 0 || x > rect.width || y < 0 || y > rect.height) return null;
    const file = Math.floor(x / rect.width * 8);
    const rank = Math.floor(y / rect.height * 8);
    const square = `${String.fromCharCode(97 + (orientation === "white" ? file : 7 - file))}${8 - rank}`;
    return square;
  }, [orientation]);
  const cleanupDragEvents = useCallback(() => {
    if (dragHandlersRef.current.handleMove) {
      window.removeEventListener("mousemove", dragHandlersRef.current.handleMove);
    }
    if (dragHandlersRef.current.handleUp) {
      window.removeEventListener("mouseup", dragHandlersRef.current.handleUp);
    }
    dragHandlersRef.current.handleMove = null;
    dragHandlersRef.current.handleUp = null;
  }, []);
  useEffect(() => {
    return () => cleanupDragEvents();
  }, [cleanupDragEvents]);
  const handleDragStart = useCallback((e, square) => {
    const piece = currentPosition[square];
    if (!piece || turn === "w" && piece.startsWith("b") || turn === "b" && piece.startsWith("w")) {
      return;
    }
    e.preventDefault();
    setDragState({
      piece,
      from: square,
      isDragging: true
    });
    const moves = getPossibleMoves(square);
    setHighlightedSquares(moves);
    const handleMove = (e2) => {
      e2.preventDefault();
      if (!boardRef.current) return;
      document.querySelectorAll(".drop-target, .dragging-over").forEach((el) => {
        el.classList.remove("drop-target", "dragging-over");
      });
      const square2 = getSquareFromEvent(e2);
      if (square2 && moves.includes(square2)) {
        const element = document.querySelector(`[data-square="${square2}"]`);
        if (element) {
          element.classList.add("drop-target", "dragging-over");
        }
      }
    };
    const handleUp = (e2) => {
      e2.preventDefault();
      document.querySelectorAll(".drop-target").forEach((el) => {
        el.classList.remove("drop-target");
      });
      const toSquare = getSquareFromEvent(e2);
      if (toSquare && toSquare !== square && moves.includes(toSquare) && onPieceDrop) {
        onPieceDrop(square, toSquare, piece);
      }
      setDragState({ piece: null, from: null, isDragging: false });
      setHighlightedSquares([]);
      cleanupDragEvents();
    };
    dragHandlersRef.current.handleMove = handleMove;
    dragHandlersRef.current.handleUp = handleUp;
    window.addEventListener("mousemove", handleMove);
    window.addEventListener("mouseup", handleUp);
  }, [currentPosition, getPossibleMoves, turn, getSquareFromEvent, onPieceDrop, cleanupDragEvents]);
  const handleSquareSelect = useCallback((e, square) => {
    e.stopPropagation();
    if (dragState.isDragging) return;
    if (selectedSquare) {
      if (square === selectedSquare) {
        setSelectedSquare(null);
        setHighlightedSquares([]);
        return;
      }
      const possibleMoves = getPossibleMoves(selectedSquare);
      if (possibleMoves.includes(square)) {
        const success = makeMove(selectedSquare, square);
        if (success && onPieceDrop) {
          onPieceDrop(selectedSquare, square, currentPosition[selectedSquare]);
        }
      }
      setSelectedSquare(null);
      setHighlightedSquares([]);
    } else if (currentPosition[square]) {
      const piece = currentPosition[square];
      if (turn === "w" && piece.startsWith("w") || turn === "b" && piece.startsWith("b")) {
        setSelectedSquare(square);
        setHighlightedSquares(getPossibleMoves(square));
      }
    } else {
      setSelectedSquare(null);
      setHighlightedSquares([]);
    }
  }, [selectedSquare, makeMove, onPieceDrop, currentPosition, getPossibleMoves, turn, dragState.isDragging]);
  const handleBoardClick = useCallback((e) => {
    if (e.target === e.currentTarget) {
      setSelectedSquare(null);
    }
  }, []);
  const handleKeyDown = useCallback((e, square) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      const syntheticEvent = {
        stopPropagation: () => {
        },
        target: e.target,
        currentTarget: e.currentTarget
      };
      handleSquareSelect(syntheticEvent, square);
    } else if (e.key === "Escape") {
      setSelectedSquare(null);
    } else {
      const direction = {
        ArrowUp: "up",
        ArrowDown: "down",
        ArrowLeft: "left",
        ArrowRight: "right"
      }[e.key];
      if (direction) {
        e.preventDefault();
        const nextSquare = getNextSquare(square, direction);
        if (nextSquare) {
          const nextElement = document.querySelector(`[data-square="${nextSquare}"]`);
          if (nextElement instanceof HTMLElement) {
            nextElement.focus();
          }
        }
      }
    }
  }, [handleSquareSelect]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      ref: boardRef,
      className: "chess-board",
      role: "grid",
      "aria-label": "Chess board",
      onClick: handleBoardClick,
      children: [
        Array.from({ length: 64 }, (_, i) => {
          const row = Math.floor(i / 8);
          const col = orientation === "white" ? i % 8 : 7 - i % 8;
          const isLight = (row + col) % 2 === 0;
          const square = `${String.fromCharCode(97 + col)}${8 - row}`;
          const piece = currentPosition[square];
          const isHighlighted = highlightedSquares.includes(square);
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `square ${isLight ? "light" : "dark"} ${selectedSquare === square ? "selected" : ""} ${isHighlighted ? "highlighted" : ""}`,
              "data-square": square,
              style: customSquareStyles[square],
              onMouseDown: (e) => piece && handleDragStart(e, square),
              onClick: (e) => handleSquareSelect(e, square),
              role: "gridcell",
              "aria-label": `${isLight ? "light" : "dark"} square ${square}${piece ? ` with ${piece[0] === "w" ? "white" : "black"} piece` : ""}`,
              tabIndex: 0,
              onKeyDown: (e) => handleKeyDown(e, square),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "square-content", children: piece && /* @__PURE__ */ jsxRuntimeExports.jsx(
                Piece,
                {
                  piece,
                  square,
                  isDragging: dragState.from === square
                }
              ) })
            },
            square
          );
        }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("style", { children: `
        .chess-board {
          display: grid;
          grid-template-columns: repeat(8, 1fr);
          aspect-ratio: 1;
          background: #312E2B;
          position: relative;
          user-select: none;
          width: 100%;
          border: 4px solid #312E2B;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
          touch-action: none;
        }

        .square {
          position: relative;
          width: 100%;
          padding-top: 100%;
          background-color: #EEEED2;
          transition: background-color 0.2s ease;
          cursor: pointer;
        }

        .square.dark {
          background-color: #769656;
        }

        .square-content {
          position: absolute;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: inherit;
        }

        .square.selected {
          box-shadow: inset 0 0 0 3px rgba(255, 255, 0, 0.5);
        }

        .square.drop-target {
          box-shadow: inset 0 0 0 3px rgba(0, 255, 0, 0.5);
        }

        .square.drop-target.selected {
          box-shadow: inset 0 0 0 3px rgba(255, 255, 0, 0.5),
                     inset 0 0 0 6px rgba(0, 255, 0, 0.5);
        }

        .square:focus {
          outline: none;
          box-shadow: inset 0 0 0 3px rgba(0, 128, 255, 0.5);
        }

        .square.selected:focus {
          box-shadow: inset 0 0 0 3px rgba(255, 255, 0, 0.5),
                      0 0 0 3px rgba(0, 128, 255, 0.5);
        }

        .square::before {
          content: attr(data-square);
          position: absolute;
          bottom: 2px;
          left: 2px;
          font-size: 8px;
          opacity: 0.5;
          color: ${orientation === "white" ? "#769656" : "#EEEED2"};
          pointer-events: none;
          z-index: 1;
        }

        .square:hover .square-content::after {
          content: '';
          position: absolute;
          inset: 0;
          background: rgba(255, 255, 255, 0.1);
          pointer-events: none;
        }

        @media (hover: none) {
          .square:hover .square-content::after {
            display: none;
          }
        }

        .square.highlighted::after {
          content: '';
          position: absolute;
          inset: 0;
          background: rgba(0, 255, 0, 0.2);
          pointer-events: none;
          z-index: 1;
        }
      ` })
      ]
    }
  );
}
const useChessGame = (initialPosition = "start") => {
  const [position, setPosition] = useState(initialPosition);
  const [gameState, setGameState] = useState({
    isCheck: false,
    isCheckmate: false,
    isStalemate: false,
    isDraw: false,
    turn: "white",
    moveNumber: 1,
    halfMoves: 0,
    fen: initialPosition,
    pgn: ""
  });
  const makeMove = (from, to) => {
    console.log(`Moving from ${from} to ${to}`);
    return true;
  };
  return {
    position,
    gameState,
    makeMove
  };
};
const isValidMove = (_from, _to, _piece, _position) => {
  return true;
};
const generateFEN = (_position) => {
  return "";
};
export {
  ChessBoard,
  ChessProvider,
  Piece,
  PieceProvider,
  generateFEN,
  isValidMove,
  useChess,
  useChessGame,
  usePieces
};
//# sourceMappingURL=index.es.js.map