<template>
  <teleport :to="resolvedTeleportTo" :disabled="!resolvedTeleportTo || inner">
    <transition name="yh-drawer-fade" @after-leave="onAfterLeave">
      <div
        v-if="rendered"
        v-show="modelValue"
        :class="[ns.e('wrapper'), modalClass, {
  [ns.is('active')]: modelValue
}, {
  [ns.is('with-modal')]: modal
}, {
  [ns.is('inner')]: inner
}]"
        :style="{
  zIndex: drawerZIndex - 1
}"
        @click.self="handleClose(true)"
      >
        <div
          ref="drawerRef"
          v-show="modelValue"
          :class="[ns.b(), ns.m(placement), {
  [ns.is('open')]: modelValue
}, {
  [ns.m('glass')]: glass
}, {
  [ns.is('round')]: round
}, {
  [ns.is('inner')]: inner
}, customClass]"
          :style="[drawerStyles, {
  zIndex: drawerZIndex
}]"
          role="dialog"
          aria-modal="true"
          :aria-labelledby="titleId"
          :aria-describedby="bodyId"
          @mousedown.stop
        >
          <!-- Resizable Handle -->
          <div
            v-if="resizable"
            :class="[ns.e('handle'), ns.em('handle', placement)]"
            @mousedown="handleResizeStart"
          >
          </div>

          <div v-if="showHeader" :class="ns.e('header')" :style="titleStyle">
            <slot name="header">
              <span :id="titleId" :class="ns.e('title')">
                <template v-if="typeof title === 'string'">{{ title }}</template>
                <component :is="title" v-else-if="title" />
                <slot v-else name="title" />
              </span>
            </slot>
            <button
              v-if="showClose"
              type="button"
              :class="ns.e('close')"
              :aria-label="t('dialog.close')"
              @click="handleClose()"
            >
              <slot name="close-icon">
                <yh-icon :name="closeIcon" />
              </slot>
            </button>
          </div>

          <div :id="bodyId" :class="ns.e('body')" :style="contentStyle">
            <slot />
          </div>

          <div v-if="showFooter" :class="ns.e('footer')" :style="footerStyle">
            <slot name="footer" />
          </div>
        </div>
      </div>
    </transition>
  </teleport>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
import { drawerProps, drawerEmits } from "./drawer";
import { YhIcon } from "../../icon";
import { useNamespace, useZIndex, useScrollLock, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
defineOptions({
  name: "YhDrawer"
});
const props = defineProps(drawerProps);
const emit = defineEmits(drawerEmits);
const ns = useNamespace("drawer");
const { t } = useLocale();
const { nextZIndex } = useZIndex();
const { themeStyle } = useComponentTheme(
  "drawer",
  computed(() => props.themeOverrides)
);
const drawerRef = ref(null);
const rendered = ref(false);
const drawerZIndex = ref(props.zIndex || nextZIndex());
const currentSize = ref(props.size);
const titleId = `yh-drawer-title-${Math.random().toString(36).slice(2, 9)}`;
const bodyId = `yh-drawer-body-${Math.random().toString(36).slice(2, 9)}`;
const isHorizontal = computed(() => ["left", "right"].includes(props.placement));
const drawerStyles = computed(() => {
  const baseStyle = typeof props.drawerStyle === "object" ? props.drawerStyle : {};
  const styles = {
    ...themeStyle.value,
    ...baseStyle
  };
  const sizeValue = typeof currentSize.value === "number" ? `${currentSize.value}px` : currentSize.value;
  if (isHorizontal.value) {
    styles.width = sizeValue;
  } else {
    styles.height = sizeValue;
  }
  return styles;
});
const resolvedTeleportTo = computed(() => {
  if (typeof HTMLElement !== "undefined" && props.teleportTo instanceof HTMLElement) {
    return props.teleportTo;
  }
  if (typeof props.teleportTo === "string" && props.teleportTo) {
    return props.teleportTo;
  }
  if (typeof document !== "undefined") {
    return document.querySelector(".yh-config-provider") ?? "body";
  }
  return "body";
});
useScrollLock(computed(() => props.modelValue && props.lockScroll));
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      rendered.value = true;
      drawerZIndex.value = props.zIndex || nextZIndex();
      emit("open");
      nextTick(() => {
        emit("opened");
      });
    } else {
      emit("close");
    }
  },
  { immediate: true }
);
watch(
  () => props.size,
  (val) => {
    currentSize.value = val;
  }
);
const handleClose = (isClickModal = false) => {
  if (isClickModal && !props.closeOnClickModal) return;
  const done = () => {
    emit("update:modelValue", false);
  };
  if (props.beforeClose) {
    props.beforeClose(done);
  } else {
    done();
  }
};
const onAfterLeave = () => {
  emit("closed");
  if (props.destroyOnClose) {
    rendered.value = false;
  }
};
let startPos = 0;
let startSize = 0;
const handleResizeStart = (e) => {
  startPos = isHorizontal.value ? e.clientX : e.clientY;
  const rect = drawerRef.value?.getBoundingClientRect();
  if (!rect) return;
  startSize = isHorizontal.value ? rect.width : rect.height;
  window.addEventListener("mousemove", handleResizeMove);
  window.addEventListener("mouseup", handleResizeEnd);
  document.body.style.cursor = isHorizontal.value ? "col-resize" : "row-resize";
  document.body.style.userSelect = "none";
};
const handleResizeMove = (e) => {
  const currentPos = isHorizontal.value ? e.clientX : e.clientY;
  let diff = currentPos - startPos;
  if (props.placement === "right" || props.placement === "bottom") {
    diff = -diff;
  }
  let newSize = startSize + diff;
  newSize = Math.max(props.minSize, Math.min(newSize, props.maxSize));
  currentSize.value = newSize;
  emit("resize", newSize);
};
const handleResizeEnd = () => {
  window.removeEventListener("mousemove", handleResizeMove);
  window.removeEventListener("mouseup", handleResizeEnd);
  document.body.style.cursor = "";
  document.body.style.userSelect = "";
};
const handleKeyDown = (e) => {
  if (props.modelValue && props.closeOnPressEscape && e.key === "Escape") {
    handleClose();
  }
};
onMounted(() => {
  window.addEventListener("keydown", handleKeyDown);
});
onBeforeUnmount(() => {
  window.removeEventListener("keydown", handleKeyDown);
  handleResizeEnd();
});
defineExpose({
  drawerRef,
  handleClose
});
</script>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-drawer {
  position: fixed;
  background: var(--yh-bg-color-overlay);
  box-shadow: var(--yh-shadow-lg);
  display: flex;
  flex-direction: column;
  transition: all var(--yh-duration-base) ease;
  overflow: hidden;
  z-index: var(--yh-z-index-modal);
}
.yh-drawer__wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
  margin: 0;
  z-index: 2000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  background: transparent;
}
.yh-drawer__wrapper.is-active {
  opacity: 1;
  visibility: visible;
}
.yh-drawer__wrapper.is-with-modal {
  background: rgba(0, 0, 0, 0.45);
}
.yh-drawer__wrapper.is-inner {
  position: absolute;
}

.yh-drawer.is-inner {
  position: absolute;
}
.yh-drawer--left {
  left: 0;
  top: 0;
  bottom: 0;
  transform: translateX(-100%);
}
.yh-drawer--left.is-round {
  border-radius: 0 16px 16px 0;
}

.yh-drawer--right {
  right: 0;
  top: 0;
  bottom: 0;
  transform: translateX(100%);
}
.yh-drawer--right.is-round {
  border-radius: 16px 0 0 16px;
}

.yh-drawer--top {
  top: 0;
  left: 0;
  right: 0;
  transform: translateY(-100%);
}
.yh-drawer--top.is-round {
  border-radius: 0 0 16px 16px;
}

.yh-drawer--bottom {
  bottom: 0;
  left: 0;
  right: 0;
  transform: translateY(100%);
}
.yh-drawer--bottom.is-round {
  border-radius: 16px 16px 0 0;
}

.yh-drawer.is-open {
  transform: translate(0, 0);
}
.yh-drawer--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-drawer--glass {
    background: rgba(25, 25, 30, 0.8) !important;
    border-color: rgba(255, 255, 255, 0.1);
  }
}

.yh-drawer__header {
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--yh-border-color-lighter);
}

.yh-drawer__title {
  font-size: var(--yh-font-size-lg);
  font-weight: 600;
  color: var(--yh-text-color-primary);
  margin: 0;
}

.yh-drawer__close {
  padding: 0;
  background: transparent;
  border: none;
  outline: none;
  cursor: pointer;
  color: var(--yh-text-color-secondary);
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: var(--yh-radius-md);
  transition: all 0.2s;
}
.yh-drawer__close:hover {
  background: var(--yh-fill-color-light);
  color: var(--yh-color-danger);
}

.yh-drawer__body {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  color: var(--yh-text-color-regular);
  font-size: var(--yh-font-size-base);
  line-height: 1.6;
}

.yh-drawer__footer {
  padding: 16px 24px;
  border-top: 1px solid var(--yh-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.yh-drawer__handle {
  position: absolute;
  z-index: 10;
  background: transparent;
  transition: background 0.2s;
}
.yh-drawer__handle:hover, .yh-drawer__handle:active {
  background: var(--yh-color-primary-light-5);
}
.yh-drawer__handle--left {
  right: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  cursor: col-resize;
}

.yh-drawer__handle--right {
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  cursor: col-resize;
}

.yh-drawer__handle--top {
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  cursor: row-resize;
}

.yh-drawer__handle--bottom {
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  cursor: row-resize;
}

.yh-drawer-fade-enter-active,
.yh-drawer-fade-leave-active {
  transition: opacity 0.3s ease;
}

.yh-drawer-fade-enter-from,
.yh-drawer-fade-leave-to {
  opacity: 0;
}
</style>
