/**
 * CDN-only highlighter that uses shiki/bundle/web (fewer languages, smaller bundle).
 * The Svelte package uses highlighter.ts which imports from full shiki.
 */
import { createHighlighter } from 'shiki/bundle/web';
let highlighterPromise = null;
const THEMES = ['github-dark', 'github-light', 'dracula', 'nord', 'one-dark-pro', 'vitesse-dark'];
export async function getHighlighter() {
    if (!highlighterPromise) {
        highlighterPromise = createHighlighter({ themes: THEMES, langs: [] });
    }
    return highlighterPromise;
}
export async function highlightCode(code, language, theme = 'github-dark', options = {}) {
    try {
        const highlighter = await getHighlighter();
        const loadedLangs = highlighter.getLoadedLanguages();
        if (!loadedLangs.includes(language)) {
            // Lazy-load the requested language from the web bundle
            try {
                await highlighter.loadLanguage(language);
            }
            catch {
                // Language not available in web bundle, fall back to plaintext
                language = 'javascript';
                if (!loadedLangs.includes('javascript')) {
                    await highlighter.loadLanguage('javascript');
                }
            }
        }
        const html = highlighter.codeToHtml(code, { lang: language, theme });
        if (options.showLineNumbers)
            return addLineNumbers(html);
        return html;
    }
    catch (e) {
        console.error('Highlighting error:', e);
        return `<pre><code>${escapeHtml(code)}</code></pre>`;
    }
}
function addLineNumbers(html) {
    const codeMatch = html.match(/<code[^>]*>([\s\S]*)<\/code>/);
    if (!codeMatch)
        return html;
    const codeContent = codeMatch[1];
    const codeLines = codeContent.split('\n');
    const numberedLines = codeLines.map((line, i) => {
        return `<span class="line-number">${i + 1}</span>${line}`;
    }).join('\n');
    return html.replace(codeMatch[1], numberedLines);
}
function escapeHtml(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}
