import type { ReactNode } from 'react';

/**
 * Render de texto enriquecido "markdown liviano" para las páginas de contenido
 * (términos, políticas, FAQ…). Soporta lo que un comercio necesita en una
 * política y nada más:
 *   ## Título        → subtítulo
 *   - item           → lista con viñetas
 *   **negrita**      → <strong>
 *   *itálica*        → <em>
 *   línea en blanco  → separación de párrafos
 *
 * Genera nodos React (nunca dangerouslySetInnerHTML): el contenido lo escribe
 * el comercio en el panel y no debe poder inyectar HTML en la tienda.
 */
export function renderStoreRichText(content: string | null | undefined): ReactNode {
	if (!content) return null;

	const lines = content.replace(/\r\n/g, '\n').split('\n');
	const out: ReactNode[] = [];
	let list: string[] = [];

	const flushList = () => {
		if (list.length === 0) return;
		out.push(
			<ul key={`ul-${out.length}`}>
				{list.map((item, i) => (
					<li key={i}>{renderInline(item)}</li>
				))}
			</ul>
		);
		list = [];
	};

	for (const raw of lines) {
		const line = raw.trim();
		if (!line) {
			flushList();
			continue;
		}
		if (line.startsWith('- ') || line.startsWith('* ')) {
			list.push(line.slice(2));
			continue;
		}
		flushList();
		if (line.startsWith('## ')) {
			out.push(<h4 key={`h-${out.length}`}>{renderInline(line.slice(3))}</h4>);
		} else {
			out.push(<p key={`p-${out.length}`}>{renderInline(line)}</p>);
		}
	}
	flushList();
	return out;
}

/** Resuelve **negrita** y *itálica* dentro de una línea. */
function renderInline(text: string): ReactNode {
	const parts: ReactNode[] = [];
	// Alterna: negrita primero (no-greedy), después itálica sobre los restos.
	const tokens = text.split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g).filter(Boolean);
	tokens.forEach((tok, i) => {
		if (tok.startsWith('**') && tok.endsWith('**') && tok.length > 4) {
			parts.push(<strong key={i}>{tok.slice(2, -2)}</strong>);
		} else if (tok.startsWith('*') && tok.endsWith('*') && tok.length > 2) {
			parts.push(<em key={i}>{tok.slice(1, -1)}</em>);
		} else {
			parts.push(tok);
		}
	});
	return parts;
}
