import React, { memo, useState, useCallback, useEffect } from 'react';
import { StyleSheet, View, Text, ScrollView } from 'react-native';
import { useShiki } from './SyntaxContext.js';

var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
function _log(...args) {
  console.log("[SyntaxHighlighter]", ...args);
}
const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  line: {
    flexDirection: "row",
    flexWrap: "wrap"
  }
});
const SyntaxHighlighter = memo(({ code, language, theme, fontSize = 14 }) => {
  const { highlighter, isReady } = useShiki();
  const [tokens, setTokens] = useState([]);
  const [error, setError] = useState(null);
  const highlight = useCallback(() => __async(void 0, null, function* () {
    var _a, _b, _c, _d;
    if (!highlighter || !isReady) {
      _log("Highlighter not ready:", { highlighter: !!highlighter, isReady });
      return;
    }
    try {
      const loadedLangs = highlighter.getLoadedLanguages();
      _log("Available languages:", loadedLangs);
      const normalizedLang = (language == null ? void 0 : language.toLowerCase()) || "text";
      _log("Requested language:", normalizedLang);
      const langToUse = loadedLangs.includes(normalizedLang) ? normalizedLang : "text";
      _log("Using language:", langToUse);
      const loadedThemes = highlighter.getLoadedThemes();
      if (typeof theme === "string" && !loadedThemes.includes(theme)) {
        throw new Error(`Theme ${theme} not loaded. Available themes: ${loadedThemes.join(", ")}`);
      }
      const currentTheme = highlighter.getTheme(theme || "default");
      _log("Theme details:", {
        name: currentTheme.name,
        type: currentTheme.type,
        tokenColors: (_a = currentTheme.tokenColors) == null ? void 0 : _a.length,
        settings: (_b = currentTheme.settings) == null ? void 0 : _b.length,
        firstTokenColor: (_c = currentTheme.tokenColors) == null ? void 0 : _c[0]
      });
      const results = highlighter.codeToTokens(code.trim(), {
        lang: langToUse,
        theme: theme || "default",
        includeExplanation: true
      });
      _log("Tokenization results:", {
        lineCount: results.tokens.length,
        totalTokens: results.tokens.flat().length,
        firstLine: (_d = results.tokens[0]) == null ? void 0 : _d.map((t) => {
          var _a2, _b2;
          return {
            content: t.content,
            color: t.color,
            fontStyle: t.fontStyle,
            scopes: (_b2 = (_a2 = t.explanation) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.scopes.map((s) => {
              var _a3;
              return {
                scope: s.scopeName,
                matches: (_a3 = s.themeMatches) == null ? void 0 : _a3.map((m) => ({
                  scope: m.scope,
                  settings: m.settings
                }))
              };
            })
          };
        }),
        uniqueColors: [...new Set(results.tokens.flat().map((t) => t.color))]
      });
      setTokens(results.tokens);
      setError(null);
    } catch (err) {
      console.error("Highlighting error:", err);
      _log("Highlighting failed:", {
        error: err instanceof Error ? err.message : "Unknown error",
        code: `${code.substring(0, 100)}...`
      });
      setError(err instanceof Error ? err.message : "Failed to highlight code");
    }
  }), [code, language, theme, highlighter, isReady]);
  useEffect(() => {
    highlight();
  }, [highlight]);
  useEffect(() => {
    var _a;
    if (tokens.length > 0) {
      _log("Token analysis:", {
        lineCount: tokens.length,
        sample: (_a = tokens[0]) == null ? void 0 : _a.slice(0, 2),
        colors: [...new Set(tokens.flat().map((t) => t.color))]
      });
    }
  }, [tokens]);
  if (!isReady) {
    return /* @__PURE__ */ React.createElement(View, { style: styles.container }, /* @__PURE__ */ React.createElement(Text, { style: { fontSize } }, code));
  }
  if (error) {
    return /* @__PURE__ */ React.createElement(View, { style: styles.container }, /* @__PURE__ */ React.createElement(Text, { style: { color: "red" } }, error), /* @__PURE__ */ React.createElement(Text, { style: { fontSize } }, code));
  }
  return /* @__PURE__ */ React.createElement(ScrollView, { horizontal: true, style: styles.container }, /* @__PURE__ */ React.createElement(View, null, tokens.map((line, i) => /* @__PURE__ */ React.createElement(View, { key: i, style: styles.line }, line.map((token, j) => /* @__PURE__ */ React.createElement(
    Text,
    {
      key: `${i}-${j}`,
      style: __spreadValues(__spreadValues(__spreadValues({
        color: token.color,
        fontSize
      }, token.fontStyle && token.fontStyle & 1 && { fontStyle: "italic" }), token.fontStyle && token.fontStyle & 2 && { fontWeight: "bold" }), token.bgColor && { backgroundColor: token.bgColor })
    },
    token.content
  ))))));
});

export { SyntaxHighlighter };
//# sourceMappingURL=SyntaxHighlighter.js.map
