import chalk from 'chalk';

export function renderInline(text) {
    return text
        .replace(/`([^`]+)`/g, (_, c) => chalk.cyan(c))
        .replace(/\*\*\*(.+?)\*\*\*/g, (_, t) => chalk.bold.italic(t))
        .replace(/\*\*(.+?)\*\*/g, (_, t) => chalk.bold(t))
        .replace(/\*([^*]+)\*/g, (_, t) => chalk.italic(t))
        .replace(/\b_([^_]+)_\b/g, (_, t) => chalk.italic(t))
        .replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => chalk.blue.underline(t) + chalk.dim(` (${u})`));
}

export function renderMarkdown(content) {
    const lines = content.split('\n');
    const out = [];
    let inCode = false;
    let codeBuf = [];
    let codeLang = '';
    let tableBuf = [];

    const stripAnsi = s => s.replace(/\x1b\[[0-9;]*m/g, '');

    const flushCode = () => {
        const label = codeLang ? chalk.dim.yellow(` ${codeLang}`) : '';
        out.push(chalk.dim('  ┌' + '─'.repeat(58)) + label);
        for (const cl of codeBuf) out.push(chalk.dim('  │ ') + chalk.cyan(cl));
        out.push(chalk.dim('  └' + '─'.repeat(58)));
        codeBuf = [];
        codeLang = '';
    };

    const flushTable = () => {
        if (!tableBuf.length) return;
        const allRows = tableBuf.map(row => {
            const isSep = /^\|[-| :]+\|$/.test(row);
            return { isSep, cells: isSep ? null : row.split('|').slice(1, -1).map(c => c.trim()) };
        });
        const dataRows = allRows.filter(r => !r.isSep).map(r => r.cells);
        const numCols = dataRows.length ? Math.max(...dataRows.map(r => r.length)) : 0;
        const maxWidths = Array(numCols).fill(0);
        for (const cells of dataRows) {
            for (let i = 0; i < Math.min(cells.length, numCols); i++) {
                maxWidths[i] = Math.max(maxWidths[i], stripAnsi(renderInline(cells[i])).length);
            }
        }
        for (const { isSep, cells } of allRows) {
            if (isSep) {
                const total = maxWidths.reduce((a, b) => a + b, 0) + Math.max(numCols - 1, 0) * 5;
                out.push(chalk.dim('  ' + '─'.repeat(Math.max(total, 0))));
            } else {
                const rendered = cells.map((c, i) => {
                    const r = renderInline(c);
                    const pad = (maxWidths[i] || 0) - stripAnsi(r).length;
                    return r + ' '.repeat(Math.max(0, pad));
                });
                out.push('  ' + rendered.join(chalk.dim('  │  ')));
            }
        }
        tableBuf = [];
    };

    for (const line of lines) {
        if (!line.startsWith('|') && tableBuf.length) flushTable();

        if (line.startsWith('```')) {
            if (!inCode) { inCode = true; codeLang = line.slice(3).trim(); }
            else { inCode = false; flushCode(); }
            continue;
        }
        if (inCode) { codeBuf.push(line); continue; }

        const h1 = line.match(/^# (.+)/);
        const h2 = line.match(/^## (.+)/);
        const h3 = line.match(/^### (.+)/);
        const h4 = line.match(/^#### (.+)/);
        if (h1) {
            const t = h1[1];
            out.push(''); out.push(chalk.bold.white.underline(t)); out.push(chalk.dim('═'.repeat(Math.min(t.length, 72)))); out.push('');
            continue;
        }
        if (h2) { out.push(''); out.push(chalk.bold.yellow(renderInline(h2[1]))); out.push(''); continue; }
        if (h3) { out.push(''); out.push(chalk.bold(renderInline(h3[1]))); continue; }
        if (h4) { out.push(''); out.push(chalk.bold.dim(renderInline(h4[1]))); continue; }

        if (line.match(/^---+$/)) { out.push(chalk.dim('─'.repeat(72))); continue; }
        if (line.startsWith('> ')) { out.push(chalk.dim('  │ ') + chalk.dim.italic(renderInline(line.slice(2)))); continue; }

        const ck = line.match(/^- \[( |x)\] (.+)/i);
        if (ck) {
            const done = ck[1].toLowerCase() === 'x';
            out.push(`  ${done ? chalk.green('☑') : chalk.dim('☐')} ${done ? chalk.dim(renderInline(ck[2])) : renderInline(ck[2])}`);
            continue;
        }
        const ul = line.match(/^(\s*)[*\-+] (.+)/);
        if (ul) {
            const depth = ul[1].length;
            out.push(`${' '.repeat(depth + 2)}${depth > 0 ? chalk.dim('◦') : chalk.yellow('•')} ${renderInline(ul[2])}`);
            continue;
        }
        const ol = line.match(/^(\s*)(\d+)\. (.+)/);
        if (ol) { out.push(`${' '.repeat(ol[1].length + 2)}${chalk.yellow(ol[2] + '.')} ${renderInline(ol[3])}`); continue; }

        if (line.startsWith('|')) { tableBuf.push(line); continue; }

        out.push(line.trim() === '' ? '' : renderInline(line));
    }

    if (tableBuf.length) flushTable();
    if (inCode) flushCode();

    return out.join('\n');
}
