<template>
<div class="position-relative me-2">
    <i class="bx bx-link-alt" @click="togglePopover"></i>
    <!-- 링크 팝업 -->
    <div
    v-if="isPopoverVisible"
    class="popover bs-popover-auto fade show d-flex align-items-center"
    role="tooltip"
    :style="popoverStyle"
    >
    <div class="popover-arrow"></div>
    <input
        v-model="link"
        placeholder="URL을 입력해주세요"
        class="form-control me-2 flex-grow-1"
        style="min-width: 200px;"
    />
    <button type="button" class="btn btn-sm btn-primary ms-2" @click="saveLink">
        등록
    </button>
    </div>
    <!-- 등록된 링크 표시 -->
    <div v-if="link" class="mt-1">
    <a :href="formattedLink" target="_blank" rel="noopener noreferrer">{{ link }}</a>
    </div>
</div>
</template>

<script setup>
import { ref, computed } from "vue";

const props = defineProps({
modelValue: String,
});
const emit = defineEmits(["update:modelValue"]);

const isPopoverVisible = ref(false);
const link = ref(props.modelValue || "");
const popoverStyle = ref({});

const formattedLink = computed(() => {
    return link.value.startsWith("http") ? link.value : "http://" + link.value;
});

const togglePopover = (event) => {
    const buttonRect = event.target.getBoundingClientRect();
    const parentRect = event.target.parentElement.getBoundingClientRect();

    popoverStyle.value = {
        position: "absolute",
        top: `${buttonRect.bottom - parentRect.top + 5}px`,
        left: `${buttonRect.left - parentRect.left}px`,
        zIndex: "1050",
        display: "flex",
        alignItems: "center",
    };

    isPopoverVisible.value = !isPopoverVisible.value;
};

const saveLink = () => {
    emit("update:modelValue", link.value);
    isPopoverVisible.value = false;
};
</script>

<style scoped>
.popover {
    max-width: 300px;
    border-radius: 6px;
    padding: 5px;
    }

.popover-arrow {
    position: absolute;
    top: -5px;
    left: 50%;
    transform: translateX(-50%);
}
</style>
