/**
 * 合同模板跨原型共享状态（合同模板管理 ↔ 租赁合同创建）
 * 原型级 store；localStorage 优先持久化，sessionStorage 作兼容回退。
 */

import {
	getContractNameLabel,
	normalizeContractType,
	resolveContractName,
	resolveContractType,
} from './contract-template-types.js';

var STORAGE_KEY = 'oneos_contract_templates_v1';
var templates = null;
var listeners = new Set();
var lastWriteSucceeded = true;

function readFromStorage() {
	if (typeof localStorage !== 'undefined') {
		try {
			var localRaw = localStorage.getItem(STORAGE_KEY);
			if (localRaw) {
				var localParsed = JSON.parse(localRaw);
				if (Array.isArray(localParsed) && localParsed.length) return localParsed;
			}
		} catch (err) {
			/* 忽略 */
		}
	}
	if (typeof sessionStorage === 'undefined') return null;
	try {
		var raw = sessionStorage.getItem(STORAGE_KEY);
		if (!raw) return null;
		var parsed = JSON.parse(raw);
		return Array.isArray(parsed) ? parsed : null;
	} catch (err) {
		return null;
	}
}

function writeToStorage() {
	if (!templates) {
		lastWriteSucceeded = true;
		return true;
	}
	var payload = JSON.stringify(templates);
	var localOk = true;
	var sessionOk = true;
	if (typeof localStorage !== 'undefined') {
		try {
			localStorage.setItem(STORAGE_KEY, payload);
		} catch (err) {
			localOk = false;
		}
	}
	if (typeof sessionStorage !== 'undefined') {
		try {
			sessionStorage.setItem(STORAGE_KEY, payload);
		} catch (err) {
			sessionOk = false;
		}
	}
	lastWriteSucceeded = localOk || sessionOk;
	return lastWriteSucceeded;
}

export function wasLastContractTemplateWriteOk() {
	return lastWriteSucceeded;
}

function notify() {
	var snapshot = templates ? templates.slice() : [];
	listeners.forEach(function (fn) {
		try {
			fn(snapshot);
		} catch (err) {
			console.error('[contract-template-store] listener error', err);
		}
	});
}

export function restoreContractTemplatesFromSession() {
	if (templates) return templates;
	var restored = readFromStorage();
	if (restored) {
		templates = restored;
		notify();
	}
	return templates || [];
}

export function ensureContractTemplateStore(seedFactory) {
	if (!templates) {
		templates = readFromStorage();
	}
	if (!templates && typeof seedFactory === 'function') {
		templates = seedFactory();
		writeToStorage();
		notify();
	}
	return templates || [];
}

export function getContractTemplates() {
	return templates ? templates.slice() : [];
}

export function setContractTemplates(updater) {
	var current = templates ? templates.slice() : [];
	var next = typeof updater === 'function' ? updater(current) : updater;
	templates = Array.isArray(next) ? next : current;
	writeToStorage();
	notify();
	return templates;
}

export function subscribeContractTemplates(listener) {
	if (typeof listener !== 'function') return function () {};
	listeners.add(listener);
	return function () {
		listeners.delete(listener);
	};
}

var VEHICLE_HINT_BY_ID = {
	'doc-1': '现代 · 18吨氢燃料电池车',
	'doc-2': '通用车型',
	'doc-4': '通用车型',
	'doc-5': '现代 · 18吨',
};

function inferKind(doc) {
	return resolveContractName(doc);
}

function inferVehicleHint(doc) {
	if (doc.id && VEHICLE_HINT_BY_ID[doc.id]) return VEHICLE_HINT_BY_ID[doc.id];
	return '通用车型';
}

export function mapTemplateToLeaseOption(doc) {
	var contractName = resolveContractName(doc);
	return {
		id: doc.id,
		title: doc.versionName || stripExtension(doc.fileName) || doc.id,
		fileName: doc.fileName || doc.versionName || '',
		versionNo: doc.versionNo || '—',
		contractType: contractName,
		contractTypeLabel: getContractNameLabel(contractName),
		kind: inferKind(doc),
		vehicleHint: inferVehicleHint(doc),
	};
}

function stripExtension(name) {
	return String(name || '').replace(/\.[^.]+$/, '');
}

/** 已发布且启用、可供租赁合同创建选用的模板 */
export function getPublishedEnabledLeaseOptions(category) {
	var cat = category || 'lease';
	return (templates || [])
		.filter(function (doc) {
			return doc.category === cat
				&& doc.status === 'published'
				&& doc.enabled !== false;
		})
		.map(mapTemplateToLeaseOption)
		.sort(function (a, b) {
			return String(a.fileName).localeCompare(String(b.fileName), 'zh-CN');
		});
}

/** 已发布且启用模板中去重后的合同类型（供租赁合同创建选用） */
export function getPublishedContractTypeOptions(category) {
	var cat = category || 'lease';
	var seen = {};
	var types = [];
	(templates || []).forEach(function (doc) {
		if (doc.category !== cat || doc.status !== 'published' || doc.enabled === false) return;
		var type = resolveContractType(doc);
		if (!type || seen[type]) return;
		seen[type] = true;
		types.push({ value: type, label: type });
	});
	return types.sort(function (a, b) {
		return a.label.localeCompare(b.label, 'zh-CN');
	});
}

export function getTemplateDocumentById(templateId) {
	if (!templateId || !templates) return null;
	return templates.find(function (doc) { return doc.id === templateId; }) || null;
}

export function getTemplateSectionVehicleBindings(templateId) {
	var doc = getTemplateDocumentById(templateId);
	if (!doc || !doc.sectionVehicleBindings) return {};
	return doc.sectionVehicleBindings;
}

/** 某合同类型下已发布且启用的模板（取最近更新的一条） */
export function getDefaultTemplateIdForContractType(contractType, category) {
	var normalizedType = normalizeContractType(contractType);
	if (!normalizedType) return '';
	var cat = category || 'lease';
	var matches = (templates || []).filter(function (doc) {
		return doc.category === cat
			&& doc.status === 'published'
			&& doc.enabled !== false
			&& resolveContractType(doc) === normalizedType;
	});
	if (!matches.length) return '';
	matches.sort(function (a, b) {
		return String(b.updateTime || '').localeCompare(String(a.updateTime || ''), 'zh-CN');
	});
	return matches[0].id;
}
