<script lang="ts">
  import { onMount } from "svelte";
  import { api } from "./api.js";
  import { me, toastErr, toastOk } from "./stores.js";
  import { treeVersion, bumpTree, currentNode, selectedFilePath, clearSelectedFile, bumpFiles } from "./browser.js";
  import type { NodeChild } from "./types.js";
  import TreeNode from "./TreeNode.svelte";
  import NodeDetailPanel from "./NodeDetailPanel.svelte";
  import FileEditor from "./FileEditor.svelte";
  import Modal from "./Modal.svelte";

  let roots = $state<NodeChild[] | null>(null);
  let treeError = $state<string | null>(null);
  let showCreateRoot = $state(false);
  let newName = $state("");
  let newKind = $state<"FOLDER" | "PROJECT">("FOLDER");
  let newDesc = $state("");

  async function loadRoots(): Promise<void> {
    try {
      const r = await api<{ nodes: NodeChild[] }>("/database/api/nodes");
      roots = r.nodes;
      treeError = null;
    } catch (e) {
      treeError = e instanceof Error ? e.message : String(e);
    }
  }

  onMount(loadRoots);
  $effect(() => {
    void $treeVersion;
    void loadRoots();
  });

  async function createRoot(): Promise<void> {
    const name = newName.trim();
    if (name === "") return;
    try {
      await api("/database/api/nodes", {
        method: "POST",
        body: {
          parentId: null,
          kind: newKind,
          name,
          ...(newDesc.trim() !== "" ? { description: newDesc.trim() } : {}),
        },
      });
      toastOk("已创建");
      showCreateRoot = false;
      newName = ""; newKind = "FOLDER"; newDesc = "";
      bumpTree();
    } catch (e) {
      toastErr(e instanceof Error ? e.message : String(e));
    }
  }

  async function logout(): Promise<void> {
    try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch { /* ignore */ }
    me.set(null);
  }

  const initial = $derived(($me?.userId ?? "U").slice(0, 1).toUpperCase());
</script>

<div class="flex h-full">
  <!-- 侧栏 -->
  <aside class="flex w-[300px] shrink-0 flex-col border-r border-line-soft bg-sidebar">
    <div class="flex items-center justify-between border-b border-line-soft px-4 py-3.5">
      <span class="text-[15px] font-semibold text-ink">文件库</span>
      {#if $me?.isWebsiteAdmin}
        <button class="rounded-lg border border-line bg-panel px-2.5 py-1 text-[11.5px] font-medium text-ink transition hover:bg-hover" onclick={() => (showCreateRoot = true)}>
          + 根目录
        </button>
      {/if}
    </div>

    <div class="flex-1 overflow-y-auto px-2 py-2 text-[13px]">
      {#if roots === null}
        <div class="px-3 py-6 text-center text-xs text-ink-3">加载中…</div>
      {:else if treeError}
        <div class="px-3 py-6 text-center text-xs text-danger">{treeError}</div>
      {:else if roots.length === 0}
        <div class="px-3 py-6 text-center text-xs text-ink-3">
          {$me?.isWebsiteAdmin ? "空文件库 · 点上方「+ 根目录」开始" : "文件库为空,请联系管理员创建根目录"}
        </div>
      {:else}
        {#each roots as node (node.id)}
          <TreeNode {node} depth={0} />
        {/each}
      {/if}
    </div>

    <div class="flex items-center gap-2 border-t border-line-soft px-4 py-3 text-[12.5px]">
      <div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-accent text-[11px] font-semibold text-white">{initial}</div>
      <span class="flex-1 truncate text-ink">{$me?.userId ?? ""}</span>
      <button class="rounded-lg border border-line-soft px-2.5 py-1 text-[11.5px] text-ink-3 transition hover:bg-hover hover:text-ink" onclick={logout} title="退出登录">退出</button>
    </div>
  </aside>

  <!-- 主区 -->
  <main class="flex-1 overflow-y-auto">
    <NodeDetailPanel />
  </main>

  <!-- 右侧:文件预览/编辑栏(选中文件时出现) -->
  {#if $selectedFilePath && $currentNode?.kind === "PROJECT"}
    <section class="flex w-[46%] min-w-[420px] shrink-0 flex-col overflow-y-auto border-l border-line-soft bg-bg p-4">
      <FileEditor
        projectId={$currentNode.id}
        path={$selectedFilePath}
        role={$currentNode.role}
        onchanged={bumpFiles}
        onclose={clearSelectedFile}
      />
    </section>
  {/if}
</div>

{#if showCreateRoot}
  <Modal title="新建根目录" onclose={() => (showCreateRoot = false)}>
    <div class="mb-3">
      <label class="mb-1 block text-[11.5px] text-ink-3" for="root-name">名称</label>
      <input id="root-name" class="w-full rounded-lg border border-line bg-panel px-3 py-2 text-[13px] outline-none focus:border-accent" bind:value={newName} placeholder="例如:物理教研" />
    </div>
    <div class="mb-3">
      <label class="mb-1 block text-[11.5px] text-ink-3" for="root-kind">类型</label>
      <select id="root-kind" class="w-full rounded-lg border border-line bg-panel px-3 py-2 text-[13px] outline-none focus:border-accent" bind:value={newKind}>
        <option value="FOLDER">文件夹</option>
        <option value="PROJECT">项目(课程资源库)</option>
      </select>
    </div>
    <div class="mb-3">
      <label class="mb-1 block text-[11.5px] text-ink-3" for="root-desc">简介(可选)</label>
      <textarea id="root-desc" rows="3" class="w-full rounded-lg border border-line bg-panel px-3 py-2 font-mono text-xs outline-none focus:border-accent" bind:value={newDesc} placeholder="简要说明用途…"></textarea>
    </div>
    <div class="mt-4 flex justify-end gap-2">
      <button class="rounded-lg border border-line bg-panel px-3.5 py-1.5 text-[12.5px] font-medium text-ink transition hover:bg-hover" onclick={() => (showCreateRoot = false)}>取消</button>
      <button class="rounded-lg bg-accent px-3.5 py-1.5 text-[12.5px] font-medium text-white transition hover:bg-accent-hover" onclick={createRoot}>创建</button>
    </div>
  </Modal>
{/if}
