import { createStore } from 'solid-js/store';
import { render, createComponent } from 'solid-js/web';
import { Relative } from '@cn-ui/core';
import { atom } from '@cn-ui/use';
import { createContext, useContext, For } from 'solid-js';

/** simple memorize result of function */

const memoize = function (func) {
  let result = undefined;
  return (...args) => {
    if (result) return result;
    result = func(...args);
    return result;
  };
};

const OutSpaceContext = createContext();
const getOutSpace = memoize(() => {
  const OutSpaceData = {
    top: atom([]),
    tl: atom([]),
    tr: atom([]),
    bottom: atom([]),
    bl: atom([]),
    br: atom([]),
    left: atom([]),
    lt: atom([]),
    lb: atom([]),
    right: atom([]),
    rt: atom([]),
    rb: atom([])
  }; // 注意，这个没有被导出

  const OuterSpace = ({}) => {
    const space = useContext(OutSpaceContext);
    const style = {
      'z-index': 1000
    }; // ['top', 'tl', 'tr', 'bottom', 'bl', 'br', 'left', 'lt', 'lb', 'right', 'rt', 'rb'] as const;

    return createComponent(Relative, {
      fixed: true,
      "class": ' pointer-events-none top-0 left-0 h-screen w-screen ',
      style: style,

      get children() {
        return createComponent(For, {
          get each() {
            return space.top();
          },

          children: item => item()
        });
      }

    });
  };
  /** 向全局注入一个默认的 Layer 空间，生命周期为 solid 全生命 */


  render(() => {
    return createComponent(OutSpaceContext.Provider, {
      value: OutSpaceData,

      get children() {
        return [createComponent(OuterSpace, {}), ";"];
      }

    });
  }, document.body);
  return OutSpaceData;
});

const defaultProps = {
  // locale: defaultLocale,
  prefixCls: 'cn',
  getPopupContainer: () => document.body,
  size: 'default',
  // renderEmpty,
  focusLock: {
    modal: {
      autoFocus: true
    },
    drawer: {
      autoFocus: true
    }
  },

  getPrefixCls(componentName, customPrefix = 'cn') {
    return `${customPrefix}-${componentName}`;
  }

};
const [store, setStore] = createStore(defaultProps);
const GlobalConfigStore = store;
const setGlobalConfig = setStore;

export { GlobalConfigStore, OutSpaceContext, getOutSpace, setGlobalConfig };
