import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/500.css";
import { invoke } from "@tauri-apps/api/core";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { listen, emit } from "@tauri-apps/api/event";
import { initPanelView } from "./panel-view";

// Abgelöstes Panel-Fenster: liest den aktuellen Entwurf einmal ein und folgt
// danach denselben `panel-update`-Events wie das angedockte Panel.
const project = new URLSearchParams(location.search).get("project")!;
const win = getCurrentWebviewWindow();

const view = initPanelView({
  content: document.getElementById("panel-content")!,
  copyBtn: document.getElementById("panel-copy")!,
  modeBtn: document.getElementById("panel-mode")!,
  titleEl: document.querySelector(".panel-title") as HTMLElement,
  editBtn: document.getElementById("panel-title-edit")!,
  editContentBtn: document.getElementById("panel-content-edit")!,
  langSelect: document.getElementById("panel-lang") as HTMLSelectElement,
  defaultLang: await invoke<string>("spellcheck_lang"),
  onCommit: (text) => invoke("panel_set", { project, text }),
});

view.set(await invoke<string>("panel_read", { project }));

await listen<string>("panel-update", (e) => view.set(e.payload));

// Archivieren: wie im angedockten Panel — Ordner nehmen oder per Dialog wählen.
const archiveBtn = document.getElementById("panel-archive")!;
function flashBtn(btn: HTMLElement, cls: string) {
  btn.classList.add(cls);
  setTimeout(() => btn.classList.remove(cls), 1400);
}
archiveBtn.addEventListener("click", async () => {
  try {
    const configured = await invoke<string | null>("panel_archive_dir_cmd", {
      project,
    });
    let dir: string | undefined;
    if (!configured) {
      const { open } = await import("@tauri-apps/plugin-dialog");
      const chosen = await open({ directory: true, title: "Archiv-Ordner wählen" });
      if (!chosen) return;
      dir = chosen as string;
    }
    const path = await invoke<string>("panel_archive_cmd", { project, dir });
    flashBtn(archiveBtn, "copied");
    invoke("reveal_path_cmd", { path });
  } catch {
    flashBtn(archiveBtn, "error");
  }
});

// „Andocken": angedocktes Panel wieder einblenden, dann dieses Fenster schließen.
document.getElementById("panel-dock")!.addEventListener("click", async () => {
  await emit("panel-attached");
  win.close();
});

// „Schließen": Fenster zu, ohne wieder anzudocken (Panel bleibt aus, bis ein
// neuer Entwurf kommt).
document.getElementById("panel-close")!.addEventListener("click", () => win.close());
