<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from "vue";
import { useNamespace, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { colorPickerProps, colorPickerEmits } from "./color-picker";
import SVPanel from "./sv-panel.vue";
import HueSlider from "./hue-slider.vue";
import AlphaSlider from "./alpha-slider.vue";
import { parseColor, formatColor, hsvToRgb, getLuminance } from "./utils";
defineOptions({
  name: "YhColorPicker"
});
const props = defineProps(colorPickerProps);
const emit = defineEmits(colorPickerEmits);
const ns = useNamespace("color-picker");
const { t } = useLocale();
const { themeStyle } = useComponentTheme(
  "color-picker",
  computed(() => props.themeOverrides)
);
const visible = ref(false);
const color = ref(parseColor(props.modelValue));
const inputValue = ref(props.modelValue || "");
const triggerRef = ref();
const popperRef = ref();
const rgb = computed(() => hsvToRgb(color.value.h, color.value.s, color.value.v));
const baseColor = computed(() => `hsl(${color.value.h}, 100%, 50%)`);
const currentColor = computed(() => formatColor(color.value, props.colorFormat));
const contrastInfo = computed(() => {
  const l = getLuminance(rgb.value.r, rgb.value.g, rgb.value.b);
  return {
    isDark: l < 0.5,
    suggestion: l < 0.5 ? t("colorpicker.suggestionDark") : t("colorpicker.suggestionLight")
  };
});
watch(
  () => props.modelValue,
  (val) => {
    const parsed = parseColor(val);
    if (JSON.stringify(parsed) !== JSON.stringify(color.value)) {
      color.value = parsed;
    }
    inputValue.value = val || "";
  }
);
watch(currentColor, (val) => {
  inputValue.value = val;
});
const updateColor = () => {
  const val = currentColor.value;
  emit("update:modelValue", val);
  emit("activeChange", val);
};
const handleInputChange = (event) => {
  const target = event.target;
  const text = target.value;
  const parsed = parseColor(text);
  color.value = parsed;
  updateColor();
};
const handleConfirm = () => {
  emit("change", currentColor.value);
  visible.value = false;
};
const handleClear = () => {
  inputValue.value = "";
  color.value = { h: 0, s: 0, v: 100, a: 1 };
  emit("update:modelValue", "");
  emit("change", "");
  visible.value = false;
};
const isEyeDropperSupported = ref(false);
onMounted(() => {
  isEyeDropperSupported.value = typeof window.EyeDropper !== "undefined";
});
const handleEyeDropper = async () => {
  if (!isEyeDropperSupported.value) return;
  const eyeDropper = new window.EyeDropper();
  try {
    const result = await eyeDropper.open();
    color.value = parseColor(result.sRGBHex);
    updateColor();
  } catch {
  }
};
const togglePopper = () => {
  if (props.disabled) return;
  visible.value = !visible.value;
};
const handleClickOutside = (e) => {
  if (visible.value && triggerRef.value && !triggerRef.value.contains(e.target) && popperRef.value && !popperRef.value.contains(e.target)) {
    visible.value = false;
  }
};
const handlePredefineClick = (c) => {
  color.value = parseColor(c);
  updateColor();
};
const popperStyle = ref({});
const updatePosition = () => {
  if (!visible.value || !triggerRef.value) return;
  const rect = triggerRef.value.getBoundingClientRect();
  const styles = window.getComputedStyle(triggerRef.value);
  const primary = styles.getPropertyValue("--yh-color-primary").trim();
  const primaryRgb = styles.getPropertyValue("--yh-color-primary-rgb").trim();
  popperStyle.value = {
    ...themeStyle.value,
    top: `${rect.bottom + window.scrollY + 8}px`,
    left: `${rect.left + window.scrollX}px`,
    position: "absolute",
    zIndex: 3e3,
    "--yh-color-primary": primary,
    "--yh-color-primary-rgb": primaryRgb
  };
};
watch(visible, (val) => {
  if (val) {
    updatePosition();
    window.addEventListener("scroll", updatePosition, true);
    window.addEventListener("resize", updatePosition);
  } else {
    window.removeEventListener("scroll", updatePosition, true);
    window.removeEventListener("resize", updatePosition);
  }
});
onMounted(() => {
  document.addEventListener("click", handleClickOutside);
});
onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside);
  window.removeEventListener("scroll", updatePosition, true);
  window.removeEventListener("resize", updatePosition);
});
defineExpose({
  visible,
  togglePopper,
  handleClear,
  handleConfirm
});
</script>

<template>
  <div
    ref="triggerRef"
    :class="[ns.b(), ns.m(size), ns.is('disabled', disabled)]"
    :style="themeStyle"
    @click="togglePopper"
  >
    <div :class="ns.e('trigger')">
      <div :class="ns.e('color')" :style="{
  backgroundColor: modelValue || 'transparent'
}">
        <svg
          v-if="!modelValue"
          viewBox="0 0 1024 1024"
          width="1em"
          height="1em"
          class="yh-color-picker__empty"
        >
          <path
            fill="currentColor"
            d="M764.288 214.592L512 466.88L259.712 214.592l-45.12 45.12L466.88 512l-252.288 252.288l45.12 45.12L512 557.12l252.288 252.288l45.12-45.12L557.12 512l252.288-252.288z"
          />
        </svg>
      </div>
      <div :class="ns.e('icon')">
        <svg viewBox="0 0 1024 1024" width="1em" height="1em">
          <path
            fill="currentColor"
            d="M831.872 340.864L512 652.672L192.128 340.864l-45.248 45.248L512 743.168l365.12-357.056z"
          />
        </svg>
      </div>
    </div>

    <Teleport to="body">
      <Transition name="yh-fade">
        <div
          v-if="visible"
          ref="popperRef"
          :class="[ns.e('panel'), popperClass]"
          :style="popperStyle"
          @click.stop
        >
          <div :class="ns.e('main')">
            <SVPanel
              :h="color.h"
              :s="color.s"
              :v="color.v"
              @update="(s, v) => {
  color.s = s;
  color.v = v;
  updateColor();
}"
            />
            <div :class="ns.e('contrast-advisor')" :title="t('colorpicker.suggestionDark')">
              <span
                :class="ns.e('contrast-dot')"
                :style="{
  backgroundColor: contrastInfo.isDark ? '#fff' : '#000'
}"
              ></span>
              {{ contrastInfo.suggestion }}
            </div>
            <div :class="ns.e('sliders')">
              <HueSlider
                :h="color.h"
                @update="h => {
  color.h = h;
  updateColor();
}"
              />
              <AlphaSlider
                v-if="showAlpha"
                :a="color.a"
                :color="baseColor"
                @update="a => {
  color.a = a;
  updateColor();
}"
              />
            </div>
          </div>

          <div v-if="predefine.length > 0" :class="ns.e('predefine')">
            <div
              v-for="c in predefine"
              :key="c"
              :class="ns.e('predefine-item')"
              :style="{
  backgroundColor: c
}"
              @click="handlePredefineClick(c)"
            ></div>
          </div>

          <div :class="ns.e('footer')">
            <div :class="ns.e('tools')">
              <div
                v-if="isEyeDropperSupported"
                :class="ns.e('eye-dropper')"
                @click="handleEyeDropper"
                :title="t('colorpicker.eyeDropper')"
              >
                <svg viewBox="0 0 1024 1024" width="1.2em" height="1.2em">
                  <path
                    fill="currentColor"
                    d="M148.65 892.42c-29.6 0-53.59-24-53.59-53.59 0-14.28 5.68-27.97 15.76-38.05L511.45 400.1c11.02-11.02 26.23-16.71 42.84-16.03l68.74 3c14.77.65 26.79 12.67 27.44 27.44l3 68.74c.68 16.61-5.01 31.81-16.03 42.84L236.78 926.75a53.48 53.48 0 0 1-38.05 15.76c-16.63-.04-33.31-7.04-50.08-50.09zm522.61-460.67l-26.68 26.68c34.78 35.8 70.9 71.55 107.5 107.22l26.68-26.68c-36.63-35.61-72.76-71.38-107.5-107.22zm256.4-180.25l-20.91-20.91c-43.11-43.11-113-43.11-156.11 0L575.48 405.74c-4.47 4.47-7.16 10.4-7.58 16.68l-4.52 103.88c-.37 8.52 3.01 16.59 9.53 22.73s15.17 9.17 23.63 8.35L711.66 550c6.26-.49 12.1-3.26 16.5-7.78l175.16-180.36c43.11-43.11 43.11-113 0-156.11z"
                  />
                </svg>
              </div>
              <input
                :class="ns.e('value')"
                :value="inputValue"
                @change="handleInputChange"
                spellcheck="false"
              />
            </div>
            <div :class="ns.e('btns')">
              <button :class="ns.e('btn-clear')" @click="handleClear">
                {{ t("colorpicker.clear") }}
              </button>
              <button :class="ns.e('btn-confirm')" @click="handleConfirm">
                {{ t("colorpicker.confirm") }}
              </button>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-color-picker {
  display: inline-block;
  position: relative;
  line-height: normal;
  cursor: pointer;
}
.yh-color-picker__trigger {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px;
  border: 1px solid var(--yh-border-color, #dcdfe6);
  border-radius: 4px;
  background: var(--yh-bg-color, #fff);
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  height: 32px;
  box-sizing: border-box;
  width: 60px;
}
.yh-color-picker__trigger:hover {
  border-color: var(--yh-color-primary, #6366f1);
}

.yh-color-picker.is-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
.yh-color-picker.is-disabled .yh-color-picker .yh-color-picker__trigger {
  background-color: var(--yh-fill-color-light);
  border-color: var(--yh-border-color-lighter);
}

.yh-color-picker--large .yh-color-picker__trigger {
  height: 40px;
  width: 70px;
}

.yh-color-picker--small .yh-color-picker__trigger {
  height: 24px;
  width: 45px;
}

.yh-color-picker__color {
  flex: 1;
  height: 100%;
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(0, 0, 0, 0.05);
}
.yh-color-picker__color .yh-color-picker__empty {
  color: #ccc;
  font-size: 14px;
}

.yh-color-picker__icon {
  margin-left: 4px;
  color: var(--yh-text-color-placeholder);
  font-size: 12px;
}

.yh-color-picker {
  /* Panel styles */
}
.yh-color-picker__panel {
  width: 280px;
  padding: 16px;
  background: var(--yh-bg-color-overlay, #fff);
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid var(--yh-border-color-light);
  user-select: none;
  z-index: 3000;
}

.yh-color-picker__main {
  margin-bottom: 16px;
  position: relative;
}

.yh-color-picker__contrast-advisor {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
  padding: 2px 8px;
  border-radius: 20px;
  font-size: 10px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  pointer-events: none;
  z-index: 10;
}

.yh-color-picker__contrast-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.yh-color-picker__sliders {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.yh-color-picker__predefine {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--yh-border-color-lighter);
}
.yh-color-picker__predefine-item {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}
.yh-color-picker__predefine-item:hover {
  transform: scale(1.15);
}

.yh-color-picker__footer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--yh-border-color-lighter);
  display: flex;
  flex-direction: column; /* 垂直排版避免横向挤压 */
  gap: 12px;
}

.yh-color-picker__tools {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.yh-color-picker__eye-dropper {
  cursor: pointer;
  color: var(--yh-text-color-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  transition: background 0.2s, color 0.2s;
}
.yh-color-picker__eye-dropper:hover {
  background: var(--yh-fill-color-light);
  color: var(--yh-color-primary);
}

.yh-color-picker__value {
  flex: 1;
  height: 28px;
  padding: 0 8px;
  font-size: 12px;
  font-family: var(--yh-font-family-mono, monospace);
  color: var(--yh-text-color-primary);
  background: var(--yh-fill-color-light);
  border: 1px solid transparent;
  border-radius: 4px;
  outline: none;
  width: 0;
}
.yh-color-picker__value:focus {
  border-color: var(--yh-color-primary);
  background: var(--yh-bg-color, #fff);
}

.yh-color-picker__btns {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  width: 100%;
}

.yh-color-picker__btn-clear {
  padding: 5px 12px;
  font-size: 12px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid var(--yh-border-color);
  background: transparent;
  color: var(--yh-text-color-regular);
  transition: all 0.2s;
}
.yh-color-picker__btn-clear:hover {
  color: var(--yh-color-primary);
  border-color: var(--yh-color-primary-light-7);
}

.yh-color-picker__btn-confirm {
  padding: 5px 16px;
  font-size: 12px;
  border-radius: 4px;
  cursor: pointer;
  background: var(--yh-color-primary);
  color: #fff;
  border: 1px solid var(--yh-color-primary);
  transition: all 0.2s;
}
.yh-color-picker__btn-confirm:hover {
  background: var(--yh-color-primary-light-3);
  border-color: var(--yh-color-primary-light-3);
}

.yh-fade-enter-active,
.yh-fade-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}

.yh-fade-enter-from,
.yh-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
