<script lang="ts">
	const API = 'http://localhost:8080/api';

	let { data } = $props();

	let initialized = $state(false);
	let token = $state('');
	let services = $state<any[]>([]);
	let showForm = $state(false);

	$effect(() => {
		if (!initialized && data) {
			token = data.token;
			services = data.services ?? [];
			initialized = true;
			fetchMaintenances();
			fetchServerStats();
		}
	});
	let editingSvc: any = $state(null);
	let saving = $state(false);
	let formError = $state('');
	let testing = $state<Record<number, boolean>>({});
	let toggling = $state<Record<number, boolean>>({});

	// maintenance state
	let maintenances = $state<any[]>([]);
	let showMtnForm = $state(false);
	let editingMtn: any = $state(null);
	let mtnSaving = $state(false);
	let mtnFormError = $state('');

	// server health state
	let serverStats: { cpu_percent: number; memory_percent: number; disk_percent: number } | null = $state(null);
	let serverStatsLoading = $state(true);
	let serverStatsError = $state('');

	async function fetchServerStats() {
		serverStatsLoading = true;
		serverStatsError = '';
		try {
			const res = await fetch(`${API}/admin/server-stats`, { headers: { Authorization: `Bearer ${token}` } });
			if (await handleUnauthorized(res)) return;
			if (!res.ok) throw new Error('Erro ao carregar');
			serverStats = await res.json();
		} catch {
			serverStatsError = 'Falha ao carregar métricas do servidor';
		} finally {
			serverStatsLoading = false;
		}
	}

	function apiHeaders() {
		return { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
	}

	async function fetchMaintenances() {
		try {
			const res = await fetch(`${API}/maintenances`, { headers: { Authorization: `Bearer ${token}` } });
			if (await handleUnauthorized(res)) return;
			if (res.ok) maintenances = await res.json();
		} catch {}
	}

	async function handleUnauthorized(res: Response) {
		if (res.status === 401) {
			window.location.href = '/login';
			return true;
		}
		return false;
	}

	function openCreate() {
		editingSvc = null;
		formError = '';
		showForm = true;
	}

	function openEdit(svc: any) {
		editingSvc = { ...svc };
		formError = '';
		showForm = true;
	}

	function closeForm() {
		showForm = false;
		editingSvc = null;
		formError = '';
	}

	async function reFetch() {
		try {
			const res = await fetch(`${API}/services`, { headers: { Authorization: `Bearer ${token}` } });
			if (await handleUnauthorized(res)) return;
			if (res.ok) {
				const list = await res.json();
				const withStats = await Promise.all(
					list.map(async (svc: any) => {
						try {
							const sr = await fetch(`${API}/services/${svc.id}/stats`, {
								headers: { Authorization: `Bearer ${token}` }
							});
							if (sr.ok) svc.stats = await sr.json();
						} catch {}
						return svc;
					})
				);
				services = withStats;
			}
		} catch {}
	}

	async function handleSubmit(e: Event) {
		e.preventDefault();
		saving = true;
		formError = '';

		const form = e.target as HTMLFormElement;
		const fd = new FormData(form);

		const body: Record<string, any> = {
			name: fd.get('name'),
			url: fd.get('url'),
			group_name: (fd.get('group_name') as string) || 'Geral',
			interval_seconds: parseInt((fd.get('interval_seconds') as string) || '60', 10),
		};
		const keyword = fd.get('keyword_to_find') as string;
		if (keyword) body.keyword_to_find = keyword;
		const discord = fd.get('discord_webhook_url') as string;
		if (discord) body.discord_webhook_url = discord;
		const email = fd.get('alert_email') as string;
		if (email) body.alert_email = email;

		try {
			const id = fd.get('id');
			const method = id ? 'PUT' : 'POST';
			const url = id ? `${API}/services/${id}` : `${API}/services`;
			const res = await fetch(url, {
				method,
				headers: apiHeaders(),
				body: JSON.stringify(body),
			});
			if (await handleUnauthorized(res)) return;
			if (!res.ok) {
				const err = await res.json().catch(() => ({}));
				throw new Error(err.error || 'Erro ao salvar');
			}
			await reFetch();
			closeForm();
		} catch (e: any) {
			formError = e.message;
		} finally {
			saving = false;
		}
	}

	async function handleDelete(id: number) {
		try {
			const res = await fetch(`${API}/services/${id}`, {
				method: 'DELETE',
				headers: { Authorization: `Bearer ${token}` }
			});
			if (await handleUnauthorized(res)) return;
			if (res.ok) await reFetch();
		} catch {}
	}

	async function handleToggle(id: number) {
		toggling = { ...toggling, [id]: true };
		try {
			const res = await fetch(`${API}/services/${id}/toggle`, {
				method: 'PATCH',
				headers: { Authorization: `Bearer ${token}` }
			});
			if (await handleUnauthorized(res)) return;
			if (res.ok) {
				const updated = await res.json();
				services = services.map((s) => (s.id === id ? { ...s, ...updated } : s));
			}
		} catch { /* ignore */ }
		toggling = { ...toggling, [id]: false };
	}

	function openMtnCreate() {
		editingMtn = null;
		mtnFormError = '';
		showMtnForm = true;
	}

	function openMtnEdit(m: any) {
		editingMtn = { ...m };
		mtnFormError = '';
		showMtnForm = true;
	}

	function closeMtnForm() {
		showMtnForm = false;
		editingMtn = null;
		mtnFormError = '';
	}

	async function handleMtnSubmit(e: Event) {
		e.preventDefault();
		mtnSaving = true;
		mtnFormError = '';
		const form = e.target as HTMLFormElement;
		const fd = new FormData(form);
		const body: Record<string, any> = {
			title: fd.get('title'),
			start_time: fd.get('start_time'),
			end_time: fd.get('end_time'),
			is_active: fd.get('is_active') === 'on',
		};
		try {
			const id = fd.get('id');
			if (id) {
				const res = await fetch(`${API}/maintenances/${id}`, {
					method: 'PUT',
					headers: apiHeaders(),
					body: JSON.stringify(body),
				});
				if (await handleUnauthorized(res)) return;
				if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Erro ao salvar');
			} else {
				const res = await fetch(`${API}/maintenances`, {
					method: 'POST',
					headers: apiHeaders(),
					body: JSON.stringify({ title: body.title, start_time: body.start_time, end_time: body.end_time }),
				});
				if (await handleUnauthorized(res)) return;
				if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Erro ao salvar');
			}
			await fetchMaintenances();
			closeMtnForm();
		} catch (e: any) {
			mtnFormError = e.message;
		} finally {
			mtnSaving = false;
		}
	}

	async function handleMtnDelete(id: number) {
		try {
			const res = await fetch(`${API}/maintenances/${id}`, {
				method: 'DELETE',
				headers: apiHeaders()
			});
			if (await handleUnauthorized(res)) return;
			if (res.ok) await fetchMaintenances();
		} catch {}
	}

	async function handleTest(id: number) {
		testing = { ...testing, [id]: true };
		try {
			const res = await fetch(`${API}/services/${id}/test`, {
				method: 'POST',
				headers: { Authorization: `Bearer ${token}` }
			});
			if (await handleUnauthorized(res)) return;
			if (res.ok) {
				const hb = await res.json();
				services = services.map((s) =>
					s.id === id ? { ...s, last_heartbeat: hb } : s
				);
			}
		} catch { /* ignore */ }
		testing = { ...testing, [id]: false };
	}
</script>

<svelte:head>
	<title>Admin — YAUM</title>
</svelte:head>

<div class="mb-8 flex items-center justify-between">
	<div>
		<h1 class="text-2xl font-semibold tracking-tight text-white">Painel de Controle</h1>
		<p class="mt-1 text-sm text-[var(--text-muted)]">Gerenciamento de serviços monitorados</p>
	</div>
	<a
		href="/"
		class="text-xs text-[var(--text-muted)] underline transition-colors hover:text-white"
	>
		← Dashboard
	</a>
</div>

<!-- Saúde do Sistema -->
<div class="mb-8">
	<h2 class="mb-4 text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
		Saúde do Sistema
	</h2>
	{#if serverStatsLoading}
		<div class="grid grid-cols-3 gap-4">
			{#each ['CPU', 'RAM', 'Disco'] as label}
				<div class="rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] p-4">
					<p class="text-[10px] font-medium uppercase tracking-wider text-[var(--text-muted)]">{label}</p>
					<div class="mt-3 h-2 rounded-full bg-[var(--border-color)]"><div class="h-full w-1/3 rounded-full bg-[var(--border-color)]"></div></div>
					<p class="mt-2 text-right font-mono text-xs text-[var(--text-muted)]">…</p>
				</div>
			{/each}
		</div>
	{:else if serverStats}
		<div class="grid grid-cols-3 gap-4">
			{#each [
				{ label: 'CPU', pct: serverStats.cpu_percent },
				{ label: 'RAM', pct: serverStats.memory_percent },
				{ label: 'Disco', pct: serverStats.disk_percent },
			] as item}
				{@const color = item.pct >= 90 ? 'var(--red)' : item.pct >= 70 ? 'var(--amber)' : 'var(--green)'}
				<div class="rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] p-4">
					<div class="flex items-center justify-between">
						<p class="text-[10px] font-medium uppercase tracking-wider text-[var(--text-muted)]">{item.label}</p>
						<span class="font-mono text-lg font-bold tabular-nums" style="color: {color}">
							{item.pct.toFixed(1)}<span class="text-xs font-normal text-[var(--text-muted)]">%</span>
						</span>
					</div>
					<div class="mt-3 h-2 overflow-hidden rounded-full bg-[var(--border-color)]">
						<div
							class="h-full rounded-full transition-all duration-500"
							style="width: {Math.min(item.pct, 100)}%; background-color: {color};"
						></div>
					</div>
				</div>
			{/each}
		</div>
	{:else if serverStatsError}
		<div class="rounded-xl border border-[var(--red)]/20 bg-[var(--red)]/5 p-4 text-center">
			<p class="text-xs text-[var(--text-muted)]">{serverStatsError}</p>
		</div>
	{/if}
</div>

<div class="mb-8">
	<button
		onclick={openCreate}
		class="flex items-center gap-2 rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-4 py-2.5 text-sm font-medium text-[var(--text-primary)] transition-all hover:border-[var(--green)]/50 hover:text-[var(--green)] hover:shadow-[0_0_20px_rgba(34,240,106,0.08)]"
	>
		<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
			<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
		</svg>
		Novo Serviço
	</button>
</div>

{#if data.error}
	<div class="rounded-xl border border-[var(--red)]/20 bg-[var(--red)]/5 p-6 text-center">
		<p class="text-sm text-[var(--red)]">{data.error}</p>
	</div>
{:else if services.length === 0}
	<div class="rounded-xl border border-dashed border-[var(--border-color)] p-12 text-center">
		<p class="text-sm text-[var(--text-muted)]">Nenhum serviço cadastrado</p>
	</div>
{:else}
	{#each [...new Set(services.map((s) => s.group_name || 'Geral'))].sort() as group}
		<div class="mb-6">
			<h2 class="mb-3 text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">{group}</h2>
			<div class="overflow-hidden rounded-xl border border-[var(--border-color)]">
				<table class="w-full text-left text-sm">
					<thead>
						<tr class="border-b border-[var(--border-color)] bg-[var(--bg-secondary)]/30">
							<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">ID</th>
							<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Nome</th>
							<th class="hidden px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)] md:table-cell">URL</th>
							<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Status</th>
							<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">SLA 30d</th>
							<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Ações</th>
						</tr>
					</thead>
					<tbody>
						{#each services.filter((s) => (s.group_name || 'Geral') === group) as svc (svc.id)}
							<tr class="border-b border-[var(--border-color)] transition-colors hover:bg-[var(--bg-secondary)]/20">
						<td class="px-4 py-3 font-mono text-xs text-[var(--text-muted)]">{svc.id}</td>
						<td class="px-4 py-3 font-medium text-white">{svc.name}</td>
						<td class="hidden max-w-[200px] truncate px-4 py-3 font-mono text-xs text-[var(--text-muted)] md:table-cell">{svc.url}</td>
						<td class="px-4 py-3">
							<span
								class="inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[10px] font-semibold"
								style="background-color: {svc.last_heartbeat?.is_up ?? true ? 'rgba(34,240,106,0.1)' : 'rgba(255,64,96,0.1)'}; color: {svc.last_heartbeat?.is_up ?? true ? 'var(--green)' : 'var(--red)'}"
							>
								{svc.last_heartbeat?.is_up ?? true ? 'UP' : 'DOWN'}
							</span>
						</td>
						<td class="px-4 py-3 font-mono text-xs tabular-nums">
							{svc.stats ? svc.stats.uptime_30d.toFixed(2) + '%' : '—'}
						</td>
						<td class="px-4 py-3">
							<div class="flex flex-wrap gap-1.5">
								<button
									onclick={() => openEdit(svc)}
									class="rounded-lg px-2.5 py-1 text-[10px] font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--border-color)] hover:text-white"
								>
									Editar
								</button>
								<button
									onclick={() => handleToggle(svc.id)}
									disabled={toggling[svc.id] ?? false}
									class="rounded-lg px-2.5 py-1 text-[10px] font-medium transition-colors"
									style="color: {svc.is_active ?? true ? 'var(--green)' : 'var(--red)'}; {(svc.is_active ?? true) ? 'border:1px solid rgba(34,240,106,0.3)' : 'border:1px solid rgba(255,64,96,0.3)'}; {toggling[svc.id] ? 'opacity:0.5' : ''}"
								>
									{svc.is_active ?? true ? 'Ativo' : 'Pausado'}
								</button>
								<button
									onclick={() => handleTest(svc.id)}
									disabled={testing[svc.id] ?? false}
									class="rounded-lg px-2.5 py-1 text-[10px] font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--border-color)] hover:text-white"
									style={testing[svc.id] ? 'opacity:0.5' : ''}
								>
									{testing[svc.id] ? '...' : 'Testar'}
								</button>
								<button
									onclick={() => handleDelete(svc.id)}
									class="rounded-lg px-2.5 py-1 text-[10px] font-medium text-[var(--red)] transition-colors hover:bg-[var(--red)]/10"
								>
									Excluir
								</button>
							</div>
						</td>
					</tr>
				{/each}
			</tbody>
		</table>
	</div>
	</div>
	{/each}
{/if}

<div class="mb-8 mt-12 border-t border-[var(--border-color)] pt-8">
	<div class="mb-6 flex items-center justify-between">
		<div>
			<h2 class="text-sm font-semibold uppercase tracking-wider text-[var(--text-secondary)]">Manutenções Programadas</h2>
			<p class="mt-0.5 text-xs text-[var(--text-muted)]">Janelas de manutenção exibem um aviso no topo do site</p>
		</div>
		<button
			onclick={openMtnCreate}
			class="flex items-center gap-2 rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-4 py-2 text-sm font-medium text-[var(--text-primary)] transition-all hover:border-[var(--green)]/50 hover:text-[var(--green)]"
		>
			<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
				<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
			</svg>
			Nova Manutenção
		</button>
	</div>

	{#if maintenances.length === 0}
		<div class="rounded-xl border border-dashed border-[var(--border-color)] p-8 text-center">
			<p class="text-xs text-[var(--text-muted)]">Nenhuma manutenção agendada</p>
		</div>
	{:else}
		<div class="overflow-hidden rounded-xl border border-[var(--border-color)]">
			<table class="w-full text-left text-sm">
				<thead>
					<tr class="border-b border-[var(--border-color)] bg-[var(--bg-secondary)]/30">
						<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Título</th>
						<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Início</th>
						<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Fim</th>
						<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Ativa</th>
						<th class="px-4 py-3 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">Ações</th>
					</tr>
				</thead>
				<tbody>
					{#each maintenances as mtn (mtn.id)}
						<tr class="border-b border-[var(--border-color)] transition-colors hover:bg-[var(--bg-secondary)]/20">
							<td class="px-4 py-3 font-medium text-white">{mtn.title}</td>
							<td class="px-4 py-3 font-mono text-xs text-[var(--text-muted)]">{new Date(mtn.start_time).toLocaleString('pt-BR')}</td>
							<td class="px-4 py-3 font-mono text-xs text-[var(--text-muted)]">{new Date(mtn.end_time).toLocaleString('pt-BR')}</td>
							<td class="px-4 py-3">
								<span
									class="inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[10px] font-semibold"
									style="background-color: {mtn.is_active ? 'rgba(34,240,106,0.1)' : 'rgba(255,64,96,0.1)'}; color: {mtn.is_active ? 'var(--green)' : 'var(--red)'}"
								>
									{mtn.is_active ? 'Sim' : 'Não'}
								</span>
							</td>
							<td class="px-4 py-3">
								<div class="flex gap-1.5">
									<button
										onclick={() => openMtnEdit(mtn)}
										class="rounded-lg px-2.5 py-1 text-[10px] font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--border-color)] hover:text-white"
									>
										Editar
									</button>
									<button
										onclick={() => handleMtnDelete(mtn.id)}
										class="rounded-lg px-2.5 py-1 text-[10px] font-medium text-[var(--red)] transition-colors hover:bg-[var(--red)]/10"
									>
										Excluir
									</button>
								</div>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	{/if}
</div>

<!-- Modal create / edit service -->
{#if showForm}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<div
		role="button"
		tabindex="-1"
		aria-label="Fechar"
		class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
		onclick={closeForm}
	>
		<div
			class="w-full max-w-md animate-[modalIn_0.2s_ease-out] rounded-2xl border border-[var(--border-color)] bg-[var(--bg-secondary)] p-6 shadow-2xl"
			onclick={(e) => e.stopPropagation()}
		>
			<div class="mb-5 flex items-center justify-between">
				<h2 class="text-sm font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
					{editingSvc ? 'Editar Serviço' : 'Novo Serviço'}
				</h2>
				<button
					onclick={closeForm}
					class="rounded-lg p-1.5 text-[var(--text-muted)] transition-colors hover:bg-[var(--border-color)] hover:text-white"
					aria-label="Fechar"
				>
					<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
						<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
					</svg>
				</button>
			</div>

			<form onsubmit={handleSubmit} class="space-y-4">
				{#if editingSvc}
					<input type="hidden" name="id" value={editingSvc.id} />
				{/if}

				<div>
					<label for="admin-name" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Nome do Serviço</label>
					<input
						id="admin-name"
						name="name"
						type="text"
						value={editingSvc?.name ?? ''}
						required
						placeholder="Meu Site"
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div>
					<label for="admin-url" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">URL</label>
					<input
						id="admin-url"
						name="url"
						type="url"
						value={editingSvc?.url ?? ''}
						required
						placeholder="https://exemplo.com"
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div>
					<label for="admin-group" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Grupo / Categoria</label>
					<input
						id="admin-group"
						name="group_name"
						type="text"
						value={editingSvc?.group_name ?? 'Geral'}
						placeholder="APIs, Websites, Servidores..."
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div>
					<label for="admin-interval" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Intervalo (segundos)</label>
					<input
						id="admin-interval"
						name="interval_seconds"
						type="number"
						value={editingSvc?.interval_seconds ?? 60}
						min="10"
						max="3600"
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div class="border-t border-[var(--border-color)] pt-4">
					<p class="mb-3 text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)]">Opcionais</p>

					<div>
						<label for="admin-keyword" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Palavra-chave</label>
						<input
							id="admin-keyword"
							name="keyword_to_find"
							type="text"
							value={editingSvc?.keyword_to_find ?? ''}
							placeholder="Bem-vindo, Login..."
							class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
						/>
					</div>

					<div class="mt-3">
						<label for="admin-webhook" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Webhook Discord</label>
						<input
							id="admin-webhook"
							name="discord_webhook_url"
							type="url"
							value={editingSvc?.discord_webhook_url ?? ''}
							placeholder="https://discord.com/api/webhooks/..."
							class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
						/>
					</div>

					<div class="mt-3">
						<label for="admin-email" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">E-mail de Alerta</label>
						<input
							id="admin-email"
							name="alert_email"
							type="email"
							value={editingSvc?.alert_email ?? ''}
							placeholder="admin@exemplo.com"
							class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
						/>
					</div>
				</div>

				{#if formError}
					<p class="rounded-lg bg-[var(--red)]/5 px-3 py-2 text-xs text-[var(--red)]">{formError}</p>
				{/if}

				<div class="flex gap-3 pt-1">
					<button
						type="button"
						onclick={closeForm}
						class="flex-1 rounded-xl border border-[var(--border-color)] px-4 py-2.5 text-sm font-medium text-[var(--text-muted)] transition-colors hover:border-[var(--text-muted)]/30 hover:text-white"
					>
						Cancelar
					</button>
					<button
						type="submit"
						disabled={saving}
						class="flex-1 rounded-xl border border-[var(--green)] bg-[var(--green)]/10 px-4 py-2.5 text-sm font-medium text-[var(--green)] transition-all hover:bg-[var(--green)]/20 disabled:cursor-not-allowed disabled:opacity-40"
					>
						{saving ? 'Salvando…' : editingSvc ? 'Salvar' : 'Adicionar'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Modal create / edit maintenance -->
{#if showMtnForm}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<div
		role="button"
		tabindex="-1"
		aria-label="Fechar"
		class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
		onclick={closeMtnForm}
	>
		<div
			class="w-full max-w-md animate-[modalIn_0.2s_ease-out] rounded-2xl border border-[var(--border-color)] bg-[var(--bg-secondary)] p-6 shadow-2xl"
			onclick={(e) => e.stopPropagation()}
		>
			<div class="mb-5 flex items-center justify-between">
				<h2 class="text-sm font-semibold uppercase tracking-wider text-[var(--text-secondary)]">
					{editingMtn ? 'Editar Manutenção' : 'Nova Manutenção'}
				</h2>
				<button
					onclick={closeMtnForm}
					class="rounded-lg p-1.5 text-[var(--text-muted)] transition-colors hover:bg-[var(--border-color)] hover:text-white"
					aria-label="Fechar"
				>
					<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
						<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
					</svg>
				</button>
			</div>

			<form onsubmit={handleMtnSubmit} class="space-y-4">
				{#if editingMtn}
					<input type="hidden" name="id" value={editingMtn.id} />
				{/if}

				<div>
					<label for="mtn-title" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Título</label>
					<input
						id="mtn-title"
						name="title"
						type="text"
						value={editingMtn?.title ?? ''}
						required
						placeholder="Manutenção nos servidores"
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all placeholder:text-[var(--text-muted)] focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div>
					<label for="mtn-start" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Início</label>
					<input
						id="mtn-start"
						name="start_time"
						type="datetime-local"
						value={editingMtn ? editingMtn.start_time.slice(0, 16) : ''}
						required
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div>
					<label for="mtn-end" class="mb-1.5 block text-xs font-medium text-[var(--text-secondary)]">Fim</label>
					<input
						id="mtn-end"
						name="end_time"
						type="datetime-local"
						value={editingMtn ? editingMtn.end_time.slice(0, 16) : ''}
						required
						class="w-full rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2.5 text-sm text-white outline-none transition-all focus:border-[var(--green)]/50 focus:ring-1 focus:ring-[var(--green)]/20"
					/>
				</div>

				<div>
					<label class="flex items-center gap-3">
						<input
							type="checkbox"
							name="is_active"
							checked={editingMtn?.is_active ?? true}
							class="h-4 w-4 rounded border-[var(--border-color)] bg-[var(--bg-card)] text-[var(--green)] focus:ring-[var(--green)]/30"
						/>
						<span class="text-xs font-medium text-[var(--text-secondary)]">Ativa</span>
					</label>
				</div>

				{#if mtnFormError}
					<p class="rounded-lg bg-[var(--red)]/5 px-3 py-2 text-xs text-[var(--red)]">{mtnFormError}</p>
				{/if}

				<div class="flex gap-3 pt-1">
					<button
						type="button"
						onclick={closeMtnForm}
						class="flex-1 rounded-xl border border-[var(--border-color)] px-4 py-2.5 text-sm font-medium text-[var(--text-muted)] transition-colors hover:border-[var(--text-muted)]/30 hover:text-white"
					>
						Cancelar
					</button>
					<button
						type="submit"
						disabled={mtnSaving}
						class="flex-1 rounded-xl border border-[var(--green)] bg-[var(--green)]/10 px-4 py-2.5 text-sm font-medium text-[var(--green)] transition-all hover:bg-[var(--green)]/20 disabled:cursor-not-allowed disabled:opacity-40"
					>
						{mtnSaving ? 'Salvando…' : editingMtn ? 'Salvar' : 'Adicionar'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
<style>
	@keyframes modalIn {
		from { opacity: 0; transform: scale(0.95) translateY(-8px); }
		to   { opacity: 1; transform: scale(1) translateY(0); }
	}
</style>
