<script setup>
import { ref, watch, computed, nextTick, onBeforeUnmount } from "vue";
import { useNamespace, useEventListener, useId, useScrollLock, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { YhIcon } from "../../icon";
import { YhSpin } from "../../spin";
import { YhButton } from "../../button";
import { dialogProps, dialogEmits } from "./dialog";
defineOptions({
  name: "YhDialog",
  inheritAttrs: false
});
const props = defineProps(dialogProps);
const emit = defineEmits(dialogEmits);
const ns = useNamespace("dialog");
const { t } = useLocale();
const dialogId = useId();
const lastClickPos = ref(null);
const handleDocumentClick = (e) => {
  lastClickPos.value = { x: e.clientX, y: e.clientY };
};
useEventListener(
  () => typeof document !== "undefined" ? document : null,
  "pointerdown",
  (e) => handleDocumentClick(e),
  true
);
onBeforeUnmount(() => {
  if (typeof document !== "undefined") {
    if (activeMouseMoveListener) {
      document.removeEventListener("mousemove", activeMouseMoveListener);
      activeMouseMoveListener = null;
    }
    if (activeMouseUpListener) {
      document.removeEventListener("mouseup", activeMouseUpListener);
      activeMouseUpListener = null;
    }
  }
  if (typeof window !== "undefined" && prevFocusedElement) {
    prevFocusedElement.focus();
  }
});
const { themeStyle: themeVars } = useComponentTheme(
  "dialog",
  computed(() => props.themeOverrides)
);
const visible = ref(false);
const closed = ref(true);
const dialogRef = ref(null);
const headerRef = ref(null);
const rendered = ref(false);
useScrollLock(computed(() => props.modelValue && props.lockScroll));
const offset = ref({ x: 0, y: 0 });
const isDragging = ref(false);
let activeMouseMoveListener = null;
let activeMouseUpListener = null;
const handleMouseDown = (e) => {
  if (!props.draggable || props.fullscreen) return;
  if (e.button !== 0) return;
  if (headerRef.value && !headerRef.value.contains(e.target)) return;
  isDragging.value = true;
  emit("dragStart", e);
  const { clientX: startX, clientY: startY } = e;
  const { x: initialX, y: initialY } = offset.value;
  const onMouseMove = (moveEvent) => {
    if (!isDragging.value || !dialogRef.value) return;
    let nextX = initialX + (moveEvent.clientX - startX);
    let nextY = initialY + (moveEvent.clientY - startY);
    if (!props.overflow) {
      const rect = dialogRef.value.getBoundingClientRect();
      const { clientWidth, clientHeight } = document.documentElement;
      const minX = -rect.left + offset.value.x;
      const maxX = clientWidth - rect.right + offset.value.x;
      const minY = -rect.top + offset.value.y;
      const maxY = clientHeight - rect.bottom + offset.value.y;
      nextX = Math.min(Math.max(nextX, minX), maxX);
      nextY = Math.min(Math.max(nextY, minY), maxY);
    }
    offset.value = {
      x: nextX,
      y: nextY
    };
    emit("dragMove", moveEvent);
  };
  const onMouseUp = (upEvent) => {
    isDragging.value = false;
    emit("dragEnd", upEvent);
    if (typeof document !== "undefined") {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
    }
    activeMouseMoveListener = null;
    activeMouseUpListener = null;
  };
  activeMouseMoveListener = onMouseMove;
  activeMouseUpListener = onMouseUp;
  if (typeof document !== "undefined") {
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  }
};
let prevFocusedElement = null;
const trapFocus = (e) => {
  if (e.key !== "Tab" || !dialogRef.value) return;
  const focusableEls = dialogRef.value.querySelectorAll(
    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
  );
  const firstFocusableEl = focusableEls[0];
  const lastFocusableEl = focusableEls[focusableEls.length - 1];
  if (e.shiftKey) {
    if (document.activeElement === firstFocusableEl) {
      lastFocusableEl.focus();
      e.preventDefault();
    }
  } else {
    if (document.activeElement === lastFocusableEl) {
      firstFocusableEl.focus();
      e.preventDefault();
    }
  }
};
const style = computed(() => {
  const styles = {
    zIndex: props.zIndex
  };
  if (!props.fullscreen) {
    styles.width = typeof props.width === "number" ? `${props.width}px` : props.width;
    if (!props.alignCenter) {
      styles.marginTop = props.top;
    }
    if (props.transformOrigin === "mouse" && lastClickPos.value && dialogRef.value) {
      const rect = dialogRef.value.getBoundingClientRect();
      const originX = lastClickPos.value.x - rect.left;
      const originY = lastClickPos.value.y - rect.top;
      styles.transformOrigin = `${originX}px ${originY}px`;
    } else if (props.transformOrigin === "center") {
      styles.transformOrigin = "center";
    }
    if (offset.value.x !== 0 || offset.value.y !== 0) {
      styles.transform = `translate(${offset.value.x}px, ${offset.value.y}px)`;
    }
  }
  return {
    ...themeVars.value,
    ...styles,
    ...typeof props.style === "string" ? parseStyle(props.style) : props.style
  };
});
const parseStyle = (str) => {
  const obj = {};
  str.split(";").forEach((item) => {
    if (!item) return;
    const [key, val] = item.split(":");
    obj[key.trim()] = val.trim();
  });
  return obj;
};
const typeIconMap = {
  success: "success",
  warning: "warning",
  error: "error",
  info: "info"
};
const typeIcon = computed(() => typeIconMap[props.type] || "");
const dialogClasses = computed(() => [
  ns.b(),
  props.customClass,
  {
    [ns.m(props.type)]: props.type && props.type !== "default",
    [ns.m("fullscreen")]: props.fullscreen,
    [ns.m("align-center")]: props.alignCenter,
    [ns.m("center")]: props.center,
    [ns.m("glass")]: props.glass,
    [ns.is("draggable")]: props.draggable
  }
]);
const headerClasses = computed(() => [
  ns.e("header"),
  {
    [ns.em("header", "center")]: props.headerAlignCenter || props.center
  }
]);
const headerStyle = computed(() => {
  const align = props.center || props.headerAlignCenter ? "center" : props.headerAlign;
  if (align === "center") return { justifyContent: "center" };
  if (align === "right") return { justifyContent: "flex-end", paddingRight: "72px" };
  return { justifyContent: "flex-start" };
});
const contentBodyStyle = computed(() => {
  const styles = {};
  const align = props.center ? "center" : props.contentAlign;
  if (align === "center") styles.textAlign = "center";
  else if (align === "right") styles.textAlign = "right";
  else styles.textAlign = "left";
  return styles;
});
const footerClasses = computed(() => [
  ns.e("footer"),
  {
    [ns.em("footer", "center")]: props.footerAlignCenter || props.center
  }
]);
const footerStyle = computed(() => {
  const styles = {};
  const align = props.center || props.footerAlignCenter ? "center" : props.footerAlign;
  if (props.swapFooterButtons) {
    styles.flexDirection = "row-reverse";
    if (align === "right") styles.justifyContent = "flex-start";
    else if (align === "left") styles.justifyContent = "flex-end";
    else styles.justifyContent = "center";
  } else {
    if (align === "right") styles.justifyContent = "flex-end";
    else if (align === "left") styles.justifyContent = "flex-start";
    else styles.justifyContent = "center";
  }
  return styles;
});
const doClose = () => {
  if (typeof window !== "undefined" && prevFocusedElement) {
    prevFocusedElement.focus();
  }
  emit("update:modelValue", false);
};
const handleClose = () => {
  emit("close");
  if (props.beforeClose) {
    props.beforeClose(doClose);
  } else {
    doClose();
  }
};
const handleCancel = () => {
  emit("cancel");
  handleClose();
};
const handleConfirm = () => {
  emit("confirm");
  handleClose();
};
let mouseDownTargetAtWrapper = false;
const handleWrapperMouseDown = (e) => {
  mouseDownTargetAtWrapper = e.target === e.currentTarget;
};
const handleWrapperClick = (e) => {
  if (props.closeOnClickModal && mouseDownTargetAtWrapper && e.target === e.currentTarget) {
    handleClose();
  }
};
watch(
  () => props.modelValue,
  async (val) => {
    if (val) {
      rendered.value = true;
      closed.value = false;
      visible.value = true;
      emit("open");
      offset.value = { x: 0, y: 0 };
      if (typeof window === "undefined") return;
      prevFocusedElement = document.activeElement;
      await nextTick();
      if (props.autoFocus && dialogRef.value) {
        const focusableEls = dialogRef.value.querySelectorAll(
          'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );
        if (focusableEls.length > 0) {
          ;
          focusableEls[0].focus();
        } else {
          dialogRef.value.focus();
        }
      } else {
        dialogRef.value?.focus();
      }
      emit("opened");
    } else {
      visible.value = false;
      if (isDragging.value) {
        isDragging.value = false;
        if (typeof document !== "undefined") {
          if (activeMouseMoveListener) {
            document.removeEventListener("mousemove", activeMouseMoveListener);
            activeMouseMoveListener = null;
          }
          if (activeMouseUpListener) {
            document.removeEventListener("mouseup", activeMouseUpListener);
            activeMouseUpListener = null;
          }
        }
      }
      if (typeof window !== "undefined" && prevFocusedElement) {
        prevFocusedElement.focus();
      }
    }
  },
  { immediate: true }
);
const afterLeave = () => {
  closed.value = true;
  emit("closed");
};
useEventListener(
  () => window,
  "keydown",
  (e) => {
    const ke = e;
    if (!props.modelValue) return;
    if (props.closeOnPressEscape && ke.key === "Escape") {
      handleClose();
    }
    trapFocus(ke);
  }
);
defineExpose({
  visible,
  dialogRef,
  handleClose,
  handleCancel,
  handleConfirm
});
</script>

<template>
  <Teleport :to="teleportTo">
    <Transition :name="ns.b('fade')" @after-leave="afterLeave">
      <div
        v-if="rendered"
        v-show="modelValue"
        :class="ns.e('wrapper')"
        :style="{
  zIndex
}"
        @mousedown="handleWrapperMouseDown"
        @click.self="handleWrapperClick"
      >
        <div
          ref="dialogRef"
          :role="'dialog'"
          :aria-modal="true"
          :aria-labelledby="dialogId"
          :class="dialogClasses"
          :style="style"
          tabindex="-1"
        >
          <!-- 头部 -->
          <div
            ref="headerRef"
            :class="headerClasses"
            :style="headerStyle"
            @mousedown="handleMouseDown"
          >
            <slot name="header">
              <div :id="dialogId" :class="[ns.e('title'), titleClass]" :style="titleStyle">
                <YhIcon
                  v-if="showIcon && typeIcon"
                  :name="typeIcon"
                  :class="[ns.e('type-icon'), ns.em('type-icon', type)]"
                />
                <template v-if="typeof title === 'string'">{{ title }}</template>
                <component v-else-if="title" :is="title" />
              </div>
            </slot>
            <button v-if="showClose" :class="ns.e('headerbtn')" type="button" @click="handleClose">
              <YhIcon :name="closeIcon" />
            </button>
          </div>

          <!-- 主体 -->
          <div :class="[ns.e('body'), contentClass]" :style="[contentStyle, contentBodyStyle]">
            <div v-if="loading" :class="ns.e('loading')">
              <YhSpin :show="true" size="small" />
            </div>
            <slot v-if="!destroyOnClose || !closed">
              <template v-if="content">
                <template v-if="typeof content === 'string'">{{ content }}</template>
                <component v-else :is="content" />
              </template>
            </slot>
          </div>

          <!-- 底部 -->
          <div
            v-if="$slots.footer || action || showFooter"
            :class="[footerClasses, actionClass]"
            :style="[actionStyle, footerStyle]"
          >
            <slot name="footer">
              <template v-if="action">
                <component :is="action" />
              </template>
              <template v-else-if="showFooter">
                <YhButton @click="handleCancel">{{ cancelText || t("dialog.cancel") }}</YhButton>
                <YhButton type="primary" @click="handleConfirm">
                  {{ confirmText || t("dialog.confirm") }}
                </YhButton>
              </template>
            </slot>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-dialog {
  position: relative;
  margin: var(--yh-dialog-margin-top, 15vh) auto 50px;
  background: var(--yh-bg-color-overlay, #ffffff);
  border-radius: var(--yh-radius-lg, 16px);
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.15), 0 10px 20px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  outline: none;
}
.yh-dialog--fullscreen {
  width: 100% !important;
  height: 100% !important;
  margin: 0 !important;
  border-radius: 0 !important;
}

.yh-dialog--align-center {
  margin: auto !important;
}

.yh-dialog--center {
  text-align: center;
}
.yh-dialog--center .yh-dialog__header {
  border-bottom: none;
}

.yh-dialog--center .yh-dialog__footer {
  border-top: none;
}

.yh-dialog--glass {
  background: rgba(255, 255, 255, 0.7) !important;
  backdrop-filter: blur(24px) saturate(190%);
  border: 1px solid rgba(255, 255, 255, 0.4);
}
@media (prefers-color-scheme: dark) {
  .yh-dialog--glass {
    background: rgba(25, 25, 30, 0.8) !important;
    border-color: rgba(255, 255, 255, 0.1);
  }
}

.yh-dialog.is-draggable .yh-dialog__header {
  cursor: move;
  user-select: none;
}

.yh-dialog__wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
}

.yh-dialog__header {
  padding: 24px 24px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}
.yh-dialog__header.yh-dialog__header--center {
  justify-content: center;
}
.yh-dialog__header.yh-dialog__header--center .yh-dialog__title {
  width: 100%;
  text-align: center;
}

.yh-dialog__title {
  font-size: 20px;
  font-weight: 700;
  color: var(--yh-text-color-primary, #1a1a1a);
  line-height: 1.4;
  letter-spacing: -0.02em;
  display: flex;
  align-items: center;
  gap: 12px;
}

.yh-dialog__type-icon {
  font-size: 24px;
  flex-shrink: 0;
}
.yh-dialog__type-icon--success {
  color: var(--yh-color-success, #67c23a);
}

.yh-dialog__type-icon--warning {
  color: var(--yh-color-warning, #e6a23c);
}

.yh-dialog__type-icon--error {
  color: var(--yh-color-danger, #f56c6c);
}

.yh-dialog__type-icon--info {
  color: var(--yh-color-info, #909399);
}

.yh-dialog__headerbtn {
  position: absolute;
  top: 24px;
  right: 24px;
  background: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
  font-size: 22px;
  color: var(--yh-text-color-secondary, #909399);
  transition: all 0.25s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
}
.yh-dialog__headerbtn:hover {
  background-color: var(--yh-border-color-light, rgba(0, 0, 0, 0.05));
  color: var(--yh-color-danger, #f56c6c);
}

.yh-dialog__body {
  padding: 8px 24px 32px;
  color: var(--yh-text-color-regular, #4a4a4a);
  font-size: 15px;
  line-height: 1.6;
  flex: 1;
  overflow-y: auto;
  position: relative;
}
.yh-dialog__body::-webkit-scrollbar {
  width: 6px;
}
.yh-dialog__body::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.yh-dialog__loading {
  position: absolute;
  inset: 0;
  background: rgba(255, 255, 255, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  backdrop-filter: blur(2px);
}
@media (prefers-color-scheme: dark) {
  .yh-dialog__loading {
    background: rgba(0, 0, 0, 0.4);
  }
}

.yh-dialog__footer {
  padding: 16px 24px 24px;
  text-align: right;
  box-sizing: border-box;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.yh-dialog__footer.yh-dialog__footer--center {
  justify-content: center;
}

.yh-dialog-fade-enter-active {
  transition: opacity 0.3s ease-out;
}
.yh-dialog-fade-enter-active .yh-dialog {
  animation: yh-dialog-zoom-in 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28);
}
.yh-dialog-fade-leave-active {
  transition: opacity 0.2s ease-in;
}
.yh-dialog-fade-leave-active .yh-dialog {
  animation: yh-dialog-zoom-out 0.2s cubic-bezier(0.6, -0.28, 0.735, 0.045);
}
.yh-dialog-fade-enter-from, .yh-dialog-fade-leave-to {
  opacity: 0;
}

@keyframes yh-dialog-zoom-in {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}
@keyframes yh-dialog-zoom-out {
  from {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
  to {
    opacity: 0;
    transform: scale(0.95) translateY(10px);
  }
}
</style>
