/*
RSK World – Tower Defense 3D (UIManager Evolution)
For support, licensing, or custom development inquiries: help@rskworld.in • Phone/WhatsApp: +91 9330539277
Website: RSK World • Business Inquiries: help@rskworld.in
🤝 Contributing: Suggestions and improvements are welcome!
*/

export class UIManager {
	constructor(state, { onSetBuildMode, onStartWave, onSpawnVillager, onToggleDayNight, onUpgradeSelected, getSelectedInfo }) {
		this.onSetBuildMode = onSetBuildMode;
		this.onStartWave = onStartWave;
		this.onSpawnVillager = onSpawnVillager;
		this.onToggleDayNight = onToggleDayNight;
		this.onUpgradeSelected = onUpgradeSelected;
		this.getSelectedInfo = getSelectedInfo;
		this.hint = document.getElementById('build-hint');
		this.btnStart = document.getElementById('btn-start');
		this.btnVillager = document.getElementById('btn-villager');
		this.btnDayNight = document.getElementById('btn-daynight');

		// Select all build buttons
		this.buildBtns = document.querySelectorAll('button[data-mode]');
		
		// Inject selection/upgrade slot
		this.upgradeSlot = document.createElement('div');
		this.upgradeSlot.className = 'control-group upgrade-panel';
		this.upgradeSlot.style.display = 'none';
		this.upgradeSlot.style.marginTop = '8px';
		this.upgradeSlot.style.paddingTop = '8px';
		this.upgradeSlot.style.borderTop = '1px solid rgba(255,255,255,0.1)';
		
		this.upgradeLabel = document.createElement('div');
		this.upgradeLabel.style.fontSize = '12px';
		this.upgradeLabel.style.marginBottom = '4px';
		this.upgradeLabel.style.color = '#94a3b8';
		
		this.upgradeBtn = document.createElement('button');
		this.upgradeBtn.className = 'btn primary';
		this.upgradeBtn.style.width = '100%';
		this.upgradeBtn.textContent = 'Upgrade';
		this.upgradeBtn.addEventListener('click', () => this.onUpgradeSelected && this.onUpgradeSelected());
		
		this.upgradeSlot.appendChild(this.upgradeLabel);
		this.upgradeSlot.appendChild(this.upgradeBtn);
		document.querySelector('.controls')?.appendChild(this.upgradeSlot);

		const setMode = (mode) => {
			const activeBtn = document.querySelector('button[data-mode].active');
			const currentMode = activeBtn ? activeBtn.getAttribute('data-mode') : 'none';

			// Toggle off if clicking the same
			if (mode === currentMode) {
				activeBtn.classList.remove('active');
				this.onSetBuildMode('none');
				this.showBuildHint(false);
				return;
			}

			// Clear previous
			this.buildBtns.forEach(btn => btn.classList.remove('active'));
			
			// Set new
			const newBtn = document.querySelector(`button[data-mode="${mode}"]`);
			if (newBtn) {
				newBtn.classList.add('active');
				this.onSetBuildMode(mode);
				this.showBuildHint(true);
				this.hint.textContent = `Deploying ${mode.toUpperCase()}...`;
			}
		};

		this.buildBtns.forEach(btn => {
			btn.addEventListener('click', () => setMode(btn.getAttribute('data-mode')));
		});

		this.btnStart.addEventListener('click', () => this.onStartWave());
		this.btnVillager.addEventListener('click', () => this.onSpawnVillager());
		
		this._isNight = false;
		this.btnDayNight.addEventListener('click', () => {
			this._isNight = !this._isNight;
			this.btnDayNight.innerHTML = this._isNight ? '<span class="icon">☀️</span> Day Mode' : '<span class="icon">🌙</span> Night Mode';
			this.onToggleDayNight(this._isNight ? 'night' : 'day');
		});

		window.addEventListener('keydown', (e) => {
			if (e.key === 'Escape') {
				this.buildBtns.forEach(btn => btn.classList.remove('active'));
				this.onSetBuildMode('none');
				this.showBuildHint(false);
			}
		});

		this.update(state);
	}

	updateUpgradeSlot() {
		if (!this.getSelectedInfo) return;
		const info = this.getSelectedInfo();
		if (!info) { this.upgradeSlot.style.display = 'none'; return; }
		
		this.upgradeSlot.style.display = 'block';
		this.upgradeLabel.textContent = `Selected: ${info.type.toUpperCase()} Lv.${info.level}`;
		this.upgradeBtn.textContent = `Upgrade (💰 ${info.cost})`;
		this.upgradeBtn.disabled = !info.canAfford || info.cost === '-';
	}

	update(state) {
		window.dispatchEvent(new CustomEvent('td3d:state', { detail: state }));
		// Note: The index.php HUD spans are updated via global event listeners usually 
		// but I'll add the manual sync here too for robustness
		const g = document.getElementById('hud-gold');
		const e = document.getElementById('hud-elixir');
		const b = document.getElementById('hud-builders');
		const l = document.getElementById('hud-lives');
		const w = document.getElementById('hud-wave');
		if (g) g.textContent = this._fmt(state.gold);
		if (e) e.textContent = this._fmt(state.elixir);
		if (b) b.textContent = String(state.builders);
		if (l) l.textContent = String(state.lives);
		if (w) w.textContent = String(state.wave);
		this.updateUpgradeSlot();
	}

	_fmt(n) {
		if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
		return String(n);
	}

	showBuildHint(show) {
		this.hint.classList.toggle('show', show);
	}

	flashHint(text) {
		const old = this.hint.textContent;
		this.hint.textContent = text;
		this.hint.classList.add('show');
		this.hint.style.color = '#ef4444';
		setTimeout(() => {
			this.hint.textContent = old;
			this.hint.style.color = '';
			if (!this.hint.classList.contains('show-permanent')) {
				// We don't have show-permanent but we want to return to build hint if in build mode
			}
		}, 2000);
	}
}
