<script lang="ts">
    import { Separator } from "@components/ui/separator";
    import { manager, OpenEditPage } from "./page.svelte";
    import { File, X } from "lucide-svelte";
    import { onMount } from "svelte";
    import { EditorView } from "@codemirror/view";
    import { basicSetup } from "codemirror";
    import EasyMDE from "easymde";
    import "easymde/dist/easymde.min.css";
    import { json } from "@codemirror/lang-json";
    import { materialDark } from "@ddietr/codemirror-themes/theme/material-dark";
    import FrontmatterEditor from "./FrontmatterEditor.svelte";
    import { slide } from "svelte/transition";
    import { Button } from "@components/ui/button";

    let codemirrorParent: HTMLElement | undefined = $state();
    let easyMdeParent: HTMLElement | undefined = $state();
    let easyMdeWrapper: HTMLElement | undefined = $state();

    let easyMde: EasyMDE | null = $state(null);
    let view: EditorView | null = $state(null);

    $effect(() => {
        switch (manager.selectedPage?.fileType) {
            case "md":
            case "mdx":
                easyMdeWrapper?.classList.remove("hidden");
                codemirrorParent?.classList.add("hidden");
                break;
            case "json":
                easyMdeWrapper?.classList.add("hidden");
                codemirrorParent?.classList.remove("hidden");
                break;
            default:
                easyMdeWrapper?.classList.add("hidden");
                codemirrorParent?.classList.add("hidden");
        }
    });

    function updatePage(page: OpenEditPage | undefined) {
        if (page) {
            easyMde?.value(page.content || "");
            view?.dispatch({
                changes: { from: 0, to: view.state.doc.length, insert: page.content || "" },
            });
        }
    }

    $effect(() => updatePage(manager.selectedPage));

    onMount(() => {
        view = new EditorView({
            doc: manager.selectedPage?.content || "",
            parent: codemirrorParent,
            extensions: [basicSetup, json(), materialDark],
        });
        easyMde = new EasyMDE({
            element: easyMdeParent,
            spellChecker: false,
            initialValue: manager.selectedPage?.content || "",
        });

        easyMde.codemirror.on("change", () => {
            if (manager.selectedPage?.content !== easyMde?.value()) {
                manager.selectedPage!.dirty = true;
            }

            manager.selectedPage!.content = easyMde?.value() || "";
        });
    });
</script>

<div class="flex flex-col h-full w-full">
    <div class="h-8 flex">
        {#each manager.pages as tab, index}
            {@const isActive = manager.openPageIndex === index}
            <button
                class="flex pl-4 border-r group items-center hover:bg-neutral-800 transition-colors cursor-pointer h-full {isActive
                    ? 'text-primary bg-neutral-900'
                    : 'text-muted-foreground'} {tab.dirty ? 'italic' : ''}"
                onclick={() => (manager.openPageIndex = index)}
            >
                <File class="h-4 w-4 mr-2" />
                {tab.pageTitle}
                <span
                    class="mx-4 hover:bg-neutral-700 transition-all rounded {isActive ? '' : 'opacity-0'} group-hover:opacity-100 cursor-pointer"
                    onclick={(e) => {
                        e.stopPropagation();
                        manager.closePage(index);
                    }}><X /></span
                >
            </button>
        {/each}
    </div>
    <Separator />
    <div class="flex-1 flex flex-col">
        {#if manager.selectedPage}
            <div class="flex items-center justify-end p-2">
                <Button disabled={!(manager.selectedPage?.dirty ?? false)} onclick={() => manager.selectedPage?.save()}>Speichern</Button>
            </div>
            <div class="flex gap-2 items-center">
                {#if manager.selectedPage.path.startsWith("src/content/announcements/")}
                    <div class="border-b flex-1" transition:slide>
                        <FrontmatterEditor />
                    </div>
                {/if}
            </div>
        {/if}
        <div class="flex-1">
            <div bind:this={codemirrorParent} class="hidden h-full"></div>
            <div bind:this={easyMdeWrapper} class="hidden h-full">
                <textarea bind:this={easyMdeParent}></textarea>
            </div>
        </div>
    </div>
</div>
