import { onBeforeUnmount, onMounted, ref, watch } from "vue";

/**
 * Docked-preview support detection:
 * a ResizeObserver on the builder layout drives `supportsPinnedPreview` with a
 * 40px hysteresis band (enable >= 1180px, disable < 1140px) so the button
 * doesn't jitter at the boundary. Dropping below the disable width auto-unpins.
 * Pin state is intentionally NOT persisted (in-memory only).
 *
 * The layout element mounts behind `v-if="!store.loading"`, so it usually does
 * NOT exist yet when this composable's onMounted runs — the ref is WATCHED and
 * the observer attaches whenever the element appears. Until then the window
 * width seeds an immediate answer so the pin button shows without waiting.
 */
const PIN_ENABLE_WIDTH = 1180;
const PIN_DISABLE_WIDTH = 1140;

export function usePreviewLayout(layoutRef) {
    const supportsPinnedPreview = ref(false);
    const previewPinned = ref(false);
    let observer = null;

    const evaluate = (width) => {
        if (width >= PIN_ENABLE_WIDTH) {
            supportsPinnedPreview.value = true;
        } else if (width < PIN_DISABLE_WIDTH) {
            supportsPinnedPreview.value = false;
            if (previewPinned.value) {
                previewPinned.value = false;
            }
        }
    };

    const attach = (el) => {
        if (!el || typeof ResizeObserver === "undefined") {
            return;
        }
        if (observer) {
            observer.disconnect();
        }
        observer = new ResizeObserver((entries) => {
            for (const entry of entries) {
                evaluate(entry.contentRect.width);
            }
        });
        observer.observe(el);
        evaluate(el.getBoundingClientRect().width);
    };

    onMounted(() => {
        // Immediate seed — the layout element may not exist yet (v-if).
        evaluate(window.innerWidth);
        attach(layoutRef.value);
    });

    watch(layoutRef, (el) => attach(el));

    onBeforeUnmount(() => {
        if (observer) {
            observer.disconnect();
            observer = null;
        }
    });

    return { supportsPinnedPreview, previewPinned };
}
