<script>
    import { createEventDispatcher, getContext } from 'svelte';
    import FilterSelect from './FilterSelect.svelte';

    const { outerWidth } = getContext('stores');

    export let column;
    export let textDirection;

    const dispatch = createEventDispatcher();

    export let active;

    $: buttonsFit = lastLinkOffset < $outerWidth;

    let buttonsContainer;
    const linkButtons = [];

    $: lastLinkOffset = linkButtons
        .filter(a => a)
        .slice(-1)
        .map(el => {
            const contLeft = buttonsContainer.getBoundingClientRect().left;
            const linkRight = el.getBoundingClientRect().right;
            return linkRight - contLeft;
        })[0];

    $: options = column
        .values()
        .filter((d, i) => column.raw()[i])
        .map((c, i) => {
            return { value: column.raw()[i], index: i };
        });

    $: optionsOrdered = textDirection === 'rtl' ? options.reverse() : options;

    function select(d) {
        $active = d.index;
        dispatch('change', d);
    }
</script>

<style lang="scss">
    .filter-ui.filter-links {
        white-space: nowrap;
        overflow-x: hidden;
        overflow-y: hidden;
        line-height: 28px;

        a {
            display: inline-block;
            height: 28px;
            padding: 0px 10px;
            text-decoration: none;

            &.active {
                box-shadow: none;
                cursor: default;
                text-decoration: none;
            }
        }
    }
    .invisible {
        opacity: 0;
        position: absolute;
        left: -9999px;
        pointer-events: none;
    }
</style>

<nav bind:this={buttonsContainer} class:invisible={!buttonsFit} class="filter-ui filter-links">
    {#each optionsOrdered as opt, i}
        <a
            bind:this={linkButtons[i]}
            tabindex="0"
            href="#{opt.index}"
            on:click|preventDefault={() => select(opt)}
            class="link-style-ignore"
            class:active={opt.index === $active}>{@html String(opt.value).trim()}</a
        >
    {/each}
</nav>

{#if !buttonsFit}
    <FilterSelect {column} on:change={evt => select(evt.detail)} {active} />
{/if}
