<template>
    <button class="pc-toolbar-btn" type="button" :disabled="disabled" @click="$emit('click', $event)">
        <img :src="loading ? (loadingIcon ?? icon) : icon" :class="['pc-toolbar-btn-icon', { 'is-loading': loading }]"
            :alt="title" />
        <span v-if="title" class="pc-toolbar-btn-tooltip">{{ title }}</span>
    </button>
</template>

<script setup lang="ts">
defineProps<{
    icon: string;
    loadingIcon?: string;
    title: string;
    disabled?: boolean;
    loading?: boolean;
}>();

defineEmits<{ (e: 'click', event: MouseEvent): void }>();
</script>

<style scoped>
.pc-toolbar-btn {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    padding: 0;
    border: none;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
}

.pc-toolbar-btn:hover:not(:disabled) {
    background: #f5f7fa;
}

.pc-toolbar-btn:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

.pc-toolbar-btn-icon {
    width: 20px;
    height: 20px;
    display: block;
}

.pc-toolbar-btn-icon.is-loading {
    animation: pc-toolbar-btn-spin 1s linear infinite;
}

.pc-toolbar-btn-tooltip {
    position: absolute;
    bottom: calc(100% + 6px);
    left: 50%;
    transform: translateX(-50%) translateY(4px);
    padding: 4px 8px;
    background: rgba(0, 0, 0, 0.75);
    color: #fff;
    font-size: 12px;
    line-height: 16px;
    border-radius: 4px;
    white-space: nowrap;
    pointer-events: none;
    opacity: 0;
    transition: opacity 0.15s ease, transform 0.15s ease;
    z-index: 10;
}

.pc-toolbar-btn-tooltip::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    border: 4px solid transparent;
    border-top-color: rgba(0, 0, 0, 0.75);
}

.pc-toolbar-btn:hover:not(:disabled) .pc-toolbar-btn-tooltip {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
}

@keyframes pc-toolbar-btn-spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
</style>
