import { writable } from "svelte/store";
import type { BreadcrumbEntry, NodeDetail } from "./types.js";

/** 树展开集合 / 当前选中节点 / 面包屑 / 树刷新计数。 */
export const expanded = writable<Set<string>>(new Set());
export const currentNode = writable<NodeDetail | null>(null);
export const breadcrumb = writable<BreadcrumbEntry[]>([]);
export const treeVersion = writable(0);

/** 右侧预览栏:当前选中文件路径(项目内);切换节点时清空。 */
export const selectedFilePath = writable<string | null>(null);
/** 文件列表刷新计数(编辑器保存/删除后 bump,列表随之重载)。 */
export const filesVersion = writable(0);

export function bumpTree(): void {
  treeVersion.update((v) => v + 1);
}

export function bumpFiles(): void {
  filesVersion.update((v) => v + 1);
}

export function clearSelectedFile(): void {
  selectedFilePath.set(null);
}

export function toggleExpanded(id: string): void {
  expanded.update((set) => {
    const next = new Set(set);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    return next;
  });
}
