<template>
    <a-breadcrumb-item v-if="selectedWebsite">
        <span class="breadcrumb-business">
            <span class="breadcrumb-business-name">{{ selectedWebsite.name }}</span>
            <a-tooltip
                v-if="selectedWebsite.landing_url"
                :title="$t('website.visit_page')"
            >
                <a @click.prevent="openUrl" class="breadcrumb-icon">
                    <LinkOutlined />
                </a>
            </a-tooltip>
            <a-tooltip :title="$t('website.view_qr_code')">
                <a @click.prevent="showViewModal" class="breadcrumb-icon">
                    <QrcodeOutlined />
                </a>
            </a-tooltip>
        </span>
    </a-breadcrumb-item>
</template>

<script setup>
import { ref, onUnmounted, h, render } from "vue";
import { LinkOutlined, QrcodeOutlined } from "@ant-design/icons-vue";
import { useAuthStore } from "../../main/store/authStore";
import { storeToRefs } from "pinia";

const authStore = useAuthStore();
const { selectedWebsite } = storeToRefs(authStore);

let modalContainer = null;

const openUrl = () => {
    if (selectedWebsite.value?.landing_url) {
        window.open(selectedWebsite.value.landing_url, "_blank");
    }
};

const showViewModal = async () => {
    // Dynamically import the modal component
    const BusinessView = (await import("../../main/views/websites/View.vue")).default;

    // Create container if not exists
    if (!modalContainer) {
        modalContainer = document.createElement("div");
        modalContainer.id = "business-view-modal-container";
        document.body.appendChild(modalContainer);
    }

    const closeModal = () => {
        if (modalContainer) {
            render(null, modalContainer);
        }
    };

    // Render modal using Vue's render function
    const vnode = h(BusinessView, {
        data: selectedWebsite.value,
        visible: true,
        onClosed: closeModal,
    });

    render(vnode, modalContainer);
};

onUnmounted(() => {
    if (modalContainer) {
        render(null, modalContainer);
        if (modalContainer.parentNode) {
            modalContainer.parentNode.removeChild(modalContainer);
        }
        modalContainer = null;
    }
});
</script>

<style scoped>
.breadcrumb-business {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    margin-top: -2px;
}

.breadcrumb-icon {
    color: #1890ff;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
}

.breadcrumb-icon :deep(svg) {
    font-size: 12px;
}

.breadcrumb-icon:hover {
    color: #40a9ff;
}
</style>
