import { app, shell } from "electron";
import { mkdirSync, readdirSync, readFileSync, existsSync } from "fs";
import { join } from "path";

const themesDir = join(app.getPath("userData"), "themes");

let activeFile: string | null = null;
let cssKey: string | null = null;

export function getThemesDir() {
  return themesDir;
}

export function getThemeFiles(): string[] {
  try {
    mkdirSync(themesDir, { recursive: true });
    return readdirSync(themesDir).filter(f => f.endsWith(".css")).sort();
  } catch {
    return [];
  }
}

export function getActiveTheme(): string | null {
  return activeFile;
}

// Call at the start of did-finish-load — old page context is gone, key is stale
export function invalidateCssKey() {
  cssKey = null;
}

export async function applyTheme(wc: Electron.WebContents, file: string | null) {
  if (cssKey) {
    try { await wc.removeInsertedCSS(cssKey); } catch {}
    cssKey = null;
  }
  activeFile = file;
  if (!file) return;
  try {
    const css = readFileSync(join(themesDir, file), "utf-8");
    cssKey = await wc.insertCSS(css);
  } catch (err) {
    console.error("[themes] failed to load", file, err);
  }
}

export async function cycleTheme(wc: Electron.WebContents): Promise<string | null> {
  const files = getThemeFiles();
  if (files.length === 0) return null;
  const idx = activeFile ? files.indexOf(activeFile) : -1;
  const next = files[(idx + 1) % files.length];
  await applyTheme(wc, next);
  return next;
}

export async function reloadTheme(wc: Electron.WebContents) {
  const file = activeFile;
  if (!file) return;
  await applyTheme(wc, file);
}

export function openThemesFolder() {
  mkdirSync(themesDir, { recursive: true });
  shell.openPath(themesDir);
}
