<script setup>
import { onMounted, onBeforeUnmount, ref, nextTick } 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
        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">
.q-toolbar {
    background: var(--vn-section-color);
}
</style>
<style lang="scss" scoped>
.sticky {
    position: sticky;
    top: 61px;
    z-index: 1;
}
@media (max-width: $breakpoint-sm) {
    .sticky {
        top: 90px;
    }
}
</style>
