// static/shell.js
const CONFIG = {
	apiBase: '/api',
	useMock: typeof IS_MOCK !== 'undefined' ? IS_MOCK : false
};

window.AquaScape = {
	appInfo: null,
	widgets: [],
	navigateTo: null
};

window.AquaScape.applyTheme = function(theme) {
	document.documentElement.setAttribute('data-theme', theme);
};

function _esc(v) {
	return String(v === undefined || v === null ? '' : v)
		.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

document.addEventListener('DOMContentLoaded', () => {
	if (sessionStorage.getItem('force_reload_after_ota') === 'true') {
		sessionStorage.removeItem('force_reload_after_ota');
		window.location.replace('/?id=' + Date.now());
		return;
	}
	initApp();
});

async function initApp() {
	await loadData();
	if (window.AquaScape.appInfo) {
		document.getElementById('app-version').textContent = `v${window.AquaScape.appInfo.version}`;
		const title = document.querySelector('.header-title');
		if (title) title.textContent = window.AquaScape.appInfo.name;
		window.AquaScape.applyTheme(window.AquaScape.appInfo.theme || 'light');
	}
	setupNavigation();
	window.AquaScape.navigateTo('home');
}

async function loadData() {
	if (CONFIG.useMock) {
		window.AquaScape.appInfo = MOCK_DATA.app;
		window.AquaScape.widgets = MOCK_DATA.widgets;
	} else {
		try {
			const [appRes, widgetsRes] = await Promise.all([
				fetch(`${CONFIG.apiBase}/app?t=${Date.now()}`),
				fetch(`${CONFIG.apiBase}/widgets?id=${Date.now()}`)
			]);
			window.AquaScape.appInfo = await appRes.json();
			window.AquaScape.widgets = await widgetsRes.json();
		} catch (error) {
			console.error('Ошибка загрузки данных:', error);
			window.AquaScape.appInfo = MOCK_DATA.app;
			window.AquaScape.widgets = MOCK_DATA.widgets;
		}
	}
}

function setupNavigation() {
	document.querySelectorAll('.nav-btn').forEach(btn => {
		btn.addEventListener('click', () => {
			window.AquaScape.navigateTo(btn.dataset.page);
		});
	});
}

window.AquaScape.navigateTo = async function(page) {
	document.querySelectorAll('.nav-btn').forEach(btn => {
		btn.classList.toggle('active', btn.dataset.page === page);
	});
	
	const content = document.getElementById('app-content');
	content.innerHTML = '<div class="loading"><div class="spinner"></div><p>Загрузка...</p></div>';

	if (page === 'home') {
		renderHome(content);
	} else if (page === 'settings') {
		await loadModule('/static/system/settings.js?id=' + Date.now(), 'renderSettings', content);
	} else if (page === 'update') {
		await loadModule('/static/system/update.js?id=' + Date.now(), 'renderUpdate', content);
	}
};

function renderHome(container) {
	if (!window.AquaScape.widgets.length) {
		container.innerHTML = '<p>Нет доступных виджетов</p>';
		return;
	}
	const grid = document.createElement('div');
	grid.className = 'widgets-grid';
	window.AquaScape.widgets.forEach(widget => {
		const el = document.createElement('div');
		el.className = 'widget';
		el.innerHTML = `<div class="widget-title">${_esc(widget.title)}</div><div class="widget-value">${_esc(widget.value)}</div><div class="widget-status">${_esc(widget.status)}</div>`;
		el.addEventListener('click', () => openWidgetPage(widget, container));
		grid.appendChild(el);
	});
	container.innerHTML = '';
	container.appendChild(grid);
}

// <<< ИЗМЕНЕНО: страница виджета = index.html + script.js (оба опциональны)
async function openWidgetPage(widget, container) {
	container.innerHTML = `
		<div class="widget-page">
			<button class="back-btn" onclick="window.AquaScape.navigateTo('home')">← Назад</button>
			<h2>${_esc(widget.title)}</h2>
			<div id="widget-body">
				<div class="loading"><div class="spinner"></div><p>Загрузка...</p></div>
			</div>
		</div>`;

	const body = document.getElementById('widget-body');
	const fallback = `
		<div class="widget-detail">
			<p>Значение: ${_esc(widget.value)}</p>
			<p>Статус: ${_esc(widget.status)}</p>
		</div>`;

	if (!widget.page) {
		body.innerHTML = fallback;
		return;
	}

	// Убираем скрипты предыдущих виджетов
	document.querySelectorAll('script[data-widget-script]').forEach(s => s.remove());

	let htmlLoaded = false;
	try {
		const res = await fetch(`/widgets/${widget.id}/index.html?id=${Date.now()}`);
		if (res.ok) {
			body.innerHTML = await res.text();
			htmlLoaded = true;
		}
	} catch (e) {}

	if (!htmlLoaded) {
		body.innerHTML = fallback;
		return;
	}

	// Скрипт виджета опционален; автозапуск лежит внутри самого скрипта
	await new Promise(resolve => {
		const script = document.createElement('script');
		script.src = `/widgets/${widget.id}/script.js?id=${Date.now()}`;
		script.async = false;
		script.setAttribute('data-widget-script', widget.id);
		script.onload = resolve;
		script.onerror = () => { script.remove(); resolve(); };
		document.head.appendChild(script);
	});
}

async function loadModule(url, initFunctionName, container) {
	if (typeof window[initFunctionName] === 'function') {
		window[initFunctionName](container);
		return;
	}
	try {
		const script = document.createElement('script');
		script.src = url;
		script.async = false;
		await new Promise((resolve, reject) => {
			script.onload = resolve;
			script.onerror = reject;
			document.head.appendChild(script);
		});
		if (typeof window[initFunctionName] === 'function') {
			window[initFunctionName](container);
		}
	} catch (error) {
		console.error(`Ошибка загрузки модуля ${url}:`, error);
		container.innerHTML = `<p style="color:red;">Ошибка загрузки раздела</p>`;
	}
}