<script lang="ts">
    import {random_string} from "$shared/lib/helpers";

    export const id = "__menu_" + random_string(3);
    export let trigger: HTMLElement;
    export let show = false;

    let windowInnerWidth = 0;
    let windowInnerHeight = 0;
    let menu: HTMLMenuElement;

    $: if (show && menu && trigger) {
        const
            selectedTriggerPosition = trigger.getBoundingClientRect(),
            menuOnTop = (windowInnerHeight - selectedTriggerPosition.bottom) < selectedTriggerPosition.top,
            left = selectedTriggerPosition.left,
            right = (windowInnerWidth - selectedTriggerPosition.right),
            isRight = (windowInnerWidth < selectedTriggerPosition.left + menu.offsetWidth),
            vertical = menuOnTop
                ? "bottom: " + (windowInnerHeight - selectedTriggerPosition.top) + "px;"
                : "top: " + selectedTriggerPosition.bottom + "px;";

        let horizontal = isRight ? "right: " + right + "px;" : "left: " + left + "px;";

        // check right position is correct -> otherwise set left to 0
        if (isRight && (right + menu.offsetWidth) > windowInnerWidth) horizontal = ("left: " + (windowInnerWidth - menu.offsetWidth) / 2 + "px;");
        const maxHeight = menuOnTop ? selectedTriggerPosition.top - 20 : windowInnerHeight - selectedTriggerPosition.bottom - 20;
        menu.setAttribute("style", horizontal + vertical + "max-height:" + Math.floor(maxHeight) + "px;");
    }
    
    function on_window_click(event) {
        if (!event.target.closest("#" + id) && !event.target.closest("[aria-controls='" + id + "']")) show = false;
    }

    function on_window_touchend(event) {
        if (!event.target.closest("#" + id) && !event.target.closest("[aria-controls='" + id + "']")) show = false;
    }
</script>

<svelte:window
        on:click={on_window_click}
        on:touchend={on_window_touchend}
        bind:innerWidth={windowInnerWidth}
        bind:innerHeight={windowInnerHeight}
/>

<menu class="menu"
      id="{id}"
      bind:this={menu}
      class:menu--is-visible={show}
      aria-expanded="{show}"
      aria-haspopup="true">
    <slot name="options"/>
</menu>
