<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import { useStateStore } from 'stores/useStateStore';

const stateStore = useStateStore();
const actions = ref(null);
const data = ref(null);
const opts = { subtree: true, childList: true, attributes: true };
const hasContent = ref(false);

onMounted(() => {
    stateStore.toggleSubToolbar();
    actions.value = document.querySelector('#st-actions');
    data.value = document.querySelector('#st-data');

    if (!actions.value && !data.value) return;

    // Check if there's content to display
    const observer = new MutationObserver(
        () =>
            (hasContent.value =
                actions.value?.childNodes?.length + data.value?.childNodes?.length)
    );
    if (actions.value) observer.observe(actions.value, opts);
    if (data.value) observer.observe(data.value, opts);
});

onBeforeUnmount(() => stateStore.toggleSubToolbar());
</script>

<template>
    <QToolbar
        id="subToolbar"
        class="justify-end sticky"
        v-show="hasContent || $slots['st-actions'] || $slots['st-data']"
    >
        <slot name="st-data">
            <div id="st-data"></div>
        </slot>
        <QSpace />
        <slot name="st-actions">
            <div id="st-actions"></div>
        </slot>
    </QToolbar>
</template>
<style lang="scss" scoped>
.sticky {
    position: sticky;
    z-index: 1;
}
</style>
