/**
 * 从 Word HTML 中按「标题」段落提取章节 Tab，并拆分/合并章节内容。
 */
import { DOCUMENT_SECTION_TABS } from './contract-template-section-html.js';

var DEFAULT_MAIN_TAB = { key: 'main', label: '合同主体' };
var HEADING_TAGS = { H1: true, H2: true, H3: true, H4: true, H5: true, H6: true };

export function getDefaultSectionTabs() {
	return DOCUMENT_SECTION_TABS.slice();
}

export function emptySectionMapForTabs(tabs) {
	var map = {};
	(tabs || []).forEach(function (tab) {
		map[tab.key] = '';
	});
	return map;
}

function normalizeHeadingText(text) {
	return String(text || '').replace(/\s+/g, ' ').trim();
}

function slugifySectionKey(label, index) {
	var slug = String(label || '')
		.toLowerCase()
		.replace(/[^\u4e00-\u9fa5a-z0-9]+/g, '_')
		.replace(/^_+|_+$/g, '')
		.slice(0, 24);
	return slug ? 'section_' + slug + '_' + index : 'section_' + index;
}

function isSectionTitleElement(node) {
	if (!node || node.nodeType !== 1) return false;
	if (!node.classList || !node.classList.contains('ct-word-section-title')) return false;
	if (node.closest && node.closest('table')) return false;
	var text = normalizeHeadingText(node.textContent);
	return text.length > 0 && text.length <= 80;
}

function isHeadingElement(node) {
	if (!node || node.nodeType !== 1) return false;
	if (isSectionTitleElement(node)) return true;
	if (!HEADING_TAGS[node.nodeName]) return false;
	if (node.closest && node.closest('table')) return false;
	var text = normalizeHeadingText(node.textContent);
	return text.length > 0 && text.length <= 80;
}

function collectHeadingElements(root) {
	var headings = [];
	if (!root) return headings;
	var seen = new Set();
	function push(node) {
		if (!node || seen.has(node)) return;
		if (!isHeadingElement(node)) return;
		seen.add(node);
		headings.push(node);
	}
	root.querySelectorAll('.ct-word-section-title,h1,h2,h3,h4,h5,h6').forEach(push);
	return headings;
}

/** 从 Word HTML 提取章节 Tab；无标题时返回 null（调用方回退默认 Tab） */
export function extractSectionTabsFromHtml(html) {
	if (typeof document === 'undefined') return null;
	var source = String(html || '').trim();
	if (!source) return null;

	var div = document.createElement('div');
	div.innerHTML = source;
	var headings = collectHeadingElements(div);
	if (!headings.length) return null;

	var tabs = [Object.assign({}, DEFAULT_MAIN_TAB)];
	var usedKeys = { main: true };

	headings.forEach(function (heading, index) {
		var label = normalizeHeadingText(heading.textContent);
		if (!label) return;
		var key = slugifySectionKey(label, index + 1);
		while (usedKeys[key]) {
			key = key + '_' + index;
		}
		usedKeys[key] = true;
		tabs.push({ key: key, label: label, headingText: label });
	});

	return tabs.length > 1 ? tabs : null;
}

function isWordBlockNode(node) {
	if (!node) return false;
	if (node.nodeType === 3) return !!String(node.textContent || '').trim();
	return node.nodeType === 1 && node.nodeName !== 'STYLE';
}

function detectDynamicSectionStartKey(node, tabs) {
	if (!node || node.nodeType !== 1 || !tabs || !tabs.length) return null;
	if (!isHeadingElement(node)) return null;
	var text = normalizeHeadingText(node.textContent);
	for (var i = 1; i < tabs.length; i++) {
		if (tabs[i].label === text || tabs[i].headingText === text) {
			return tabs[i].key;
		}
	}
	return null;
}

/** 按章节 Tab 将整份 HTML 拆为 section map */
export function splitHtmlBySectionTabs(html, tabs) {
	var sectionTabs = tabs && tabs.length ? tabs : getDefaultSectionTabs();
	var source = String(html || '');
	var result = emptySectionMapForTabs(sectionTabs);
	if (!source.trim()) return result;

	if (typeof document === 'undefined') {
		return result;
	}

	var div = document.createElement('div');
	div.innerHTML = source.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
	var root = div.querySelector('.ct-word-doc') || div;
	var children = [];
	root.childNodes.forEach(function (node) {
		if (isWordBlockNode(node)) children.push(node);
	});

	if (!children.length) {
		result.main = source;
		return result;
	}

	var holders = {};
	var currentKey = 'main';
	children.forEach(function (child) {
		var startKey = detectDynamicSectionStartKey(child, sectionTabs);
		if (startKey) currentKey = startKey;
		if (!holders[currentKey]) holders[currentKey] = document.createElement('div');
		holders[currentKey].appendChild(child.cloneNode(true));
	});

	sectionTabs.forEach(function (tab) {
		result[tab.key] = holders[tab.key] ? holders[tab.key].innerHTML : '';
	});
	return result;
}

/** 将章节 map 合并为整份 HTML */
export function mergeHtmlBySectionTabs(sectionMap, tabs) {
	var sectionTabs = tabs && tabs.length ? tabs : getDefaultSectionTabs();
	var map = sectionMap || {};
	var out = String(map.main || '');
	sectionTabs.slice(1).forEach(function (tab) {
		var chunk = map[tab.key];
		if (chunk) out += String(chunk);
	});
	return out;
}

export function resolveSectionTabs(record) {
	if (record && Array.isArray(record.sectionTabs) && record.sectionTabs.length) {
		return record.sectionTabs;
	}
	return getDefaultSectionTabs();
}

export function getSectionTabLabel(tabs, key) {
	var list = tabs || getDefaultSectionTabs();
	var tab = list.find(function (item) { return item.key === key; });
	return tab ? tab.label : key;
}
