import { Tooltip, Button } from './chunk-FKEFVCK4.js';
import { forwardRef, useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useTheme, css } from '@emotion/react';
import { Compartment, EditorState } from '@codemirror/state';
import { highlightSpecialChars, drawSelection, dropCursor, rectangularSelection, crosshairCursor, highlightActiveLine, highlightActiveLineGutter, keymap, EditorView, placeholder, lineNumbers } from '@codemirror/view';
import { indentOnInput, syntaxHighlighting, defaultHighlightStyle, bracketMatching, foldKeymap, foldGutter, HighlightStyle } from '@codemirror/language';
import { history, defaultKeymap, historyKeymap } from '@codemirror/commands';
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
import { lintKeymap } from '@codemirror/lint';
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import { css as css$1 } from '@codemirror/lang-css';
import { html } from '@codemirror/lang-html';
import { json } from '@codemirror/lang-json';
import { tags } from '@lezer/highlight';
import { useI18n } from '@timeui/core';
import { jsxs, jsx } from '@emotion/react/jsx-runtime';

function createCodeEditorTheme(theme, isDark) {
  const editorTheme = EditorView.theme(
    {
      "&": {
        color: theme.colors.text.primary,
        backgroundColor: theme.colors.bg.surface,
        fontFamily: theme.typography.fontFamily.mono,
        height: "100%"
      },
      ".cm-content": {
        caretColor: theme.colors.primary[500],
        padding: "8px 0"
      },
      ".cm-cursor, .cm-dropCursor": {
        borderLeftColor: theme.colors.primary[500]
      },
      "&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
        backgroundColor: isDark ? `${theme.colors.primary[200]}44` : `${theme.colors.primary[200]}88`
      },
      ".cm-panels": {
        backgroundColor: theme.colors.bg.muted,
        color: theme.colors.text.primary
      },
      ".cm-panels.cm-panels-top": {
        borderBottom: `1px solid ${theme.colors.border.subtle}`
      },
      ".cm-panels.cm-panels-bottom": {
        borderTop: `1px solid ${theme.colors.border.subtle}`
      },
      ".cm-searchMatch": {
        backgroundColor: `${theme.colors.primary[200]}66`,
        outline: `1px solid ${theme.colors.primary[200]}`
      },
      ".cm-searchMatch.cm-searchMatch-selected": {
        backgroundColor: `${theme.colors.primary[200]}88`
      },
      ".cm-activeLine": {
        backgroundColor: isDark ? `${theme.colors.bg.muted}88` : `${theme.colors.bg.sunken}88`
      },
      ".cm-selectionMatch": {
        backgroundColor: `${theme.colors.primary[100]}88`
      },
      "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": {
        backgroundColor: `${theme.colors.primary[200]}66`
      },
      ".cm-gutters": {
        backgroundColor: theme.colors.bg.muted,
        color: theme.colors.text.disabled,
        border: "none",
        borderRight: `1px solid ${theme.colors.border.subtle}`
      },
      ".cm-activeLineGutter": {
        backgroundColor: isDark ? `${theme.colors.bg.sunken}88` : `${theme.colors.bg.canvas}88`
      },
      ".cm-foldPlaceholder": {
        backgroundColor: "transparent",
        border: "none",
        color: theme.colors.text.muted
      },
      ".cm-tooltip": {
        border: `1px solid ${theme.colors.border.default}`,
        backgroundColor: theme.colors.bg.surface,
        boxShadow: theme.shadows.md,
        borderRadius: theme.componentRadius.sm
      },
      ".cm-tooltip .cm-tooltip-arrow:before": {
        borderTopColor: "transparent",
        borderBottomColor: "transparent"
      },
      ".cm-tooltip .cm-tooltip-arrow:after": {
        borderTopColor: theme.colors.bg.surface,
        borderBottomColor: theme.colors.bg.surface
      },
      ".cm-tooltip-autocomplete": {
        "& > ul > li[aria-selected]": {
          backgroundColor: isDark ? theme.colors.primary[600] : theme.colors.primary[100],
          color: isDark ? theme.colors.primary[100] : theme.colors.primary[600]
        }
      }
    },
    { dark: isDark }
  );
  const highlightStyle = HighlightStyle.define([
    { tag: tags.comment, color: theme.colors.text.disabled, fontStyle: "italic" },
    { tag: tags.lineComment, color: theme.colors.text.disabled, fontStyle: "italic" },
    { tag: tags.blockComment, color: theme.colors.text.disabled, fontStyle: "italic" },
    { tag: tags.docComment, color: theme.colors.text.disabled, fontStyle: "italic" },
    {
      tag: tags.keyword,
      color: isDark ? theme.colors.primary[200] : theme.colors.primary[600]
    },
    {
      tag: [tags.deleted, tags.character, tags.propertyName, tags.macroName],
      color: isDark ? theme.colors.primary[200] : theme.colors.primary[600]
    },
    {
      tag: [tags.function(tags.variableName), tags.definition(tags.variableName), tags.labelName],
      color: isDark ? theme.colors.primary[200] : theme.colors.primary[500]
    },
    {
      tag: [tags.color, tags.constant(tags.name), tags.standard(tags.name)],
      color: isDark ? theme.colors.primary[200] : theme.colors.primary[600]
    },
    {
      tag: [tags.definition(tags.name), tags.separator],
      color: theme.colors.text.primary
    },
    {
      // Type names, class names — use cyan-ish tone
      tag: [
        tags.typeName,
        tags.className,
        tags.changed,
        tags.annotation,
        tags.modifier,
        tags.self,
        tags.namespace
      ],
      color: isDark ? "#79b8ff" : "#0086b3"
    },
    {
      tag: [tags.number],
      // orange for numbers — use warning color if available
      color: isDark ? theme.colors.warning[200] : theme.colors.warning[600]
    },
    {
      tag: [
        tags.operator,
        tags.operatorKeyword,
        tags.escape,
        tags.regexp,
        tags.link,
        tags.special(tags.string)
      ],
      color: theme.colors.text.secondary
    },
    {
      tag: [tags.url],
      color: theme.colors.text.link
    },
    {
      tag: [tags.meta],
      color: theme.colors.text.muted
    },
    {
      tag: tags.strong,
      fontWeight: "bold"
    },
    {
      tag: tags.emphasis,
      fontStyle: "italic"
    },
    {
      tag: tags.strikethrough,
      textDecoration: "line-through"
    },
    {
      tag: tags.link,
      color: theme.colors.text.link,
      textDecoration: "underline"
    },
    {
      tag: tags.heading,
      fontWeight: "bold",
      color: theme.colors.text.primary
    },
    {
      tag: [tags.atom, tags.bool, tags.special(tags.variableName)],
      color: isDark ? theme.colors.primary[200] : theme.colors.primary[600]
    },
    {
      // green tones for strings
      tag: [tags.processingInstruction, tags.string, tags.inserted],
      color: isDark ? "#85e89d" : "#22863a"
    },
    {
      tag: tags.invalid,
      color: isDark ? theme.colors.danger[200] : theme.colors.danger[600]
    }
  ]);
  return [editorTheme, syntaxHighlighting(highlightStyle)];
}
var FALLBACK_LABELS = {
  toolbarLabel: "Code editor toolbar",
  copy: "Copy",
  copied: "Copied!",
  lineWrap: "Toggle line wrap",
  lineNumbers: "Toggle line numbers",
  fullscreen: "Fullscreen",
  exitFullscreen: "Exit fullscreen",
  language: "Language",
  aiSuggest: "AI suggestions"
};
var LANGUAGE_OPTIONS = [
  { value: "javascript", label: "JavaScript" },
  { value: "typescript", label: "TypeScript" },
  { value: "python", label: "Python" },
  { value: "css", label: "CSS" },
  { value: "html", label: "HTML" },
  { value: "json", label: "JSON" }
];
function Icon({ size = 16, children }) {
  return /* @__PURE__ */ jsx(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: 1.8,
      strokeLinecap: "round",
      strokeLinejoin: "round",
      "aria-hidden": true,
      focusable: false,
      children
    }
  );
}
var CopyIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("rect", { x: "9", y: "9", width: "13", height: "13", rx: "2", ry: "2" }),
  /* @__PURE__ */ jsx("path", { d: "M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" })
] });
var CheckIcon = ({ size }) => /* @__PURE__ */ jsx(Icon, { size, children: /* @__PURE__ */ jsx("polyline", { points: "20 6 9 17 4 12" }) });
var WrapTextIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("path", { d: "M4 6h16" }),
  /* @__PURE__ */ jsx("path", { d: "M4 12h10a3 3 0 0 1 0 6H4" }),
  /* @__PURE__ */ jsx("polyline", { points: "12 15 9 18 12 21" })
] });
var HashIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("line", { x1: "4", y1: "9", x2: "20", y2: "9" }),
  /* @__PURE__ */ jsx("line", { x1: "4", y1: "15", x2: "20", y2: "15" }),
  /* @__PURE__ */ jsx("line", { x1: "10", y1: "3", x2: "8", y2: "21" }),
  /* @__PURE__ */ jsx("line", { x1: "16", y1: "3", x2: "14", y2: "21" })
] });
var MaximizeIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("path", { d: "M8 3H5a2 2 0 0 0-2 2v3" }),
  /* @__PURE__ */ jsx("path", { d: "M21 8V5a2 2 0 0 0-2-2h-3" }),
  /* @__PURE__ */ jsx("path", { d: "M3 16v3a2 2 0 0 0 2 2h3" }),
  /* @__PURE__ */ jsx("path", { d: "M16 21h3a2 2 0 0 0 2-2v-3" })
] });
var MinimizeIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("path", { d: "M8 3v3a2 2 0 0 1-2 2H3" }),
  /* @__PURE__ */ jsx("path", { d: "M21 8h-3a2 2 0 0 1-2-2V3" }),
  /* @__PURE__ */ jsx("path", { d: "M3 16h3a2 2 0 0 1 2 2v3" }),
  /* @__PURE__ */ jsx("path", { d: "M16 21v-3a2 2 0 0 1 2-2h3" })
] });
var SparklesIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("path", { d: "M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5Z" }),
  /* @__PURE__ */ jsx("path", { d: "M19 13l.75 2.25L22 16l-2.25.75L19 19l-.75-2.25L16 16l2.25-.75Z" }),
  /* @__PURE__ */ jsx("path", { d: "M5 17l.5 1.5L7 19l-1.5.5L5 21l-.5-1.5L3 19l1.5-.5Z" })
] });
function CodeEditorToolbar({
  getValue,
  language,
  onLanguageChange,
  lineWrap,
  onLineWrapToggle,
  showLineNumbers,
  onLineNumbersToggle,
  isFullscreen,
  onFullscreenToggle,
  config,
  labelOverrides,
  hasAI,
  onAISuggest,
  "aria-label": ariaLabelProp
}) {
  const theme = useTheme();
  const i18n = useI18n();
  const i18nLabels = i18n.codeEditor ?? FALLBACK_LABELS;
  const labels = { ...i18nLabels, ...labelOverrides };
  const resolvedAriaLabel = ariaLabelProp ?? labels.toolbarLabel;
  const [copied, setCopied] = useState(false);
  const handleCopy = useCallback(() => {
    if (typeof navigator === "undefined" || !navigator.clipboard) return;
    navigator.clipboard.writeText(getValue()).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2e3);
    }).catch(() => {
    });
  }, [getValue]);
  const showCopy = config.showCopy !== false;
  const showLineWrap = config.showLineWrap !== false;
  const showLineNums = config.showLineNumbers !== false;
  const showLangSelect = config.showLanguageSelect !== false;
  const showFullscreen = config.showFullscreen !== false;
  const containerCss = css`
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 4px;
    padding: 6px 10px;
    border-bottom: ${theme.borders.width.thin} solid ${theme.colors.border.subtle};
    color: ${theme.colors.text.primary};
    background-color: ${theme.colors.bg.muted};
    border-radius: ${theme.componentRadius.md} ${theme.componentRadius.md} 0 0;
  `;
  const separatorCss = css`
    width: ${theme.borders.width.thin};
    align-self: stretch;
    min-height: 16px;
    margin: 2px 4px;
    background: ${theme.colors.border.subtle};
  `;
  const langSelectCss = css`
    appearance: none;
    -webkit-appearance: none;
    background-color: transparent;
    border: 1px solid ${theme.colors.border.subtle};
    border-radius: ${theme.componentRadius.sm};
    color: ${theme.colors.text.secondary};
    font-family: ${theme.typography.fontFamily.sans};
    font-size: ${theme.typography.fontSize.xs};
    height: 28px;
    padding: 0 24px 0 8px;
    cursor: pointer;
    outline: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%23888' stroke-width='1.5' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 6px center;
    transition: border-color 0.15s ease;

    &:hover {
      border-color: ${theme.colors.border.default};
      color: ${theme.colors.text.primary};
    }

    &:focus {
      border-color: ${theme.colors.primary[500]};
      box-shadow: 0 0 0 2px ${theme.colors.primary[100]};
    }
  `;
  const activeButtonCss = (active) => css`
    ${active ? `
      background-color: ${theme.colors.default[200]};
      color: ${theme.colors.text.primary};
    ` : ""}
  `;
  const spacerCss = css`
    flex: 1;
  `;
  return /* @__PURE__ */ jsxs("div", { role: "toolbar", "aria-label": resolvedAriaLabel, css: containerCss, children: [
    showLangSelect && /* @__PURE__ */ jsx(Tooltip, { content: labels.language, placement: "top", children: /* @__PURE__ */ jsx(
      "select",
      {
        "aria-label": labels.language,
        value: language,
        onChange: (e) => onLanguageChange(e.target.value),
        css: langSelectCss,
        children: LANGUAGE_OPTIONS.map((opt) => /* @__PURE__ */ jsx("option", { value: opt.value, children: opt.label }, opt.value))
      }
    ) }),
    showLangSelect && (showLineWrap || showLineNums || showCopy || showFullscreen || hasAI) && /* @__PURE__ */ jsx("span", { css: separatorCss, "aria-hidden": true }),
    showLineWrap && /* @__PURE__ */ jsx(Tooltip, { content: labels.lineWrap, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.lineWrap,
        "aria-pressed": lineWrap,
        "data-active": lineWrap || void 0,
        onClick: onLineWrapToggle,
        css: activeButtonCss(lineWrap),
        children: /* @__PURE__ */ jsx(WrapTextIcon, { size: 15 })
      }
    ) }),
    showLineNums && /* @__PURE__ */ jsx(Tooltip, { content: labels.lineNumbers, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.lineNumbers,
        "aria-pressed": showLineNumbers,
        "data-active": showLineNumbers || void 0,
        onClick: onLineNumbersToggle,
        css: activeButtonCss(showLineNumbers),
        children: /* @__PURE__ */ jsx(HashIcon, { size: 15 })
      }
    ) }),
    /* @__PURE__ */ jsx("span", { css: spacerCss }),
    showCopy && /* @__PURE__ */ jsx(Tooltip, { content: copied ? labels.copied : labels.copy, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": copied ? labels.copied : labels.copy,
        onClick: handleCopy,
        children: copied ? /* @__PURE__ */ jsx(CheckIcon, { size: 15 }) : /* @__PURE__ */ jsx(CopyIcon, { size: 15 })
      }
    ) }),
    hasAI && /* @__PURE__ */ jsx(Tooltip, { content: labels.aiSuggest, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.aiSuggest,
        onClick: onAISuggest,
        children: /* @__PURE__ */ jsx(SparklesIcon, { size: 15 })
      }
    ) }),
    showFullscreen && /* @__PURE__ */ jsx(Tooltip, { content: isFullscreen ? labels.exitFullscreen : labels.fullscreen, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": isFullscreen ? labels.exitFullscreen : labels.fullscreen,
        "aria-pressed": isFullscreen,
        onClick: onFullscreenToggle,
        children: isFullscreen ? /* @__PURE__ */ jsx(MinimizeIcon, { size: 15 }) : /* @__PURE__ */ jsx(MaximizeIcon, { size: 15 })
      }
    ) })
  ] });
}
function getLanguageExtension(language) {
  switch (language) {
    case "javascript":
      return javascript();
    case "typescript":
      return javascript({ typescript: true });
    case "python":
      return python();
    case "css":
      return css$1();
    case "html":
      return html();
    case "json":
      return json();
    default:
      return javascript();
  }
}
function toCssLength(value) {
  if (value === null || value === void 0) return null;
  return typeof value === "number" ? `${value}px` : value;
}
function resolveToolbarConfig(toolbar) {
  if (toolbar === false) return false;
  if (toolbar === true || toolbar === void 0) return {};
  return toolbar;
}
var SIZE_TO_FONT = {
  xs: "11px",
  sm: "12px",
  md: "13px",
  lg: "14px",
  xl: "16px"
};
var SIZE_TO_MIN_HEIGHT = {
  xs: "80px",
  sm: "120px",
  md: "200px",
  lg: "280px",
  xl: "360px"
};
var CodeEditor = forwardRef(function CodeEditor2({
  value,
  defaultValue,
  onChange,
  language: languageProp = "javascript",
  onLanguageChange,
  size = "md",
  variant = "bordered",
  placeholder: placeholder$1,
  isDisabled = false,
  isReadOnly = false,
  isInvalid = false,
  showLineNumbers: showLineNumbersProp = true,
  onShowLineNumbersChange,
  lineWrap: lineWrapProp = false,
  onLineWrapChange,
  toolbar,
  minHeight,
  maxHeight,
  extensions: extraExtensions,
  onAISuggest,
  className,
  "aria-label": ariaLabel,
  "aria-labelledby": ariaLabelledby,
  "aria-describedby": ariaDescribedby
}, ref) {
  const theme = useTheme();
  const isDark = theme.mode === "dark";
  const [language, setLanguageInternal] = useState(languageProp);
  const [lineWrap, setLineWrap] = useState(lineWrapProp);
  const [showLineNumbers, setShowLineNumbers] = useState(showLineNumbersProp);
  const [isFullscreen, setIsFullscreen] = useState(false);
  useEffect(() => {
    setLanguageInternal(languageProp);
  }, [languageProp]);
  useEffect(() => {
    setLineWrap(lineWrapProp);
  }, [lineWrapProp]);
  useEffect(() => {
    setShowLineNumbers(showLineNumbersProp);
  }, [showLineNumbersProp]);
  const setLanguage = useCallback(
    (lang) => {
      setLanguageInternal(lang);
      onLanguageChange?.(lang);
    },
    [onLanguageChange]
  );
  const toggleLineWrap = useCallback(() => {
    setLineWrap((prev) => {
      const next = !prev;
      onLineWrapChange?.(next);
      return next;
    });
  }, [onLineWrapChange]);
  const toggleLineNumbers = useCallback(() => {
    setShowLineNumbers((prev) => {
      const next = !prev;
      onShowLineNumbersChange?.(next);
      return next;
    });
  }, [onShowLineNumbersChange]);
  const getValue = useCallback(
    () => viewRef.current?.state.doc.toString() ?? value ?? defaultValue ?? "",
    [value, defaultValue]
  );
  const languageCompartment = useMemo(() => new Compartment(), []);
  const themeCompartment = useMemo(() => new Compartment(), []);
  const lineWrapCompartment = useMemo(() => new Compartment(), []);
  const lineNumbersCompartment = useMemo(() => new Compartment(), []);
  const readOnlyCompartment = useMemo(() => new Compartment(), []);
  const editorRef = useRef(null);
  const viewRef = useRef(null);
  const onChangeRef = useRef(onChange);
  useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);
  const lastExternalValue = useRef(value);
  const buildExtensions = useCallback(() => {
    const exts = [
      highlightSpecialChars(),
      history(),
      drawSelection(),
      dropCursor(),
      EditorState.allowMultipleSelections.of(true),
      indentOnInput(),
      syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
      bracketMatching(),
      closeBrackets(),
      autocompletion(),
      rectangularSelection(),
      crosshairCursor(),
      highlightActiveLine(),
      highlightActiveLineGutter(),
      highlightSelectionMatches(),
      keymap.of([
        ...closeBracketsKeymap,
        ...defaultKeymap,
        ...searchKeymap,
        ...historyKeymap,
        ...foldKeymap,
        ...completionKeymap,
        ...lintKeymap
      ]),
      foldGutter(),
      EditorView.updateListener.of((update) => {
        if (update.docChanged) {
          const newValue = update.state.doc.toString();
          lastExternalValue.current = newValue;
          onChangeRef.current?.(newValue);
        }
      })
    ];
    if (placeholder$1) {
      exts.push(placeholder(placeholder$1));
    }
    if (extraExtensions && extraExtensions.length > 0) {
      exts.push(...extraExtensions);
    }
    return exts;
  }, [placeholder$1, extraExtensions]);
  useEffect(() => {
    if (!editorRef.current) return;
    const initialDoc = value ?? defaultValue ?? "";
    lastExternalValue.current = initialDoc;
    const startState = EditorState.create({
      doc: initialDoc,
      extensions: [
        ...buildExtensions(),
        lineNumbersCompartment.of(showLineNumbers ? lineNumbers() : []),
        lineWrapCompartment.of(lineWrap ? EditorView.lineWrapping : []),
        readOnlyCompartment.of([
          EditorState.readOnly.of(isReadOnly || isDisabled),
          EditorView.editable.of(!isDisabled)
        ]),
        languageCompartment.of(getLanguageExtension(language)),
        themeCompartment.of(createCodeEditorTheme(theme, isDark))
      ]
    });
    const view = new EditorView({
      state: startState,
      parent: editorRef.current
    });
    viewRef.current = view;
    return () => {
      view.destroy();
      viewRef.current = null;
    };
  }, []);
  useEffect(() => {
    const view = viewRef.current;
    if (!view) return;
    if (value === void 0) return;
    const current = view.state.doc.toString();
    if (current === value) return;
    lastExternalValue.current = value;
    view.dispatch({
      changes: { from: 0, to: view.state.doc.length, insert: value }
    });
  }, [value]);
  useEffect(() => {
    viewRef.current?.dispatch({
      effects: languageCompartment.reconfigure(getLanguageExtension(language))
    });
  }, [language, languageCompartment]);
  useEffect(() => {
    viewRef.current?.dispatch({
      effects: themeCompartment.reconfigure(createCodeEditorTheme(theme, isDark))
    });
  }, [theme, isDark, themeCompartment]);
  useEffect(() => {
    viewRef.current?.dispatch({
      effects: lineWrapCompartment.reconfigure(lineWrap ? EditorView.lineWrapping : [])
    });
  }, [lineWrap, lineWrapCompartment]);
  useEffect(() => {
    viewRef.current?.dispatch({
      effects: lineNumbersCompartment.reconfigure(showLineNumbers ? lineNumbers() : [])
    });
  }, [showLineNumbers, lineNumbersCompartment]);
  useEffect(() => {
    viewRef.current?.dispatch({
      effects: readOnlyCompartment.reconfigure([
        EditorState.readOnly.of(isReadOnly || isDisabled),
        EditorView.editable.of(!isDisabled)
      ])
    });
  }, [isReadOnly, isDisabled, readOnlyCompartment]);
  const toolbarConfig = resolveToolbarConfig(toolbar);
  const hasToolbar = toolbarConfig !== false;
  const handleAISuggest = useCallback(() => {
    if (!onAISuggest || !viewRef.current) return;
    const view = viewRef.current;
    const pos = view.state.selection.main.head;
    const code = view.state.doc.toString();
    onAISuggest(code, pos).then((suggestions) => {
      const best = suggestions[0];
      if (!best) return;
      view.dispatch({
        changes: { from: pos, to: pos, insert: best.text }
      });
    });
  }, [onAISuggest]);
  const minHeightCss = toCssLength(minHeight) ?? SIZE_TO_MIN_HEIGHT[size];
  const maxHeightCss = toCssLength(maxHeight ?? null);
  const fontSizeCss = SIZE_TO_FONT[size];
  const getVariantBorder = (v) => {
    if (v === "flat") return "none";
    if (v === "bordered")
      return `${theme.borders.width.thin} solid ${isInvalid ? theme.colors.danger[500] : theme.colors.border.default}`;
    if (v === "faded")
      return `${theme.borders.width.thin} solid ${isInvalid ? theme.colors.danger[500] : theme.colors.border.subtle}`;
    return "none";
  };
  const getVariantBg = (v) => {
    if (v === "faded") return theme.colors.bg.muted;
    return theme.colors.bg.surface;
  };
  const containerCss = css`
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: 100%;
    min-width: 0;
    font-family: ${theme.typography.fontFamily.mono};
    font-size: ${fontSizeCss};
    line-height: 1.6;
    border-radius: ${theme.componentRadius.md};
    border: ${getVariantBorder(variant)};
    background-color: ${getVariantBg(variant)};
    overflow: hidden;
    transition:
      border-color 0.15s ease,
      box-shadow 0.15s ease;
    ${isDisabled ? "opacity: 0.6; pointer-events: none;" : ""}
    ${isFullscreen ? `
        position: fixed;
        inset: 0;
        z-index: ${theme.zIndex.modal};
        border-radius: 0;
        border: none;
        max-height: 100vh;
      ` : ""}

    &:focus-within {
      ${variant !== "flat" ? `
        border-color: ${isInvalid ? theme.colors.danger[500] : theme.colors.primary[500]};
        box-shadow: 0 0 0 2px ${isInvalid ? theme.colors.danger[100] : theme.colors.primary[100]};
      ` : ""}
    }
  `;
  const editorScrollCss = css`
    flex: 1 1 auto;
    min-height: 0;
    overflow: auto;
    ${maxHeightCss && !isFullscreen ? `max-height: ${maxHeightCss};` : ""}

    /* CodeMirror editor sizing */
    .cm-editor {
      font-size: ${fontSizeCss};
      min-height: ${minHeightCss};
      height: ${isFullscreen ? "100%" : "auto"};
    }

    .cm-scroller {
      overflow: auto;
      font-family: ${theme.typography.fontFamily.mono};
      min-height: ${minHeightCss};
    }
  `;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref,
      role: "group",
      css: containerCss,
      "data-variant": variant,
      "data-size": size,
      "data-fullscreen": isFullscreen || void 0,
      "data-disabled": isDisabled || void 0,
      "data-readonly": isReadOnly || void 0,
      "data-invalid": isInvalid || void 0,
      className,
      "aria-label": ariaLabel,
      "aria-labelledby": ariaLabelledby,
      "aria-describedby": ariaDescribedby,
      children: [
        hasToolbar && /* @__PURE__ */ jsx(
          CodeEditorToolbar,
          {
            getValue,
            language,
            onLanguageChange: setLanguage,
            lineWrap,
            onLineWrapToggle: toggleLineWrap,
            showLineNumbers,
            onLineNumbersToggle: toggleLineNumbers,
            isFullscreen,
            onFullscreenToggle: () => setIsFullscreen((v) => !v),
            config: toolbarConfig,
            hasAI: !!onAISuggest,
            onAISuggest: handleAISuggest
          }
        ),
        /* @__PURE__ */ jsx("div", { ref: editorRef, css: editorScrollCss, "data-slot": "code-editor-mount" })
      ]
    }
  );
});
CodeEditor.displayName = "CodeEditor";

export { CodeEditor };
//# sourceMappingURL=code-editor.js.map
//# sourceMappingURL=code-editor.js.map