import { computed, ref, watchEffect } from 'vue';
import { useLocaleReceiver } from '../../locale-provider/LocaleReceiver';
import defaultLocale from '../../locale/en_US';
import useMergedState from '../../_util/hooks/useMergedState';
import '../color';
import { generateColor } from '../util';
export default function useModeColor(defaultValue, value, mode) {
  const [locale] = useLocaleReceiver('ColorPicker', defaultLocale.ColorPicker);
  // ======================== Base ========================
  // Color
  const [mergedColor, setMergedColor] = useMergedState(defaultValue, {
    value
  });
  // Mode
  const modeState = ref('single');
  const getModeOptions = computed(() => {
    const modeValue = mode.value;
    const list = (Array.isArray(modeValue) ? modeValue : [modeValue]).filter(m => m);
    if (!list.length) {
      list.push('single');
    }
    const modes = new Set(list);
    const optionList = [];
    const pushOption = (modeType, localeTxt) => {
      if (modes.has(modeType)) {
        optionList.push({
          label: localeTxt,
          value: modeType
        });
      }
    };
    pushOption('single', locale.value.singleColor);
    pushOption('gradient', locale.value.gradientColor);
    return {
      modes,
      optionList
    };
  });
  // ======================== Post ========================
  // We need align `mode` with `color` state
  // >>>>> Color
  const cacheColor = ref(null);
  const setColor = nextColor => {
    cacheColor.value = nextColor;
    setMergedColor(nextColor);
  };
  const postColor = computed(() => {
    const colorObj = generateColor(mergedColor.value || '');
    return colorObj.equals(cacheColor.value) ? cacheColor.value : colorObj;
  });
  // >>>>> Mode
  const postMode = computed(() => {
    var _a;
    const {
      modes,
      optionList
    } = getModeOptions.value;
    if (modes.has(modeState.value)) {
      return modeState.value;
    }
    return (_a = optionList[0]) === null || _a === void 0 ? void 0 : _a.value;
  });
  // ======================= Effect =======================
  // Dynamic update mode when color change
  watchEffect(() => {
    modeState.value = postColor.value.isGradient() ? 'gradient' : 'single';
  });
  return {
    postColor,
    setColor,
    postMode,
    setModeState: nextMode => {
      modeState.value = nextMode;
    },
    modeOptionList: computed(() => getModeOptions.value.optionList)
  };
}