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

import { ensureStableIds, getCompleteSteps, stepPlainText } from './steps';
import { normalizeStringList } from './string-list';

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

/**
 * Derive setup status from block attributes.
 *
 * - empty: no content yet
 * - incomplete: has content but missing name or a complete step
 * - ready_for_schema: name + at least one complete step (schema still deferred to Phase 41)
 *
 * @param {Object} attributes Block attributes.
 * @return {{status:HowToSetupStatus,completeCount:number,totalCount:number,message:string,code:string}} Status.
 */
export function getHowToSetupStatus(attributes = {}) {
	const name = String(attributes.name || '').trim();
	const description = String(attributes.description || '').trim();
	const steps = ensureStableIds(attributes.steps || []);
	const supplies = normalizeStringList(attributes.supplies || []);
	const tools = normalizeStringList(attributes.tools || []);
	const totalTime = String(attributes.totalTime || '').trim();
	const cost = attributes.estimatedCost && typeof attributes.estimatedCost === 'object'
		? attributes.estimatedCost
		: {};
	const hasCost =
		String(cost.currency || '').trim() !== '' || String(cost.value || '').trim() !== '';

	const complete = getCompleteSteps(steps);
	const completeCount = complete.length;
	const totalCount = steps.length;

	const hasAny =
		name !== '' ||
		description !== '' ||
		totalCount > 0 ||
		supplies.length > 0 ||
		tools.length > 0 ||
		totalTime !== '' ||
		hasCost ||
		steps.some(hasAnyStepContent);

	if (!hasAny) {
		return {
			status: 'empty',
			completeCount: 0,
			totalCount,
			code: 'howto_setup_empty',
			message:
				'Add a how-to name and at least one step. Schema is not published until the minimum content exists.',
		};
	}

	if (name !== '' && completeCount >= 1) {
		return {
			status: 'ready_for_schema',
			completeCount,
			totalCount,
			code: 'howto_setup_ready',
			message:
				'Visible How-to content is ready. Schema publishing is handled separately by SEOvault when this post is saved — this block does not inject JSON-LD by itself.',
		};
	}

	return {
		status: 'incomplete',
		completeCount,
		totalCount,
		code: 'howto_setup_incomplete',
		message:
			'Finish a how-to name and at least one complete step. Incomplete steps stay in the editor but are excluded from schema.',
	};
}

/**
 * @param {Object} step Step.
 * @return {boolean} Whether the row has any text.
 */
function hasAnyStepContent(step) {
	const name = (step.name || '').trim();
	const plain = stepPlainText(step.text);
	return name !== '' || plain !== '';
}
