<template>
<div class="mb-2 row">
    <!-- 링크 아이콘 -->
    <label for="name" class="col-md-2 col-form-label">
        <div class="d-flex align-items-center">
            <!-- 링크 아이콘 -->
            <i class="bx bx-link-alt me-2" @click="togglePopover"></i>
            <!-- 등록된 링크, 입력창이 보이지 않고 등록된 링크만 보일 때 -->
            <span v-if="isLinkSaved && !isPopoverVisible" class="ms-2">
                <a :href="formattedLink" class="d-inline-block text-truncate" target="_blank" rel="noopener noreferrer">
                    {{ link }}
                </a>
            </span>
        </div>
    </label>
    <!-- 링크 입력창 (옆으로 나오게) -->
    <div v-if="isPopoverVisible" class="col-md-10">
        <div class="d-flex align-items-center">
            <input
                v-model="link"
                placeholder="URL을 입력해주세요"
                class="form-control me-2"
            />
            <save-btn class="btn-icon" @click="saveLink"/>
        </div>
    </div>
</div>
</template>

<script setup>
import SaveBtn from '@c/button/SaveBtn.vue'
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 isLinkSaved = ref(false);  // Track if the link has been saved

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

const togglePopover = () => {
isPopoverVisible.value = !isPopoverVisible.value;
};

const saveLink = () => {
emit("update:modelValue", link.value);
isLinkSaved.value = true;  // Set the link as saved
isPopoverVisible.value = false;
};
</script>

<style scoped>
.popover-container {
display: flex;
align-items: center;
gap: 8px; /* 아이콘과 입력창 간격 조정 */
}
a {
  max-width: 500px; /* 원하는 너비로 조정 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
