<script lang="ts">
    import {
        CloseOutline,
        MinusOutline,
        WindowRestoreSolid,
        CaretDownOutline,
        PlusOutline,
        FilePdfSolid,
        ArrowsRepeatOutline,
        DownloadOutline,
        ArrowLeftOutline,
        ArrowRightOutline,
        AngleDownOutline
    } from "flowbite-svelte-icons";
    import { getCurrentWindow } from "@tauri-apps/api/window";
    import { homeDir } from "@tauri-apps/api/path";
    import type FileViewState from "../models/FileViewState.svelte";

    const appWindow = getCurrentWindow();
    let home = "";
    getHome();

    let {
        fStates,
        fState,
        selectTab,
        closeTab,
        openTab: newFile,
    }: {
        fStates: FileViewState[];
        fState: FileViewState | undefined;
        selectTab: (arg0: FileViewState) => void;
        closeTab: (arg0: FileViewState) => void;
        openTab: () => void;
    } = $props();

    let dropdownVisible = $state(false);
    let dropdownEl: HTMLElement;
    let historyVisible = $state(false);
    let historyEl: HTMLElement;

    async function getHome() {
        home = await homeDir();
    }

    function formatFileName(name: string) {
        if (name.length < 100) {
            return name;
        }
        return name.substring(0, 17) + "...";
    }

    function formatFilePath(path: string) {
        // Replace home directory with ~

        if (path.startsWith(home)) {
            path = path.replace(home, "~");
        }

        if (path.length < 40) {
            return path;
        }

        const parts = path.split(/[/\\]/);
        const first = parts[0];
        const last = parts[parts.length - 1];
        const middle = parts
            .slice(1, -1)
            .map((part) => part.charAt(0) + "...")
            .join("/");

        return `${first}/${middle}/${last}`;
    }

    function minimize() {
        appWindow.minimize();
    }

    function maximize() {
        appWindow.toggleMaximize();
    }

    function close() {
        appWindow.close();
    }

    function toggleDropdown() {
        dropdownVisible = !dropdownVisible;
    }

    function toggleHistoryDropdown() {
        historyVisible = !historyVisible;
    }

    function handleFocusOutHistory(e: FocusEvent) {
        const dropdown = historyEl;
        if (!dropdown) return;

        const relatedTarget = e.relatedTarget as HTMLElement;
        if (!dropdown.contains(relatedTarget)) {
            historyVisible = false;
        }
    }

    function handleFocusOut(e: FocusEvent) {
        const dropdown = dropdownEl;
        if (!dropdown) return;

        const relatedTarget = e.relatedTarget as HTMLElement;
        if (!dropdown.contains(relatedTarget)) {
            dropdownVisible = false;
        }
    }



    function handleSelectTab(state: FileViewState) {
        selectTab(state);
        dropdownVisible = false;
    }

    function handleNewFile() {
        newFile();
        dropdownVisible = false;
    }

    function handleCloseTab(state: FileViewState) {
        closeTab(state);
    }
</script>

<div data-tauri-drag-region class="titlebar">
    <div class="m-[2px]">
        <img
            src="/pdf-forge-logo-30x30.png"
            class="logo forge"
            alt="PDF Forge Logo"
        />
    </div>
    <div class="mx-4"></div>
    <div class="flex flex-row">
        <button
                onclick={() => fState?.back()}
                class="nav-button"
                id="titlebar-back"
                class:possible={fState?.canBack}
        >
            <ArrowLeftOutline/>
        </button>
        <button
                onfocusout={handleFocusOutHistory}
                onclick={() => toggleHistoryDropdown()}
                class="nav-button possible"
                id="titlebar-forward"
        >
            <AngleDownOutline/>
        </button>
        {#if historyVisible && fState}
            <div class="dropdown-menu" bind:this={historyEl}>
                {#each fState.pathHistory.history as path, index}
                    <button class="dropdown-item new-tab active:bg-forge-sec" class:active={fState.pathHistory.currentIndex === index} onclick={() => fState.jump(index)}>
                        {path.join("/")}
                    </button>
                {/each}
            </div>
        {/if}
        <button
                onclick={() => fState?.forward()}
                class="nav-button"
                id="titlebar-forward"
                class:possible={fState?.canForward}
        >
            <ArrowRightOutline/>
        </button>
    </div>
    <div class="file-selector" onfocusout={handleFocusOut}>
        <button class="file-dropdown-button" onclick={toggleDropdown}>
            <FilePdfSolid size="sm" />
            <span class="px-2"
                >{fState
                    ? formatFileName(fState.file.name)
                    : "Select File"}</span
            >
            <CaretDownOutline class="ml-1 text-forge-text_sec" size="sm" />
        </button>

        {#if dropdownVisible}
            <div class="dropdown-menu" bind:this={dropdownEl}>
                <button class="dropdown-item new-tab" onclick={handleNewFile}>
                    <PlusOutline size="sm" />
                    <p class="ml-1">New File...</p>
                </button>
                <div class="divider"></div>
                <div class="w-full text-forge-text_sec text-xs ml-3 mt-1 mb-1">
                    <p>Open Files</p>
                </div>
                <div class="divider"></div>
                {#each fStates as state}
                    <div
                        class="dropdown-item justify-between"
                        class:active={state.file.id === fState?.file.id}
                    >
                        <button
                            class="select-button text-left"
                            onclick={() => handleSelectTab(state)}
                        >
                            <FilePdfSolid size="md" />
                            <div class="flex flex-col">
                                <p class="ml-1">
                                    {formatFileName(state.file.name)}
                                </p>
                                <p class="path-text">
                                    {formatFilePath(state.file.path)}
                                </p>
                            </div>
                        </button>
                        <button
                            class="close-button"
                            onclick={() => handleCloseTab(state)}
                        >
                            <CloseOutline size="xs" />
                        </button>
                    </div>
                {/each}
            </div>
        {/if}
    </div>

    <div class="flex flex-row">
        <button
                onclick={() => fState?.reload()}
                class="titlebar-button"
                id="titlebar-reload"
        >
            <ArrowsRepeatOutline/>
        </button>
        <button
                onclick={() => fState?.save()}
                class="titlebar-button"
                id="titlebar-save"
        >
            <DownloadOutline/>
        </button>
    </div>


    <div class="titlebar-button-group">
        <button
            onclick={minimize}
            class="titlebar-button"
            id="titlebar-minimize"
        >
            <MinusOutline />
        </button>
        <button
            onclick={maximize}
            class="titlebar-button"
            id="titlebar-maximize"
        >
            <WindowRestoreSolid />
        </button>
        <button onclick={close} class="titlebar-button" id="titlebar-close">
            <CloseOutline></CloseOutline>
        </button>
    </div>
</div>

<style lang="postcss">

    .nav-button.possible {
        @apply hover:bg-forge-acc text-forge-text
    }

    .nav-button {
        @apply text-forge-text_sec rounded ;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        width: 30px;
        height: 30px;
        user-select: none;
        -webkit-user-select: none;
    }

    .titlebar {
        @apply border border-forge-bound;
        height: 30px;
        user-select: none;
        display: flex;
        flex-direction: row;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
    }

    .titlebar-button-group {
        position: fixed;
        right: 0;
        display: flex;
        justify-content: flex-end;
    }

    .titlebar-button {
        @apply text-forge-text hover:bg-forge-acc rounded;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        width: 30px;
        height: 30px;
        user-select: none;
        -webkit-user-select: none;
    }

    .file-selector {
        @apply relative ml-4;
    }

    .file-dropdown-button {
        @apply flex flex-row items-center px-2 py-1 text-xs text-forge-text rounded hover:bg-forge-acc;
        height: 26px;
        margin-top: 2px;
    }

    .dropdown-menu {
        @apply absolute top-full left-0 mt-1 bg-forge-prim border border-forge-sec rounded-md border;
        min-width: 200px;
    }

    .dropdown-item {
        @apply flex flex-row items-center w-full text-xs text-forge-text hover:bg-forge-acc;
    }

    .dropdown-item.active {
        @apply bg-forge-active  hover:bg-forge-acc;
    }

    .close-button {
        @apply ml-2 p-1 rounded hover:bg-forge-active;
        opacity: 0;
    }

    .dropdown-item:hover .close-button {
        opacity: 1;
    }

    .new-tab {
        @apply border-t border-forge-bound px-3 py-3;
    }

    .select-button {
        @apply m-0 px-2 py-1 flex flex-row;
    }

    .path-text {
        @apply text-forge-text_sec ml-2 mt-1;
        max-width: 100%;
        font-size: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .divider {
        @apply h-[1px] bg-forge-sec w-full;
    }
</style>
