/**
 * 租赁合同预览：检测风控红线条款（模板标记）是否被修改
 */

export var STANDARD_CONTRACT_APPROVAL = '标准合同';
export var NONSTANDARD_CONTRACT_APPROVAL = '非标准合同';

var RISK_SELECTOR = '.ct-risk-redline[data-risk-redline="1"]';

function normalizeRiskText(value) {
	return String(value || '')
		.replace(/<br\s*\/?>/gi, '\n')
		.replace(/&nbsp;/gi, ' ')
		.replace(/\u200b/g, '')
		.replace(/\s+/g, ' ')
		.trim();
}

function collectRiskSnapshots(html) {
	if (!html || typeof document === 'undefined') return [];
	var div = document.createElement('div');
	div.innerHTML = String(html || '');
	var list = [];
	div.querySelectorAll(RISK_SELECTOR).forEach(function (el, index) {
		list.push({
			id: el.getAttribute('data-risk-id') || ('risk-' + index),
			text: normalizeRiskText(el.innerHTML),
		});
	});
	return list;
}

/** 风控红线条款正文是否与基线不一致 */
export function isRiskRedlineContentModified(baselineHtml, currentHtml) {
	var baseline = collectRiskSnapshots(baselineHtml);
	var current = collectRiskSnapshots(currentHtml);
	if (!baseline.length && !current.length) return false;
	if (baseline.length !== current.length) return true;
	for (var i = 0; i < baseline.length; i++) {
		if (baseline[i].text !== current[i].text) return true;
	}
	return false;
}

export function mergePreviewPages(pages) {
	return (pages || []).join('');
}

export function resolveContractApprovalType(baselineHtml, currentHtml) {
	return isRiskRedlineContentModified(baselineHtml, currentHtml)
		? NONSTANDARD_CONTRACT_APPROVAL
		: STANDARD_CONTRACT_APPROVAL;
}
