<script setup>
import { onBeforeUnmount, onMounted } from "vue";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  title: { type: String, default: "" },
  maxWidth: { type: String, default: "720px" }
});

const emit = defineEmits(["update:modelValue"]);

function close() {
  emit("update:modelValue", false);
}

function onKeydown(e) {
  if (e.key === "Escape") close();
}

onMounted(() => {
  window.addEventListener("keydown", onKeydown);
});

onBeforeUnmount(() => {
  window.removeEventListener("keydown", onKeydown);
});
</script>

<template>
  <teleport to="body">
    <div v-if="modelValue" class="bb-modalOverlay" role="dialog" aria-modal="true">
      <div class="bb-modalBackdrop" @click="close" />
      <div class="bb-modalPanel" :style="{ maxWidth }">
        <div class="bb-modalHeader">
          <div class="bb-modalTitle">{{ title }}</div>
          <button type="button" class="bb-modalClose" @click="close" aria-label="关闭">×</button>
        </div>
        <div class="bb-modalBody">
          <slot />
        </div>
      </div>
    </div>
  </teleport>
</template>

<style scoped>
.bb-modalOverlay {
  position: fixed;
  inset: 0;
  z-index: 2147483500;
  display: grid;
  place-items: center;
  padding: 18px;
}

.bb-modalBackdrop {
  position: absolute;
  inset: 0;
  background: rgba(15, 23, 42, 0.35);
  backdrop-filter: blur(6px);
}

.bb-modalPanel {
  position: relative;
  width: min(100%, var(--bb-modal-max, 720px));
  max-height: min(84vh, 860px);
  overflow: auto;
  border-radius: 18px;
  border: 1px solid rgba(255,255,255,0.65);
  background: rgba(255,255,255,0.82);
  backdrop-filter: blur(14px);
  box-shadow: 0 18px 60px rgba(15, 23, 42, 0.18);
}

.bb-modalHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 12px 14px;
  border-bottom: 1px solid rgba(15, 23, 42, 0.08);
}

.bb-modalTitle {
  font-weight: 900;
  color: var(--bb-text);
}

.bb-modalClose {
  width: 34px;
  height: 34px;
  border-radius: 12px;
  border: 1px solid rgba(255,255,255,0.55);
  background: rgba(255,255,255,0.45);
  cursor: pointer;
  font-size: 20px;
  line-height: 1;
  color: rgba(15, 23, 42, 0.72);
}

.bb-modalClose:hover {
  background: rgba(255,255,255,0.75);
}

.bb-modalBody {
  padding: 14px;
}
</style>
