import { invoke } from "@tauri-apps/api/core";

const darkTheme: Record<string, string> = {
  "--color-background": "#1e1e1e",
  "--color-foreground": "#cccccc",
  "--color-card": "#252526",
  "--color-card-foreground": "#cccccc",
  "--color-popover": "#252526",
  "--color-popover-foreground": "#cccccc",
  "--color-primary": "#007acc",
  "--color-primary-foreground": "#ffffff",
  "--color-secondary": "#3c3c3c",
  "--color-secondary-foreground": "#cccccc",
  "--color-muted": "#2d2d2d",
  "--color-muted-foreground": "#969696",
  "--color-accent": "#04395e",
  "--color-accent-foreground": "#ffffff",
  "--color-destructive": "#f44747",
  "--color-destructive-foreground": "#ffffff",
  "--color-border": "#3c3c3c",
  "--color-input": "#3c3c3c",
  "--color-ring": "#007acc",
  "--color-sidebar-background": "#252526",
  "--color-sidebar-foreground": "#cccccc",
  "--color-sidebar-accent": "#37373d",
  "--color-sidebar-accent-foreground": "#cccccc",
  "--color-sidebar-border": "#3c3c3c",
};

const lightTheme: Record<string, string> = {
  "--color-background": "#ffffff",
  "--color-foreground": "#333333",
  "--color-card": "#f3f3f3",
  "--color-card-foreground": "#333333",
  "--color-popover": "#f3f3f3",
  "--color-popover-foreground": "#333333",
  "--color-primary": "#007acc",
  "--color-primary-foreground": "#ffffff",
  "--color-secondary": "#e0e0e0",
  "--color-secondary-foreground": "#333333",
  "--color-muted": "#f0f0f0",
  "--color-muted-foreground": "#717171",
  "--color-accent": "#c8ddf1",
  "--color-accent-foreground": "#333333",
  "--color-destructive": "#d32f2f",
  "--color-destructive-foreground": "#ffffff",
  "--color-border": "#d4d4d4",
  "--color-input": "#d4d4d4",
  "--color-ring": "#007acc",
  "--color-sidebar-background": "#f3f3f3",
  "--color-sidebar-foreground": "#333333",
  "--color-sidebar-accent": "#e8e8e8",
  "--color-sidebar-accent-foreground": "#333333",
  "--color-sidebar-border": "#d4d4d4",
};

export function applyTheme(theme: "dark" | "light") {
  const vars = theme === "dark" ? darkTheme : lightTheme;
  const root = document.documentElement;
  for (const [key, value] of Object.entries(vars)) {
    root.style.setProperty(key, value);
  }
}

export async function loadCustomCSS(path: string | null) {
  const existing = document.getElementById("custom-theme-css");
  if (existing) existing.remove();

  if (!path) return;

  try {
    const css = await invoke<string>("read_file", { path });
    const style = document.createElement("style");
    style.id = "custom-theme-css";
    style.textContent = css;
    document.head.appendChild(style);
  } catch (err) {
    console.error("Failed to load custom CSS:", err);
  }
}
