<script lang="ts">
	import { onMount } from 'svelte';
	import { invoke } from '@tauri-apps/api/core';
	import { emit } from '@tauri-apps/api/event';
	import IdePanel from './IdePanel.svelte';

	interface XvfbStatus {
		running: boolean;
		display_num: number;
		pid: number | null;
		resolution: string;
	}

	interface PlaywrightInfo {
		available: boolean;
		hint: string;
	}

	interface DesktopAction {
		id: string;
		name: string;
		icon: string;
		category: string;
		description: string;
	}

	let section = $state<'actions' | 'ide' | 'playwright' | 'dbus' | 'xvfb'>('actions');
	let actions = $state<DesktopAction[]>([]);
	let actionResult = $state<string | null>(null);
	let screenshotPreview = $state<string | null>(null);
	let screenshotCapturing = $state(false);

	let xvfb = $state<XvfbStatus>({ running: false, display_num: 1, pid: null, resolution: '1920x1080x24' });
	let playwright = $state<PlaywrightInfo>({ available: false, hint: '' });
	let dbusServices = $state<string[]>([]);
	let dbusLoading = $state(false);
	let screenshot = $state<string | null>(null);
	let errorMsg = $state<string | null>(null);

	async function copyError() {
		if (errorMsg) {
			try {
				await navigator.clipboard.writeText(errorMsg);
			} catch (e) {
				console.error('Clipboard:', e);
			}
		}
	}

	async function loadXvfb() {
		try {
			xvfb = await invoke<XvfbStatus>('xvfb_status');
		} catch (err) {
			console.error(err);
		}
	}

	async function startXvfb() {
		try {
			xvfb = await invoke<XvfbStatus>('xvfb_start', {
				displayNum: xvfb.display_num,
				resolution: xvfb.resolution
			});
		} catch (err) {
			errorMsg = String(err);
		}
	}

	async function stopXvfb() {
		try {
			xvfb = await invoke<XvfbStatus>('xvfb_stop');
			screenshot = null;
		} catch (err) {
			errorMsg = String(err);
		}
	}

	async function takeScreenshot() {
		try {
			const b64 = await invoke<string>('xvfb_screenshot', { displayNum: xvfb.display_num });
			screenshot = `data:image/png;base64,${b64}`;
		} catch (err) {
			errorMsg = String(err);
		}
	}

	async function loadPlaywright() {
		try {
			playwright = await invoke<PlaywrightInfo>('playwright_info');
		} catch {}
	}

	async function loadDbus() {
		dbusLoading = true;
		try {
			dbusServices = await invoke<string[]>('dbus_list_services', { session: true });
		} catch (err) {
			dbusServices = [];
			errorMsg = String(err);
		} finally {
			dbusLoading = false;
		}
	}

	async function loadActions() {
		try {
			actions = await invoke<DesktopAction[]>('dbus_list_actions');
		} catch (err) {
			console.error('Aktionen laden:', err);
		}
	}

	async function runAction(actionId: string, arg?: string) {
		actionResult = null;
		try {
			const result = await invoke<any>('dbus_run_action', {
				actionId,
				arg: arg || null,
			});
			actionResult = result.success
				? `✅ ${result.stdout || 'Erfolgreich'}`
				: `❌ ${result.stderr || 'Fehler'}`;
		} catch (err) {
			actionResult = `❌ ${err}`;
		}
		// Ergebnis nach 3s ausblenden
		setTimeout(() => { actionResult = null; }, 3000);
	}

	async function captureScreenshot(region: boolean = true) {
		screenshotCapturing = true;
		screenshotPreview = null;
		try {
			const b64 = await invoke<string>('capture_screenshot', { region });
			screenshotPreview = `data:image/png;base64,${b64}`;
		} catch (err) {
			errorMsg = String(err);
		} finally {
			screenshotCapturing = false;
		}
	}

	async function sendScreenshotToChat() {
		if (!screenshotPreview) return;
		// Ans ChatPanel senden über emit
		await emit('screenshot-to-chat', { image: screenshotPreview });
		actionResult = '✅ Screenshot an Chat gesendet';
		setTimeout(() => { actionResult = null; }, 2000);
	}

	onMount(() => {
		loadXvfb();
		loadPlaywright();
		loadActions();
	});
</script>

<div class="programs-panel">
	<div class="section-tabs">
		<button class:active={section === 'actions'} onclick={() => (section = 'actions')}>⚡ Aktionen</button>
		<button class:active={section === 'ide'} onclick={() => (section = 'ide')}>🧩 VSCodium</button>
		<button class:active={section === 'playwright'} onclick={() => (section = 'playwright')}>🎭 Playwright</button>
		<button class:active={section === 'dbus'} onclick={() => (section = 'dbus')}>🔌 D-Bus</button>
		<button class:active={section === 'xvfb'} onclick={() => (section = 'xvfb')}>🖥️ Xvfb</button>
	</div>

	{#if errorMsg}
		<div class="error-banner">
			<div class="error-header">
				<span>⚠️ Fehler</span>
				<div class="error-actions">
					<button onclick={copyError} title="In Zwischenablage kopieren">📋 Kopieren</button>
					<button onclick={() => (errorMsg = null)} title="Schließen">✕</button>
				</div>
			</div>
			<pre class="error-text">{errorMsg}</pre>
		</div>
	{/if}

	<div class="section-body">
		{#if section === 'actions'}
			<h3>⚡ Desktop-Aktionen</h3>
			{#if actionResult}
				<div class="action-result">{actionResult}</div>
			{/if}
			<div class="actions-grid">
				{#each actions as action}
					<button class="action-card" onclick={() => runAction(action.id)} title={action.description}>
						<span class="action-icon">{action.icon}</span>
						<span class="action-name">{action.name}</span>
						<span class="action-cat">{action.category}</span>
					</button>
				{/each}
			</div>
			<!-- Screenshot-Analyse -->
			<h3 style="margin-top: var(--spacing-md);">📸 Screenshot-Analyse</h3>
			<div class="screenshot-controls">
				<button class="btn-screenshot" onclick={() => captureScreenshot(true)} disabled={screenshotCapturing}>
					{screenshotCapturing ? '⏳ Auswählen...' : '📐 Bereich markieren'}
				</button>
				<button class="btn-screenshot secondary" onclick={() => captureScreenshot(false)} disabled={screenshotCapturing}>
					🖥️ Ganzer Bildschirm
				</button>
			</div>
			{#if screenshotPreview}
				<div class="screenshot-preview">
					<img src={screenshotPreview} alt="Screenshot" />
					<div class="screenshot-actions">
						<button onclick={sendScreenshotToChat}>💬 An Claude senden</button>
						<button onclick={() => screenshotPreview = null}>✕ Verwerfen</button>
					</div>
				</div>
			{/if}
			<div class="hint">
				Claude kann diese Aktionen auch direkt im Chat nutzen.
				Screenshots werden als Bild an Claude gesendet — ideal zum UI-Debuggen.
			</div>
		{:else if section === 'ide'}
			<IdePanel />
		{:else if section === 'playwright'}
			<h3>🎭 Playwright (Browser-Automation)</h3>
			<div class="info-card">
				<strong>Status:</strong>
				{playwright.available ? '✅ MCP-Server konfiguriert' : '⚠️ Nicht verfügbar'}
			</div>
			<div class="hint">{playwright.hint}</div>
		{:else if section === 'dbus'}
			<h3>🔌 D-Bus Services</h3>
			<div class="controls">
				<button onclick={loadDbus} disabled={dbusLoading}>
					{dbusLoading ? 'Lade...' : 'Services laden'}
				</button>
			</div>
			{#if dbusServices.length > 0}
				<ul class="dbus-list">
					{#each dbusServices as svc}
						<li>{svc}</li>
					{/each}
				</ul>
			{:else}
				<div class="empty">Noch keine Services geladen.</div>
			{/if}
			<div class="hint">
				Aufruf via Chat: Claude kann <code>dbus_call(service, path, method)</code> nutzen.
			</div>
		{:else if section === 'xvfb'}
			<h3>🖥️ Virtuelles Display (Xvfb)</h3>
			<div class="info-card" class:running={xvfb.running}>
				{xvfb.running ? `✅ Läuft auf :${xvfb.display_num} (PID ${xvfb.pid})` : '⚠️ Nicht aktiv'}
			</div>
			<div class="controls">
				<label>
					Display:
					<input type="number" bind:value={xvfb.display_num} disabled={xvfb.running} />
				</label>
				<label>
					Auflösung:
					<input bind:value={xvfb.resolution} disabled={xvfb.running} />
				</label>
				{#if xvfb.running}
					<button onclick={stopXvfb}>Stopp</button>
					<button onclick={takeScreenshot}>📸 Screenshot</button>
				{:else}
					<button onclick={startXvfb} class="primary">Start</button>
				{/if}
			</div>
			{#if screenshot}
				<img src={screenshot} alt="Xvfb Screenshot" class="screenshot" />
			{/if}
			<div class="hint">
				Starte Programme auf diesem Display via
				<code>DISPLAY=:1 firefox</code>. Claude kann Screenshots aufnehmen.
			</div>
		{/if}
	</div>
</div>

<style>
	.programs-panel {
		display: flex;
		flex-direction: column;
		height: 100%;
		overflow: hidden;
	}

	.section-tabs {
		display: flex;
		gap: 2px;
		padding: var(--spacing-xs);
		background: var(--bg-secondary);
		border-bottom: 1px solid var(--bg-tertiary);
	}

	.section-tabs button {
		flex: 1;
		padding: 4px 8px;
		font-size: 0.78rem;
		background: transparent;
		border: none;
		color: var(--text-secondary);
		cursor: pointer;
		border-radius: var(--radius-sm);
	}

	.section-tabs button.active {
		background: var(--accent);
		color: white;
	}

	.section-body {
		flex: 1;
		overflow-y: auto;
		padding: var(--spacing-md);
	}

	h3 {
		margin: 0 0 var(--spacing-sm) 0;
		font-size: 0.95rem;
	}

	.info-card {
		padding: var(--spacing-sm);
		background: var(--bg-secondary);
		border-radius: var(--radius-sm);
		margin-bottom: var(--spacing-sm);
		font-size: 0.85rem;
	}

	.info-card.running {
		background: rgba(34, 197, 94, 0.12);
		color: #22c55e;
	}

	.controls {
		display: flex;
		flex-wrap: wrap;
		gap: var(--spacing-sm);
		margin-bottom: var(--spacing-sm);
		align-items: center;
		font-size: 0.82rem;
	}

	.controls input {
		width: 140px;
		padding: 2px 6px;
	}

	.controls button {
		padding: 6px 14px;
		cursor: pointer;
		background: var(--bg-tertiary);
		color: var(--text-primary);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		font-size: 0.85rem;
		font-weight: 500;
		transition: background 0.15s, border-color 0.15s;
	}

	.controls button:hover:not(:disabled) {
		background: var(--accent);
		color: white;
		border-color: var(--accent);
	}

	.controls button:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.controls button.primary {
		background: var(--accent);
		color: white;
		border: 1px solid var(--accent);
	}

	.controls button.primary:hover:not(:disabled) {
		filter: brightness(1.15);
	}

	.dbus-list {
		list-style: none;
		padding: 0;
		margin: 0;
		font-family: monospace;
		font-size: 0.75rem;
		max-height: 260px;
		overflow-y: auto;
	}

	.dbus-list li {
		padding: 2px var(--spacing-xs);
		border-bottom: 1px solid var(--bg-tertiary);
	}

	.screenshot {
		max-width: 100%;
		border: 1px solid var(--bg-tertiary);
		border-radius: var(--radius-sm);
		margin-top: var(--spacing-sm);
	}

	.hint {
		font-size: 0.75rem;
		color: var(--text-secondary);
		margin-top: var(--spacing-sm);
		line-height: 1.4;
	}

	.hint code {
		background: var(--bg-tertiary);
		padding: 1px 4px;
		border-radius: 2px;
	}

	/* Desktop-Aktionen Grid */
	.actions-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
		gap: var(--spacing-sm);
		margin-bottom: var(--spacing-md);
	}

	.action-card {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 4px;
		padding: var(--spacing-md) var(--spacing-sm);
		background: var(--bg-secondary);
		border: 1px solid transparent;
		border-radius: var(--radius-md);
		cursor: pointer;
		transition: all 0.15s;
	}

	.action-card:hover {
		background: var(--bg-tertiary);
		border-color: var(--accent);
		transform: translateY(-1px);
	}

	.action-icon {
		font-size: 1.5rem;
	}

	.action-name {
		font-size: 0.75rem;
		font-weight: 600;
		color: var(--text-primary);
		text-align: center;
	}

	.action-cat {
		font-size: 0.6rem;
		color: var(--text-secondary);
	}

	.action-result {
		padding: var(--spacing-sm);
		background: var(--bg-secondary);
		border-radius: var(--radius-sm);
		font-size: 0.8rem;
		margin-bottom: var(--spacing-sm);
		animation: fadeIn 0.2s;
	}

	@keyframes fadeIn {
		from { opacity: 0; transform: translateY(-4px); }
		to { opacity: 1; transform: translateY(0); }
	}

	/* Screenshot-Analyse */
	.screenshot-controls {
		display: flex;
		gap: var(--spacing-sm);
		margin-bottom: var(--spacing-sm);
	}

	.btn-screenshot {
		padding: var(--spacing-sm) var(--spacing-md);
		background: var(--accent);
		color: white;
		border: none;
		border-radius: var(--radius-sm);
		font-size: 0.8rem;
		font-weight: 600;
		cursor: pointer;
		transition: filter 0.15s;
	}

	.btn-screenshot:hover:not(:disabled) {
		filter: brightness(1.15);
	}

	.btn-screenshot:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.btn-screenshot.secondary {
		background: var(--bg-tertiary);
		color: var(--text-primary);
		border: 1px solid var(--border);
	}

	.screenshot-preview {
		margin-bottom: var(--spacing-sm);
		border: 1px solid var(--border);
		border-radius: var(--radius-md);
		overflow: hidden;
	}

	.screenshot-preview img {
		width: 100%;
		display: block;
	}

	.screenshot-actions {
		display: flex;
		gap: var(--spacing-sm);
		padding: var(--spacing-sm);
		background: var(--bg-secondary);
	}

	.screenshot-actions button {
		flex: 1;
		padding: var(--spacing-xs) var(--spacing-sm);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		background: var(--bg-tertiary);
		color: var(--text-primary);
		font-size: 0.75rem;
		font-weight: 500;
		cursor: pointer;
	}

	.screenshot-actions button:first-child {
		background: var(--accent);
		color: white;
		border-color: var(--accent);
	}

	.empty {
		color: var(--text-secondary);
		font-size: 0.8rem;
		font-style: italic;
	}

	.error-banner {
		margin: var(--spacing-sm);
		background: rgba(248, 113, 113, 0.08);
		border: 1px solid rgba(248, 113, 113, 0.4);
		border-radius: var(--radius-sm);
		overflow: hidden;
	}

	.error-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 4px var(--spacing-sm);
		background: rgba(248, 113, 113, 0.15);
		color: #f87171;
		font-weight: 600;
		font-size: 0.82rem;
	}

	.error-actions {
		display: flex;
		gap: var(--spacing-xs);
	}

	.error-actions button {
		background: transparent;
		border: 1px solid rgba(248, 113, 113, 0.4);
		color: #f87171;
		padding: 2px 8px;
		font-size: 0.75rem;
		cursor: pointer;
		border-radius: 3px;
	}

	.error-actions button:hover {
		background: rgba(248, 113, 113, 0.2);
	}

	.error-text {
		margin: 0;
		padding: var(--spacing-sm);
		font-family: monospace;
		font-size: 0.78rem;
		color: var(--text-primary);
		white-space: pre-wrap;
		word-break: break-word;
		max-height: 300px;
		overflow-y: auto;
		user-select: text;
	}
</style>
