/**
 * Editor-facing FAQ setup status (does not claim schema is published).
 */

import { getCompleteItems, ensureStableIds } from './items';

/**
 * @typedef {'empty'|'incomplete'|'ready_for_schema'} FaqSetupStatus
 */

/**
 * Derive setup status from block attributes.
 *
 * - empty: no content yet
 * - incomplete: has rows but no complete Q/A pair (or only partial pairs)
 * - ready_for_schema: at least one complete visible pair (schema still deferred to Phase 28)
 *
 * @param {Object} attributes Block attributes.
 * @return {{status:FaqSetupStatus,completeCount:number,totalCount:number,message:string,code:string}} Status.
 */
export function getFaqSetupStatus(attributes = {}) {
	const items = ensureStableIds(attributes.items || []);
	const complete = getCompleteItems(items);
	const total = items.length;
	const completeCount = complete.length;

	if (total === 0 || (completeCount === 0 && !items.some(hasAnyContent))) {
		return {
			status: 'empty',
			completeCount: 0,
			totalCount: total,
			code: 'faq_setup_empty',
			message:
				'Add at least one question and answer. Schema is not published until a complete pair exists.',
		};
	}

	if (completeCount === 0) {
		return {
			status: 'incomplete',
			completeCount: 0,
			totalCount: total,
			code: 'faq_setup_incomplete',
			message:
				'Finish at least one complete question and answer. Incomplete rows stay visible in the editor but are excluded from schema.',
		};
	}

	return {
		status: 'ready_for_schema',
		completeCount,
		totalCount: total,
		code: 'faq_setup_ready',
		message:
			'Visible FAQ content is ready. Schema publishing is handled separately by SEOvault when this post is saved — this block does not inject JSON-LD by itself.',
	};
}

/**
 * @param {Object} item Item.
 * @return {boolean} Whether the row has any text.
 */
function hasAnyContent(item) {
	const question = (item.question || '').trim();
	const plain = String(item.answer || '')
		.replace(/<[^>]+>/g, ' ')
		.replace(/\s+/g, ' ')
		.trim();
	return question !== '' || plain !== '';
}
