/**
 * Save-path serialization helpers (pure, testable).
 */

import { getVisibleItems } from './items';

/**
 * Escape text for HTML text nodes.
 *
 * @param {string} value Raw.
 * @return {string} Escaped.
 */
export function escapeHtml(value) {
	return String(value || '')
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#039;');
}

/**
 * Strip scripts / event handlers from answer HTML before save.
 * Server re-sanitizes with wp_kses on render.
 *
 * @param {string} html Raw HTML.
 * @return {string} Safer HTML.
 */
export function sanitizeAnswerHtml(html) {
	const value = String(html || '');
	return value
		.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '')
		.replace(/\son\w+\s*=\s*(".*?"|'.*?'|[^\s>]+)/gi, '')
		.replace(/javascript:/gi, '');
}

/**
 * Build static/fallback-visible inner HTML for the FAQ block.
 *
 * Accordion uses native details/summary so content remains accessible
 * without the plugin or JavaScript.
 *
 * @param {Object} attributes Block attributes.
 * @return {string} Inner HTML (without outer section wrapper).
 */
export function buildFaqInnerHtml(attributes = {}) {
	const {
		heading = '',
		intro = '',
		items = [],
		displayMode = 'accordion',
		openFirstItem = false,
		showQuestionNumbers = false,
	} = attributes;

	const visible = getVisibleItems(items);
	let index = 0;
	const itemsHtml = visible
		.map((item) => {
			const question = (item.question || '').trim();
			const answer = item.answer || '';
			index += 1;
			const label = showQuestionNumbers ? `${index}. ${question}` : question;
			const idAttr = item.id
				? ` data-faq-item-id="${escapeHtml(item.id)}"`
				: '';
			const answerHtml = sanitizeAnswerHtml(answer);
			if (displayMode === 'static') {
				return `<div class="seovault-faq-block__item"${idAttr}><h3 class="seovault-faq-block__question">${escapeHtml(
					label
				)}</h3><div class="seovault-faq-block__answer">${answerHtml}</div></div>`;
			}
			const openAttr = openFirstItem && index === 1 ? ' open' : '';
			return `<details class="seovault-faq-block__item"${idAttr}${openAttr}><summary class="seovault-faq-block__question">${escapeHtml(
				label
			)}</summary><div class="seovault-faq-block__answer">${answerHtml}</div></details>`;
		})
		.join('');

	const headingHtml = heading
		? `<h2 class="seovault-faq-block__heading">${escapeHtml(heading)}</h2>`
		: '';
	const introHtml = intro
		? `<p class="seovault-faq-block__intro">${escapeHtml(intro)}</p>`
		: '';

	return `${headingHtml}${introHtml}<div class="seovault-faq-block__items">${itemsHtml}</div>`;
}

/**
 * Class list for the saved/rendered wrapper.
 *
 * @param {Object} attributes Attributes.
 * @return {string[]} Classes.
 */
export function buildFaqClassList(attributes = {}) {
	const {
		displayMode = 'accordion',
		stylePreset = 'accordion-cards',
		colorPreset = 'blue',
		density = 'comfortable',
		sharpCorners = false,
	} = attributes;

	const classes = [
		'seovault-faq-block',
		`seovault-faq-block--${displayMode}`,
		`seovault-faq-block--style-${stylePreset}`,
		`seovault-faq-block--color-${colorPreset}`,
		`seovault-faq-block--density-${density}`,
	];
	if (sharpCorners) {
		classes.push('seovault-faq-block--sharp');
	}
	return classes;
}
