<script>
    let { fields } = $props();

    let params = new URLSearchParams(document.location.search);

    let sortBy = $state(params.get("sortBy") + "_" + params.get("sortDir"));
    let columns = $state(params.get("columns")?.split(",") || []);

    function handleSortAsc() {
        params.set("sortBy", sortBy.replace("_asc", ""));
        params.set("sortDir", "asc");
        Turbo.visit(window.location.pathname + `?` + params.toString());
    }

    function handleSortDesc() {
        params.set("sortBy", sortBy.replace("_desc", ""));
        params.set("sortDir", "desc");
        Turbo.visit(window.location.pathname + `?` + params.toString());
    }

    function handleToggleColumn() {
        params.set("columns", columns.join(","));
        Turbo.visit(window.location.pathname + `?` + params.toString());
    }
</script>

<!-- Radios -->
<details class="dropdown">
    <summary> Sort by </summary>
    <ul>
        {#each fields as field}
            <li>
                <label>
                    <input
                        bind:group={sortBy}
                        type="radio"
                        value={field.id + "_asc"}
                        onchange={handleSortAsc}
                    />
                    {field.name}
                </label>
            </li>
            <li>
                <label>
                    <input
                        bind:group={sortBy}
                        type="radio"
                        value={field.id + "_desc"}
                        onchange={handleSortDesc}
                    />
                    {field.name} desc
                </label>
            </li>
        {/each}
    </ul>
</details>

<!-- Checkboxes -->
<details class="dropdown">
    <summary> Show/Hide columns </summary>
    <ul>
        {#each fields as field}
            <li>
                <label>
                    <input
                        bind:group={columns}
                        type="checkbox"
                        value={field.id}
                        onchange={handleToggleColumn}
                    />
                    {field.name}
                </label>
            </li>
        {/each}
    </ul>
</details>
