// 初始化 markdown-it with highlight.js
const mdInstance = window.markdownit({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str, lang) {
        if (lang && window.hljs && hljs.getLanguage(lang)) {
            try {
                return hljs.highlight(str, { language: lang, ignoreIllegals: true }).value;
            } catch (__) {}
        }
        if (window.hljs) {
            try {
                return hljs.highlightAuto(str).value;
            } catch (__) {}
        }
        return mdInstance.utils.escapeHtml(str);
    }
});

export const md = {
    render: (text) => {
        const rawHtml = mdInstance.render(text);
        const sanitized = window.DOMPurify.sanitize(rawHtml, {
            ADD_ATTR: ['target'],
            FORBID_TAGS: ['style', 'form', 'input'],
            FORBID_ATTR: ['style', 'onerror', 'onload', 'onclick', 'onmouseover'],
        });
        // 为所有链接添加 target="_blank"，在新标签页打开
        const withTarget = sanitized.replace(/<a /g, '<a target="_blank" rel="noopener noreferrer" ');
        // 为代码块添加包装器（不含 onclick，用事件委托处理复制）
        return withTarget.replace(/<pre><code([^>]*)>/g, (match, attrs) => {
            return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-lang">${escapeHtml(extractLangFromAttrs(attrs))}</span><button class="code-copy-btn" data-action="copy-code" title="复制代码"><span class="material-symbols-rounded">content_copy</span><span>复制</span></button></div><code${attrs}>`;
        });
    }
};

function extractLangFromAttrs(attrs) {
    const m = attrs.match(/class="[^"]*language-([^"\s]+)[^"]*"/);
    return m ? m[1] : 'TEXT';
}

function escapeHtml(value) {
    return String(value).replace(/[&<>"']/g, (char) => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;',
    }[char]));
}

// 全局事件委托：处理代码块复制按钮
document.addEventListener('click', async (e) => {
    const btn = e.target.closest('[data-action="copy-code"]');
    if (!btn) return;
    const pre = btn.closest('pre');
    const code = pre ? pre.querySelector('code') : null;
    if (!code) return;
    try {
        await navigator.clipboard.writeText(code.textContent);
        const icon = btn.querySelector('.material-symbols-rounded');
        const textSpan = btn.querySelector('span:not(.material-symbols-rounded)');
        icon.textContent = 'check';
        if(textSpan) textSpan.textContent = '已复制';
        btn.style.color = 'var(--success)';
        
        setTimeout(() => { 
            icon.textContent = 'content_copy'; 
            if(textSpan) textSpan.textContent = '复制';
            btn.style.color = '';
        }, 2000);
    } catch (err) { console.error('Copy failed:', err); }
});

export function applyTheme(theme) {
    if (!theme || theme === 'auto') {
        // Auto-detect system preference
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        document.documentElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
        _updateHljsTheme(prefersDark);
    } else {
        document.documentElement.setAttribute('data-theme', theme);
        _updateHljsTheme(theme === 'dark');
    }
}

function _updateHljsTheme(isDark) {
    const darkSheet = document.getElementById('hljs-dark');
    const lightSheet = document.getElementById('hljs-light');
    if (darkSheet) darkSheet.disabled = !isDark;
    if (lightSheet) lightSheet.disabled = isDark;
}

/**
 * Strip markdown formatting to get plain text.
 */
export function stripMarkdown(mdText) {
    if (!mdText) return '';
    let text = mdText;
    text = text.replace(/```[\s\S]*?```/g, (match) => {
        const lines = match.split('\n');
        return lines.slice(1, lines.length - 1).join('\n');
    });
    text = text.replace(/`([^`]+)`/g, '$1');
    text = text.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1');
    text = text.replace(/\[([^\]]*)\]\([^)]+\)/g, '$1');
    text = text.replace(/^#{1,6}\s+/gm, '');
    text = text.replace(/\*\*\*(.+?)\*\*\*/g, '$1');
    text = text.replace(/\*\*(.+?)\*\*/g, '$1');
    text = text.replace(/\*(.+?)\*/g, '$1');
    text = text.replace(/___(.+?)___/g, '$1');
    text = text.replace(/__(.+?)__/g, '$1');
    text = text.replace(/_(.+?)_/g, '$1');
    text = text.replace(/~~(.+?)~~/g, '$1');
    text = text.replace(/^>\s?/gm, '');
    text = text.replace(/^[-*_]{3,}\s*$/gm, '');
    text = text.replace(/^\s*[-*+]\s+/gm, '');
    text = text.replace(/^\s*\d+\.\s+/gm, '');
    text = text.replace(/\n{3,}/g, '\n\n');
    return text.trim();
}

export function createMessageActionButton(className, icon, title, onClick) {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = `message-action-btn ${className}`.trim();
    btn.innerHTML = `<span class="material-symbols-rounded">${icon}</span>`;
    btn.title = title;
    btn.setAttribute('aria-label', title);
    btn.onclick = onClick;
    return btn;
}

export function createMessageActionRail(buttons, label = '消息操作') {
    const rail = document.createElement('div');
    rail.className = 'message-action-rail';
    rail.setAttribute('role', 'toolbar');
    rail.setAttribute('aria-label', label);

    buttons.filter(Boolean).forEach((button) => rail.appendChild(button));
    return rail;
}

export function createCopyButton(contentGetter) {
    const btn = createMessageActionButton('copy-btn', 'content_copy', '复制', async (e) => {
        e.stopPropagation();
        const raw = typeof contentGetter === 'function' ? contentGetter() : contentGetter;
        if (!raw) return;

        const text = stripMarkdown(raw);

        try {
            await navigator.clipboard.writeText(text);
            const icon = btn.querySelector('span');
            icon.textContent = 'check';
            btn.classList.add('is-success');
            btn.title = '已复制';
            btn.setAttribute('aria-label', '已复制');
            setTimeout(() => {
                icon.textContent = 'content_copy';
                btn.classList.remove('is-success');
                btn.title = '复制';
                btn.setAttribute('aria-label', '复制');
            }, 1600);
        } catch (err) {
            console.error('Failed to copy:', err);
        }
    });
    btn.dataset.action = 'copy-message';

    return btn;
}

export function createEditMessageButton(contentGetter, onEdit) {
    const btn = createMessageActionButton('edit-message-btn', 'edit', '编辑', (e) => {
        e.stopPropagation();
        const raw = typeof contentGetter === 'function' ? contentGetter() : contentGetter;
        if (!raw) return;
        onEdit(raw);
    });
    btn.dataset.action = 'edit-message';
    return btn;
}

export function createRegenerateButton(onRegenerate) {
    const btn = createMessageActionButton('regenerate-btn', 'refresh', '重新生成', async (e) => {
        e.stopPropagation();
        await onRegenerate();
    });
    btn.dataset.action = 'regenerate-message';
    return btn;
}

export function createDeleteMessageButton(onDelete) {
    const btn = createMessageActionButton('msg-delete-btn', 'delete', '删除', async (e) => {
        e.stopPropagation();
        await onDelete();
    });
    btn.dataset.action = 'delete-message';
    return btn;
}
