<template>
    <Teleport to="#modals">
        <Transition name="modal-comp--transition">
            <div class="modal-comp" v-show="showed" @click.self="returnResult('')">
                <div class="modal-comp__container">
                    <slot></slot>

                    <div class="modal-comp__buttons" v-if="modalType === 'yes_no'">
                        <ButtonComp type="primary" value="Да" @click="returnResult('yes')" />
                        <ButtonComp type="default" value="Нет" @click="returnResult('no')" />
                    </div>

                    <div class="modal-comp__buttons" v-else-if="modalType === 'cancel_leave'">
                        <ButtonComp type="default" value="Отмена" @click="returnResult('cancel')" />
                        <ButtonComp type="primary" value="Выйти" @click="returnResult('leave')" />
                    </div>

                    <FontAwesomeIcon class="modal-comp__close" icon="xmark" v-if="modalType === 'default'" @click="returnResult('')" />
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<script setup lang="ts">
import { ref } from "vue";

type types = "default" | "yes_no" | "cancel_leave";

const showed = ref(false);
const modalType = ref<types>("default");
let promiseResolve: (value: unknown) => void = function () {
    console.log("unknown");
};

function open(options: { type: types } = { type: "default" }) {
    showed.value = true;
    modalType.value = options.type;

    return new Promise((resolve) => {
        promiseResolve = resolve;
    });
}

function returnResult(result: string) {
    promiseResolve(result);
    close();
}

function close() {
    showed.value = false;
}

defineExpose({ open, close });
</script>

<style lang="scss">
.modal-comp {
    position: fixed;
    inset: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: r(20);
    background: hsla(0, 0, 0, 0.5);

    z-index: 200;

    &__container {
        position: relative;
        padding: r(20);
        background: color("main-background");
        border-radius: r(6);
    }

    &__buttons {
        display: flex;
        justify-content: flex-end;
        gap: r(20);
        margin-top: r(20);
    }

    &__close {
        position: absolute;
        top: r(10);
        right: r(10);
        width: r(30);
        height: r(30);
        padding: r(5);
        border-radius: 50%;
        background: color("main-background");
        cursor: pointer;
    }

    &--transition {
        &-enter-active {
            transition: opacity 0.1s ease-out;
        }
        &-leave-active {
            transition: opacity 0.1s ease-in;
        }

        &-enter-from,
        &-leave-to {
            opacity: 0;
        }
    }
}
</style>
