<script>
    import FileTreeNode from './FileTreeNode.svelte';

    let { fileTree, openFile, openNewFileModal } = $props();
    let expandedDirs = $state([]);

    function toggleDir(path) {
        if (expandedDirs.includes(path)) {
            expandedDirs = expandedDirs.filter(p => p !== path);
        } else {
            expandedDirs = [...expandedDirs, path];
        }
    }

    function handleKeydown(event, action) {
        if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            action();
        }
    }
</script>

{#each fileTree as item}
    <div class="item">
        {#if item.type === 'directory'}
            <i class="folder icon {expandedDirs.includes(item.path) ? 'open' : ''}"
               style="cursor: pointer;"
               role="button"
               tabindex="0"
               aria-label="Toggle directory"
               onkeydown={(e) => handleKeydown(e, () => toggleDir(item.path))}
               onclick={() => toggleDir(item.path)}></i>
            <div class="content">
                <div class="header"
                     style="cursor: pointer; display: flex; justify-content: space-between; align-items: center;"
                     role="button"
                     tabindex="0"
                     onkeydown={(e) => handleKeydown(e, () => toggleDir(item.path))}
                     onclick={() => toggleDir(item.path)}>
                    {item.name}
                    <button class="ui icon mini button basic" onclick={(e) => { e.stopPropagation(); openNewFileModal(item.path); }} title="New File in this directory">
                        <i class="plus icon"></i>
                    </button>
                </div>
                {#if expandedDirs.includes(item.path)}
                    <div class="list">
                        <FileTreeNode fileTree={item.children} {openFile} {openNewFileModal} />
                    </div>
                {/if}
            </div>
        {:else}
            <i class="file alternate outline icon"></i>
            <div class="content">
                <div class="header"
                     style="cursor: pointer;"
                     role="button"
                     tabindex="0"
                     onkeydown={(e) => handleKeydown(e, () => openFile(item))}
                     onclick={() => openFile(item)}>
                    {item.name}
                </div>
            </div>
        {/if}
    </div>
{/each}
