/**
 * Small, safe Markdown renderer for AI text (Ask AI answers, AI daily brief).
 *
 * Builds React elements only (no innerHTML), so model output can never inject markup.
 * Supports paragraphs, line breaks, # headings, - / * / • lists (nested by indent),
 * 1. lists, **bold**, *italic*, `code` and http(s) links.
 */
const INLINE_SOURCE = /(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|(?<![\w*])\*(?!\s)[^*]+?(?<!\s)\*(?![\w*])|(?<![\w_])_(?!\s)[^_]+?(?<!\s)_(?![\w_]))/g;

function inline( text, keyBase, depth = 0 ) {
	if ( depth > 4 ) {
		return [ text ];
	}
	// A fresh regex per call: a shared global regex would have its position reset by the
	// recursive calls below and loop forever on the same token.
	const re = new RegExp( INLINE_SOURCE.source, 'g' );
	const out = [];
	let last = 0;
	let m;
	let i = 0;
	while ( ( m = re.exec( text ) ) !== null ) {
		if ( m[ 0 ].length === 0 ) {
			re.lastIndex++;
			continue;
		}
		if ( m.index > last ) {
			out.push( text.slice( last, m.index ) );
		}
		const tok = m[ 0 ];
		const key = `${ keyBase }-${ i++ }`;
		if ( tok.startsWith( '**' ) || tok.startsWith( '__' ) ) {
			out.push( <strong key={ key }>{ inline( tok.slice( 2, -2 ), key, depth + 1 ) }</strong> );
		} else if ( tok.startsWith( '`' ) ) {
			out.push( <code key={ key }>{ tok.slice( 1, -1 ) }</code> );
		} else if ( tok.startsWith( '[' ) ) {
			const link = /^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec( tok );
			out.push( link ? <a key={ key } href={ link[ 2 ] } target="_blank" rel="noopener noreferrer">{ link[ 1 ] }</a> : tok );
		} else {
			out.push( <em key={ key }>{ inline( tok.slice( 1, -1 ), key, depth + 1 ) }</em> );
		}
		last = re.lastIndex;
	}
	if ( last < text.length ) {
		out.push( text.slice( last ) );
	}
	return out;
}

const LIST_RE = /^(\s*)([-*•]|\d+[.)])\s+(.*)$/;

/** Nested list from consecutive list lines: [ { indent, ordered, text } ]. */
function renderList( items, keyBase ) {
	const root = { children: [], ordered: items[ 0 ].ordered };
	const stack = [ { indent: items[ 0 ].indent, node: root } ];
	items.forEach( ( it ) => {
		while ( stack.length > 1 && it.indent < stack[ stack.length - 1 ].indent ) {
			stack.pop();
		}
		const top = stack[ stack.length - 1 ];
		if ( it.indent > top.indent && top.node.children.length ) {
			const parent = top.node.children[ top.node.children.length - 1 ];
			parent.sub = parent.sub || { children: [], ordered: it.ordered };
			stack.push( { indent: it.indent, node: parent.sub } );
		}
		stack[ stack.length - 1 ].node.children.push( { text: it.text } );
	} );
	const build = ( node, key ) => {
		const Tag = node.ordered ? 'ol' : 'ul';
		return (
			<Tag key={ key }>
				{ node.children.map( ( c, i ) => (
					<li key={ `${ key }-${ i }` }>
						{ inline( c.text, `${ key }-${ i }` ) }
						{ c.sub && build( c.sub, `${ key }-${ i }-s` ) }
					</li>
				) ) }
			</Tag>
		);
	};
	return build( root, keyBase );
}

export function renderMarkdown( source ) {
	const lines = String( source || '' ).replace( /\r\n?/g, '\n' ).split( '\n' );
	const blocks = [];
	let para = [];
	let list = [];
	const flushPara = () => {
		if ( para.length ) {
			const key = `p${ blocks.length }`;
			blocks.push(
				<p key={ key }>
					{ para.map( ( l, i ) => [ i ? <br key={ `${ key }-br${ i }` } /> : null, ...inline( l, `${ key }-${ i }` ) ] ) }
				</p>
			);
			para = [];
		}
	};
	const flushList = () => {
		if ( list.length ) {
			blocks.push( renderList( list, `l${ blocks.length }` ) );
			list = [];
		}
	};
	lines.forEach( ( raw ) => {
		const line = raw.replace( /\s+$/, '' );
		if ( ! line.trim() ) {
			flushPara();
			flushList();
			return;
		}
		const h = /^\s*(#{1,6})\s+(.*)$/.exec( line );
		if ( h ) {
			flushPara();
			flushList();
			blocks.push( <p key={ `h${ blocks.length }` } className="ssgsw-md__h"><strong>{ inline( h[ 2 ], `h${ blocks.length }` ) }</strong></p> );
			return;
		}
		const li = LIST_RE.exec( line );
		if ( li ) {
			flushPara();
			list.push( { indent: li[ 1 ].replace( /\t/g, '    ' ).length, ordered: /\d/.test( li[ 2 ] ), text: li[ 3 ] } );
			return;
		}
		flushList();
		para.push( line.trim() );
	} );
	flushPara();
	flushList();
	return blocks;
}

/** Plain text of a Markdown string (for Copy and for places that cannot render). */
export function markdownToText( source ) {
	return String( source || '' )
		.replace( /\r\n?/g, '\n' )
		.replace( /^\s*#{1,6}\s+/gm, '' )
		.replace( /^(\s*)[-*]\s+/gm, '$1• ' )
		.replace( /\*\*([^*]+)\*\*|__([^_]+)__/g, ( m, a, b ) => a || b )
		.replace( /(^|[^\w*])\*(?!\s)([^*]+?)\*(?![\w*])/g, '$1$2' )
		.replace( /`([^`]+)`/g, '$1' )
		.replace( /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '$1 ($2)' );
}

export default function Markdown( { text, className = '' } ) {
	return <div className={ `ssgsw-md ${ className }` }>{ renderMarkdown( text ) }</div>;
}
