import { EditorView } from "@codemirror/view";
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
import { tags as t } from "@lezer/highlight";

// CSS variables are defined in static/css/tokens.css (light) and the
// `prefers-color-scheme: dark` block. Both themes route through the
// same --cm-* variable names; the OS toggle swaps the underlying values.
//
// Two named themes so we can also force-pick light/dark in tests if needed.

const baseRules = {
  "&": {
    backgroundColor: "var(--cm-bg)",
    color: "var(--cm-fg)",
    fontFamily: "var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)",
    fontSize: "14px",
  },
  ".cm-content": { caretColor: "var(--cm-fg)", padding: "8px" },
  ".cm-cursor": { borderLeftColor: "var(--cm-fg)" },
  "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection": {
    backgroundColor: "var(--cm-selection)",
  },
  ".cm-gutters": {
    backgroundColor: "var(--cm-bg)",
    color: "var(--fg-muted, #888)",
    border: "none",
  },
  ".cm-tooltip": {
    backgroundColor: "var(--cm-bg)",
    border: "1px solid var(--border-strong, #444)",
    color: "var(--cm-fg)",
  },
  ".cm-tooltip-autocomplete > ul > li[aria-selected]": {
    backgroundColor: "var(--cm-selection)",
  },
};

export const editorLightTheme = EditorView.theme(baseRules, { dark: false });
export const editorDarkTheme = EditorView.theme(baseRules, { dark: true });

export const editorHighlightStyle = HighlightStyle.define([
  { tag: t.comment, color: "var(--cm-comment)" },
  { tag: t.string, color: "var(--cm-string)" },
  { tag: t.number, color: "var(--cm-number)" },
  { tag: t.keyword, color: "var(--cm-keyword)" },
  { tag: t.variableName, color: "var(--cm-fg)" },
]);

export const editorHighlighting = syntaxHighlighting(editorHighlightStyle);
