// Video Concat — app shell: title bar, theme, drag-drop.

import "./styles.css";
import { h } from "./dom";
import { toast } from "./ui";
import { getTools, onFilesDropped } from "./api";
import { buildConcat } from "./views/concat";

async function boot() {
  // ── Theme (system default, persisted toggle) ────────────────────────────
  const saved = localStorage.getItem("theme");
  const prefersDark = matchMedia("(prefers-color-scheme: dark)").matches;
  let theme = saved ?? (prefersDark ? "dark" : "light");
  const applyTheme = () => document.documentElement.setAttribute("data-theme", theme);
  applyTheme();

  // ── Single view: concat ─────────────────────────────────────────────────
  const concat = buildConcat();

  const themeBtn = h("button", { class: "icon-btn", title: "Toggle theme" },
    theme === "dark" ? "☀" : "☾") as HTMLButtonElement;
  themeBtn.addEventListener("click", () => {
    theme = theme === "dark" ? "light" : "dark";
    localStorage.setItem("theme", theme);
    applyTheme();
    themeBtn.textContent = theme === "dark" ? "☀" : "☾";
  });

  const app = document.getElementById("app")!;
  app.append(
    h("div", { class: "titlebar" },
      h("div", { class: "brand" },
        h("div", { class: "logo" }, "🎬"),
        h("span", {}, "Video Concat")),
      h("div", { class: "spacer" }),
      themeBtn,
    ),
    h("div", { class: "content" }, concat.el),
  );

  // ── Drag-and-drop routes to the concat view ─────────────────────────────
  await onFilesDropped((paths) => concat.onDrop(paths));

  // ── ffmpeg health check ─────────────────────────────────────────────────
  try {
    const tools = await getTools();
    if (!tools.ffmpeg) {
      const banner = h("div", { class: "banner", style: "margin:0 22px 12px" },
        "⚠ ffmpeg was not found. Put ffmpeg.exe & ffprobe.exe next to the app or on your PATH.");
      app.querySelector(".content")!.before(banner);
    }
  } catch (e) {
    toast(`Backend not ready: ${e}`, "err");
  }
}

boot();
