<script lang="ts">
	import { page } from '$app/stores';
	import { resolve } from '$app/paths';
	import { goto } from '$app/navigation';
	import { useQuery, useConvexClient } from 'convex-svelte';
	import { api } from '@sgse-app/backend/convex/_generated/api';
	import type { Id } from '@sgse-app/backend/convex/_generated/dataModel';
	import ActionGuard from '$lib/components/ActionGuard.svelte';
	import RelogioPrazo from '$lib/components/RelogioPrazo.svelte';

	const client = useConvexClient();
	const instanceId = $derived($page.params.id as Id<'flowInstances'>);

	// Query da instância com passos
	const instanceQuery = useQuery(api.flows.getInstanceWithSteps, () => ({ id: instanceId }));

	// Estado para query de usuários por setor
	let setorIdParaAtribuicao = $state<Id<'setores'> | null>(null);

	// Query de usuários por setor para atribuição (reativa baseada no setorId)
	const usuariosPorSetorQuery = useQuery(api.flows.getUsuariosBySetorForAssignment, () =>
		setorIdParaAtribuicao ? { setorId: setorIdParaAtribuicao } : 'skip'
	);

	// Estado de operações
	let isProcessing = $state(false);
	let processingError = $state<string | null>(null);

	// Estado de toast
	let toastMessage = $state<string | null>(null);
	let toastType = $state<'success' | 'error' | 'warning' | 'info'>('error');

	// Modal de reatribuição
	let showReassignModal = $state(false);
	let stepToReassign = $state<{ _id: Id<'flowInstanceSteps'>; stepName: string } | null>(null);
	let newAssigneeId = $state<Id<'usuarios'> | ''>('');

	// Modal de notas
	let showNotesModal = $state(false);
	let stepForNotes = $state<{
		_id: Id<'flowInstanceSteps'>;
		stepName: string;
		notes: string;
	} | null>(null);
	let editedNotes = $state('');

	// Modal de upload
	let showUploadModal = $state(false);
	let stepForUpload = $state<{ _id: Id<'flowInstanceSteps'>; stepName: string } | null>(null);
	let uploadFile = $state<File | null>(null);
	let isUploading = $state(false);

	// Modal de confirmação de cancelamento
	let showCancelModal = $state(false);

	// Estado de sub-etapas - carregar automaticamente para todos os passos
	let showSubEtapaModal = $state(false);
	let subEtapaNome = $state('');
	let subEtapaDescricao = $state('');
	let isCriandoSubEtapa = $state(false);
	let subEtapaError = $state<string | null>(null);
	let stepIdParaSubEtapas = $state<Id<'flowInstanceSteps'> | null>(null);

	// Modal de alterar gestor
	let showAlterarGestorModal = $state(false);
	let novoGestorId = $state<Id<'usuarios'> | ''>('');
	let isAlterandoGestor = $state(false);
	let alterarGestorError = $state<string | null>(null);

	// Query de usuários para seleção de gestor
	const usuariosQuery = useQuery(api.usuarios.listar, {});

	async function handleStartStep(stepId: Id<'flowInstanceSteps'>) {
		isProcessing = true;
		processingError = null;

		try {
			await client.mutation(api.flows.updateStepStatus, {
				instanceStepId: stepId,
				status: 'in_progress'
			});
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao iniciar passo';
		} finally {
			isProcessing = false;
		}
	}

	async function handleCompleteStep(stepId: Id<'flowInstanceSteps'>) {
		isProcessing = true;
		processingError = null;

		try {
			await client.mutation(api.flows.completeStep, {
				instanceStepId: stepId
			});
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao completar passo';
		} finally {
			isProcessing = false;
		}
	}

	async function handleBlockStep(stepId: Id<'flowInstanceSteps'>) {
		isProcessing = true;
		processingError = null;

		try {
			await client.mutation(api.flows.updateStepStatus, {
				instanceStepId: stepId,
				status: 'blocked'
			});
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao bloquear passo';
		} finally {
			isProcessing = false;
		}
	}

	function openReassignModal(step: {
		_id: Id<'flowInstanceSteps'>;
		stepName: string;
		assignedToId?: Id<'usuarios'>;
		setorId: Id<'setores'>;
	}) {
		stepToReassign = step;
		newAssigneeId = step.assignedToId ?? '';
		setorIdParaAtribuicao = step.setorId;
		showReassignModal = true;
	}

	function closeReassignModal() {
		showReassignModal = false;
		stepToReassign = null;
		newAssigneeId = '';
		setorIdParaAtribuicao = null;
	}

	async function handleReassign() {
		if (!stepToReassign || !newAssigneeId) return;

		isProcessing = true;
		processingError = null;
		toastMessage = null;

		try {
			await client.mutation(api.flows.reassignStep, {
				instanceStepId: stepToReassign._id,
				assignedToId: newAssigneeId as Id<'usuarios'>
			});
			toastMessage = 'Responsável atribuído com sucesso';
			toastType = 'success';
			closeReassignModal();
			// Limpar toast após 3 segundos
			setTimeout(() => {
				toastMessage = null;
			}, 3000);
		} catch (e) {
			const errorMessage = e instanceof Error ? e.message : 'Erro ao reatribuir passo';
			processingError = errorMessage;
			toastMessage = errorMessage;
			toastType = 'error';
			// Limpar toast após 5 segundos
			setTimeout(() => {
				toastMessage = null;
			}, 5000);
		} finally {
			isProcessing = false;
		}
	}

	function openNotesModal(step: {
		_id: Id<'flowInstanceSteps'>;
		stepName: string;
		notes?: string;
	}) {
		stepForNotes = { ...step, notes: step.notes ?? '' };
		editedNotes = step.notes ?? '';
		showNotesModal = true;
	}

	function closeNotesModal() {
		showNotesModal = false;
		stepForNotes = null;
		editedNotes = '';
	}

	async function handleSaveNotes() {
		if (!stepForNotes) return;

		isProcessing = true;
		processingError = null;

		try {
			await client.mutation(api.flows.updateStepNotes, {
				instanceStepId: stepForNotes._id,
				notes: editedNotes
			});
			closeNotesModal();
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao salvar notas';
		} finally {
			isProcessing = false;
		}
	}

	function openUploadModal(step: { _id: Id<'flowInstanceSteps'>; stepName: string }) {
		stepForUpload = step;
		uploadFile = null;
		showUploadModal = true;
	}

	function closeUploadModal() {
		showUploadModal = false;
		stepForUpload = null;
		uploadFile = null;
	}

	function handleFileSelect(event: Event) {
		const input = event.target as HTMLInputElement;
		if (input.files && input.files.length > 0) {
			uploadFile = input.files[0];
		}
	}

	async function handleUpload() {
		if (!stepForUpload || !uploadFile) return;

		isUploading = true;
		processingError = null;

		try {
			// Gerar URL de upload
			const uploadUrl = await client.mutation(api.flows.generateUploadUrl, {});

			// Fazer upload do arquivo
			const response = await fetch(uploadUrl, {
				method: 'POST',
				headers: { 'Content-Type': uploadFile.type },
				body: uploadFile
			});

			if (!response.ok) {
				throw new Error('Falha no upload do arquivo');
			}

			const { storageId } = await response.json();

			// Registrar o documento
			await client.mutation(api.flows.registerDocument, {
				flowInstanceStepId: stepForUpload._id,
				storageId,
				name: uploadFile.name
			});

			closeUploadModal();
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao fazer upload';
		} finally {
			isUploading = false;
		}
	}

	async function handleDeleteDocument(documentId: Id<'flowInstanceDocuments'>) {
		isProcessing = true;
		processingError = null;

		try {
			await client.mutation(api.flows.deleteDocument, { id: documentId });
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao excluir documento';
		} finally {
			isProcessing = false;
		}
	}

	async function handleCancelInstance() {
		isProcessing = true;
		processingError = null;

		try {
			await client.mutation(api.flows.cancelInstance, { id: instanceId });
			showCancelModal = false;
		} catch (e) {
			processingError = e instanceof Error ? e.message : 'Erro ao cancelar instância';
		} finally {
			isProcessing = false;
		}
	}

	function getStatusBadge(status: 'pending' | 'in_progress' | 'completed' | 'blocked') {
		switch (status) {
			case 'pending':
				return { class: 'badge-ghost', label: 'Pendente', icon: 'clock' };
			case 'in_progress':
				return { class: 'badge-info', label: 'Em Progresso', icon: 'play' };
			case 'completed':
				return { class: 'badge-success', label: 'Concluído', icon: 'check' };
			case 'blocked':
				return { class: 'badge-error', label: 'Bloqueado', icon: 'x' };
		}
	}

	function getInstanceStatusBadge(status: 'active' | 'completed' | 'cancelled') {
		switch (status) {
			case 'active':
				return { class: 'badge-info', label: 'Em Andamento' };
			case 'completed':
				return { class: 'badge-success', label: 'Concluído' };
			case 'cancelled':
				return { class: 'badge-error', label: 'Cancelado' };
		}
	}

	function formatDate(timestamp: number | undefined): string {
		if (!timestamp) return '-';
		return new Date(timestamp).toLocaleDateString('pt-BR', {
			day: '2-digit',
			month: '2-digit',
			year: 'numeric',
			hour: '2-digit',
			minute: '2-digit'
		});
	}

	function isStepCurrent(stepId: Id<'flowInstanceSteps'>): boolean {
		return instanceQuery.data?.instance.currentStepId === stepId;
	}

	function isOverdue(dueDate: number | undefined): boolean {
		if (!dueDate) return false;
		return Date.now() > dueDate;
	}

	function openAlterarGestorModal() {
		novoGestorId = '';
		alterarGestorError = null;
		showAlterarGestorModal = true;
	}

	function closeAlterarGestorModal() {
		showAlterarGestorModal = false;
		novoGestorId = '';
		alterarGestorError = null;
	}

	async function handleAlterarGestor() {
		if (!novoGestorId || !instanceId) return;

		isAlterandoGestor = true;
		alterarGestorError = null;
		toastMessage = null;

		try {
			await client.mutation(api.flows.alterarGestorFluxo, {
				flowInstanceId: instanceId,
				novoManagerId: novoGestorId as Id<'usuarios'>
			});
			toastMessage = 'Gestor alterado com sucesso';
			toastType = 'success';
			closeAlterarGestorModal();
			setTimeout(() => {
				toastMessage = null;
			}, 3000);
		} catch (e) {
			const errorMessage = e instanceof Error ? e.message : 'Erro ao alterar gestor';
			alterarGestorError = errorMessage;
			toastMessage = errorMessage;
			toastType = 'error';
			setTimeout(() => {
				toastMessage = null;
			}, 5000);
		} finally {
			isAlterandoGestor = false;
		}
	}

	// Funções de sub-etapas
	function getFileIcon(fileName: string): string {
		const ext = fileName.split('.').pop()?.toLowerCase();
		if (['pdf'].includes(ext || ''))
			return 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z';
		if (['doc', 'docx'].includes(ext || ''))
			return 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z';
		if (['xls', 'xlsx'].includes(ext || ''))
			return 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z';
		if (['jpg', 'jpeg', 'png', 'gif'].includes(ext || ''))
			return 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z';
		return 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z';
	}

	function openSubEtapaModal(stepId: Id<'flowInstanceSteps'>) {
		stepIdParaSubEtapas = stepId;
		subEtapaNome = '';
		subEtapaDescricao = '';
		subEtapaError = null;
		showSubEtapaModal = true;
	}

	function closeSubEtapaModal() {
		showSubEtapaModal = false;
		subEtapaNome = '';
		subEtapaDescricao = '';
		subEtapaError = null;
	}

	async function handleCriarSubEtapa() {
		if (!stepIdParaSubEtapas || !subEtapaNome.trim()) {
			subEtapaError = 'O nome é obrigatório';
			return;
		}

		isCriandoSubEtapa = true;
		subEtapaError = null;

		try {
			await client.mutation(api.flows.criarSubEtapa, {
				flowInstanceStepId: stepIdParaSubEtapas,
				name: subEtapaNome.trim(),
				description: subEtapaDescricao.trim() || undefined
			});
			closeSubEtapaModal();
			toastMessage = 'Sub-etapa criada com sucesso';
			toastType = 'success';
			setTimeout(() => {
				toastMessage = null;
			}, 3000);
		} catch (e) {
			const errorMessage = e instanceof Error ? e.message : 'Erro ao criar sub-etapa';
			subEtapaError = errorMessage;
			toastMessage = errorMessage;
			toastType = 'error';
			setTimeout(() => {
				toastMessage = null;
			}, 5000);
		} finally {
			isCriandoSubEtapa = false;
		}
	}

	async function handleDeletarSubEtapa(subEtapaId: Id<'flowSubSteps'>) {
		if (!confirm('Tem certeza que deseja excluir esta sub-etapa?')) {
			return;
		}

		try {
			await client.mutation(api.flows.deletarSubEtapa, { subEtapaId });
			toastMessage = 'Sub-etapa excluída com sucesso';
			toastType = 'success';
			setTimeout(() => {
				toastMessage = null;
			}, 3000);
		} catch (e) {
			toastMessage = e instanceof Error ? e.message : 'Erro ao deletar sub-etapa';
			toastType = 'error';
			setTimeout(() => {
				toastMessage = null;
			}, 5000);
		}
	}

	async function handleAtualizarStatusSubEtapa(
		subEtapaId: Id<'flowSubSteps'>,
		novoStatus: 'pending' | 'in_progress' | 'completed' | 'blocked'
	) {
		try {
			await client.mutation(api.flows.atualizarSubEtapa, {
				subEtapaId,
				status: novoStatus
			});
		} catch (e) {
			toastMessage = e instanceof Error ? e.message : 'Erro ao atualizar status';
			toastType = 'error';
			setTimeout(() => {
				toastMessage = null;
			}, 5000);
		}
	}
</script>

<main class="mx-auto w-full max-w-7xl space-y-8 px-4 py-10">
	{#if instanceQuery.isLoading}
		<div class="flex items-center justify-center py-24">
			<span class="loading loading-spinner loading-lg text-info"></span>
		</div>
	{:else if !instanceQuery.data}
		<div class="flex flex-col items-center justify-center py-24 text-center">
			<svg
				xmlns="http://www.w3.org/2000/svg"
				class="text-base-content/30 h-16 w-16"
				fill="none"
				viewBox="0 0 24 24"
				stroke="currentColor"
				aria-hidden="true"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="1.5"
					d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
				/>
			</svg>
			<h3 class="text-base-content/70 mt-4 text-lg font-semibold">Fluxo não encontrado</h3>
			<a href={resolve('/(dashboard)/licitacoes/fluxos')} class="btn btn-ghost mt-4"
				>Voltar para lista</a
			>
		</div>
	{:else}
		{@const instance = instanceQuery.data.instance}
		{@const steps = instanceQuery.data.steps}
		{@const statusBadge = getInstanceStatusBadge(instance.status)}

		<!-- Header -->
		<section
			class="border-info/25 from-info/10 via-base-100 to-secondary/20 relative overflow-hidden rounded-3xl border bg-linear-to-br p-8 shadow-2xl"
		>
			<div class="bg-info/20 absolute top-10 -left-10 h-40 w-40 rounded-full blur-3xl"></div>
			<div
				class="bg-secondary/20 absolute right-0 -bottom-16 h-56 w-56 rounded-full blur-3xl"
			></div>
			<div class="relative z-10">
				<div class="mb-6 flex items-center gap-4">
					<button
						type="button"
						class="btn btn-ghost btn-sm"
						onclick={() => {
							if (typeof window !== 'undefined' && window.history.length > 1) {
								window.history.back();
							} else {
								goto(resolve('/licitacoes/fluxos'));
							}
						}}
						aria-label="Voltar para página anterior"
					>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-5 w-5"
							fill="none"
							viewBox="0 0 24 24"
							stroke="currentColor"
							aria-hidden="true"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M10 19l-7-7m0 0l7-7m-7 7h18"
							/>
						</svg>
						Voltar
					</button>
					<span class="badge {statusBadge.class} badge-lg">{statusBadge.label}</span>
				</div>

				<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
					<div class="max-w-3xl space-y-4">
						<h1 class="text-base-content text-3xl leading-tight font-black sm:text-4xl">
							{instance.templateName ?? 'Fluxo'}
						</h1>
						<div class="flex flex-wrap gap-4">
							{#if instance.contratoId}
								<div class="flex items-center gap-2">
									<span class="badge badge-outline">Contrato</span>
									<span class="text-base-content/70 font-medium">{instance.contratoId}</span>
								</div>
							{/if}
							<div class="text-base-content/60 flex items-center gap-2">
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-4 w-4"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
									/>
								</svg>
								<div class="flex items-center gap-2">
									<span>Gerente: {instance.managerName ?? '-'}</span>
									<button
										type="button"
										class="btn btn-ghost btn-xs"
										onclick={openAlterarGestorModal}
										aria-label="Alterar gestor"
									>
										<svg
											xmlns="http://www.w3.org/2000/svg"
											class="h-4 w-4"
											fill="none"
											viewBox="0 0 24 24"
											stroke="currentColor"
											aria-hidden="true"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
											/>
										</svg>
									</button>
								</div>
							</div>
							<div class="text-base-content/60 flex items-center gap-2">
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-4 w-4"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
									/>
								</svg>
								Iniciado: {formatDate(instance.startedAt)}
							</div>
							<div class="flex items-center gap-2">
								<RelogioPrazo
									dueDate={instance.finishedAt
										? undefined
										: instance.startedAt + instance.prazoTotalDias * 24 * 60 * 60 * 1000}
									startedAt={instance.startedAt}
									finishedAt={instance.finishedAt}
									status={instance.status === 'completed'
										? 'completed'
										: instance.status === 'active'
											? 'in_progress'
											: 'pending'}
									expectedDuration={instance.prazoTotalDias}
								/>
							</div>
						</div>
					</div>

					{#if instance.status === 'active'}
						<ActionGuard recurso="fluxos_instancias" acao="cancelar">
							<button class="btn btn-error btn-outline" onclick={() => (showCancelModal = true)}>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-5 w-5"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M6 18L18 6M6 6l12 12"
									/>
								</svg>
								Cancelar Fluxo
							</button>
						</ActionGuard>
					{/if}
				</div>
			</div>
		</section>

		<!-- Erro global -->
		{#if processingError}
			<div class="alert alert-error">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					class="h-6 w-6 shrink-0 stroke-current"
					fill="none"
					viewBox="0 0 24 24"
					aria-hidden="true"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<span>{processingError}</span>
				<button class="btn btn-ghost btn-sm" onclick={() => (processingError = null)}>Fechar</button
				>
			</div>
		{/if}

		<!-- Timeline de Passos -->
		<section class="bg-base-100 rounded-2xl border p-6 shadow-lg">
			<h2 class="mb-6 text-xl font-bold">Timeline do Fluxo</h2>

			<div class="space-y-6">
				{#each steps as step, index (step._id)}
					{@const stepStatus = getStatusBadge(step.status)}
					{@const isCurrent = isStepCurrent(step._id)}
					{@const overdue = step.status !== 'completed' && isOverdue(step.dueDate)}
					{@const subEtapasQuery = useQuery(api.flows.listarSubEtapas, () => ({
						flowInstanceStepId: step._id
					}))}
					{@const subEtapas = subEtapasQuery.data}
					{@const subEtapasCount = subEtapas?.length ?? 0}
					{@const subEtapasCompleted =
						subEtapas?.filter((s: { status: string }) => s.status === 'completed').length ?? 0}

					<div class="relative flex gap-6 {index < steps.length - 1 ? 'pb-6' : ''}">
						<!-- Linha conectora -->
						{#if index < steps.length - 1}
							<div
								class="absolute top-10 bottom-0 left-5 w-0.5 {step.status === 'completed'
									? 'bg-success'
									: 'bg-base-300'}"
							></div>
						{/if}

						<!-- Indicador de status -->
						<div
							class="z-10 flex h-10 w-10 shrink-0 items-center justify-center rounded-full {step.status ===
							'completed'
								? 'bg-success text-success-content'
								: isCurrent
									? 'bg-info text-info-content'
									: step.status === 'blocked'
										? 'bg-error text-error-content'
										: 'bg-base-300 text-base-content'}"
						>
							{#if step.status === 'completed'}
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-5 w-5"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M5 13l4 4L19 7"
									/>
								</svg>
							{:else if step.status === 'blocked'}
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-5 w-5"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									aria-hidden="true"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
									/>
								</svg>
							{:else}
								<span class="text-sm font-bold">{index + 1}</span>
							{/if}
						</div>

						<!-- Conteúdo do passo -->
						<div
							class="flex-1 rounded-xl border {isCurrent
								? 'border-info bg-info/5'
								: 'bg-base-200/50'} space-y-4 p-5"
						>
							<!-- Cabeçalho do Passo -->
							<div class="flex flex-wrap items-start justify-between gap-4">
								<div class="min-w-0 flex-1">
									<div class="mb-2 flex flex-wrap items-center gap-2">
										<h3 class="text-lg font-semibold">{step.stepName}</h3>
										<span class="badge {stepStatus.class} badge-sm">{stepStatus.label}</span>
										<RelogioPrazo
											dueDate={step.dueDate}
											startedAt={step.startedAt}
											finishedAt={step.finishedAt}
											status={step.status}
											expectedDuration={step.expectedDuration}
										/>
									</div>
									{#if step.stepDescription}
										<p class="text-base-content/70 mt-1 text-sm">{step.stepDescription}</p>
									{/if}
									<div class="text-base-content/60 mt-3 flex flex-wrap gap-4 text-xs">
										<span class="flex items-center gap-1.5">
											<svg
												xmlns="http://www.w3.org/2000/svg"
												class="h-4 w-4"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
												aria-hidden="true"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5"
												/>
											</svg>
											{step.setorNome ?? 'Setor não definido'}
										</span>
										{#if step.assignedToName}
											<span class="flex items-center gap-1.5">
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-4 w-4"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
													/>
												</svg>
												{step.assignedToName}
											</span>
										{/if}
										{#if step.dueDate}
											<span
												class="flex items-center gap-1.5 {overdue
													? 'text-warning font-medium'
													: ''}"
											>
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-4 w-4"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
													/>
												</svg>
												Prazo: {formatDate(step.dueDate)}
											</span>
										{/if}
									</div>
								</div>

								<!-- Ações do passo -->
								{#if instance.status === 'active'}
									<div class="flex flex-wrap gap-2">
										{#if step.status === 'pending'}
											<ActionGuard recurso="fluxos_instancias" acao="avancar_passo">
												<button
													class="btn btn-info btn-sm"
													onclick={() => handleStartStep(step._id)}
													disabled={isProcessing}
												>
													Iniciar
												</button>
											</ActionGuard>
										{:else if step.status === 'in_progress'}
											<ActionGuard recurso="fluxos_instancias" acao="avancar_passo">
												<button
													class="btn btn-success btn-sm"
													onclick={() => handleCompleteStep(step._id)}
													disabled={isProcessing}
												>
													Concluir
												</button>
												<button
													class="btn btn-warning btn-sm"
													onclick={() => handleBlockStep(step._id)}
													disabled={isProcessing}
												>
													Bloquear
												</button>
											</ActionGuard>
										{:else if step.status === 'blocked'}
											<ActionGuard recurso="fluxos_instancias" acao="avancar_passo">
												<button
													class="btn btn-info btn-sm"
													onclick={() => handleStartStep(step._id)}
													disabled={isProcessing}
												>
													Desbloquear
												</button>
											</ActionGuard>
										{/if}

										<ActionGuard recurso="fluxos_instancias" acao="atribuir_usuario">
											<button
												class="btn btn-ghost btn-sm"
												onclick={() => openReassignModal(step)}
												aria-label="Reatribuir responsável"
												title="Reatribuir responsável"
											>
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-4 w-4"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
													/>
												</svg>
											</button>
										</ActionGuard>
									</div>
								{/if}
							</div>

							<!-- Sub-etapas - Sempre Visível -->
							<div class="border-base-300 border-t pt-4">
								<div class="mb-3 flex items-center justify-between">
									<div class="flex items-center gap-2">
										<svg
											xmlns="http://www.w3.org/2000/svg"
											class="text-base-content/70 h-5 w-5"
											fill="none"
											viewBox="0 0 24 24"
											stroke="currentColor"
											aria-hidden="true"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
											/>
										</svg>
										<h4 class="text-base font-semibold">Sub-etapas</h4>
										{#if subEtapasCount > 0}
											<span class="badge badge-sm badge-info">
												{subEtapasCompleted} / {subEtapasCount} concluídas
											</span>
										{/if}
									</div>
									{#if instance.status === 'active'}
										<button
											type="button"
											class="btn btn-ghost btn-xs"
											onclick={() => openSubEtapaModal(step._id)}
											aria-label="Adicionar sub-etapa"
										>
											<svg
												xmlns="http://www.w3.org/2000/svg"
												class="h-4 w-4"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
												aria-hidden="true"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M12 4v16m8-8H4"
												/>
											</svg>
											Adicionar
										</button>
									{/if}
								</div>

								{#if subEtapasQuery.isLoading}
									<div class="flex items-center justify-center py-4">
										<span class="loading loading-spinner loading-sm"></span>
									</div>
								{:else if subEtapas && subEtapas.length > 0}
									<div class="space-y-2">
										{#each subEtapas as subEtapa (subEtapa._id)}
											<div
												class="border-base-300 bg-base-100 hover:bg-base-200 flex items-start gap-3 rounded-lg border p-3 transition-colors"
											>
												<div class="min-w-0 flex-1">
													<div class="mb-1 flex items-center gap-2">
														<div class="text-sm font-medium">{subEtapa.name}</div>
														<span
															class="badge badge-xs {subEtapa.status === 'completed'
																? 'badge-success'
																: subEtapa.status === 'in_progress'
																	? 'badge-info'
																	: subEtapa.status === 'blocked'
																		? 'badge-error'
																		: 'badge-ghost'}"
														>
															{subEtapa.status === 'completed'
																? 'Concluída'
																: subEtapa.status === 'in_progress'
																	? 'Em Andamento'
																	: subEtapa.status === 'blocked'
																		? 'Bloqueada'
																		: 'Pendente'}
														</span>
													</div>
													{#if subEtapa.description}
														<div class="text-base-content/60 mt-1 text-xs">
															{subEtapa.description}
														</div>
													{/if}
												</div>
												<div class="flex shrink-0 gap-2">
													{#if instance.status === 'active'}
														<select
															class="select select-xs select-bordered"
															value={subEtapa.status}
															onchange={(e) =>
																handleAtualizarStatusSubEtapa(
																	subEtapa._id,
																	e.currentTarget.value as
																		| 'pending'
																		| 'in_progress'
																		| 'completed'
																		| 'blocked'
																)}
														>
															<option value="pending">Pendente</option>
															<option value="in_progress">Em Andamento</option>
															<option value="completed">Concluída</option>
															<option value="blocked">Bloqueada</option>
														</select>
														<button
															type="button"
															class="btn btn-ghost btn-xs text-error"
															onclick={() => handleDeletarSubEtapa(subEtapa._id)}
															aria-label="Deletar sub-etapa"
														>
															<svg
																xmlns="http://www.w3.org/2000/svg"
																class="h-4 w-4"
																fill="none"
																viewBox="0 0 24 24"
																stroke="currentColor"
																aria-hidden="true"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M6 18L18 6M6 6l12 12"
																/>
															</svg>
														</button>
													{/if}
												</div>
											</div>
										{/each}
									</div>
								{:else}
									<div
										class="text-base-content/40 border-base-300 bg-base-200/50 rounded-lg border border-dashed p-4 text-center text-sm"
									>
										Nenhuma sub-etapa adicionada
									</div>
								{/if}
							</div>

							<!-- Seção de Documentos -->
							<div class="border-base-300 border-t pt-4">
								<div class="mb-3 flex items-center justify-between">
									<div class="flex items-center gap-2">
										<svg
											xmlns="http://www.w3.org/2000/svg"
											class="text-base-content/70 h-5 w-5"
											fill="none"
											viewBox="0 0 24 24"
											stroke="currentColor"
											aria-hidden="true"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
											/>
										</svg>
										<h4 class="text-base font-semibold">Documentos</h4>
										{#if step.documents && step.documents.length > 0}
											<span class="badge badge-sm badge-info">{step.documents.length}</span>
										{/if}
									</div>
									{#if instance.status === 'active'}
										<ActionGuard recurso="fluxos_documentos" acao="upload">
											<button
												class="btn btn-ghost btn-xs"
												onclick={() => openUploadModal(step)}
												aria-label="Upload de documento"
											>
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-4 w-4"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
													/>
												</svg>
												Enviar
											</button>
										</ActionGuard>
									{/if}
								</div>

								{#if step.documents && step.documents.length > 0}
									<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
										{#each step.documents as doc (doc._id)}
											<div
												class="border-base-300 bg-base-100 hover:bg-base-200 flex items-center gap-3 rounded-lg border p-3 transition-colors"
											>
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="text-base-content/60 h-5 w-5 shrink-0"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d={getFileIcon(doc.name)}
													/>
												</svg>
												<div class="min-w-0 flex-1">
													<div class="truncate text-sm font-medium" title={doc.name}>
														{doc.name}
													</div>
												</div>
												{#if instance.status === 'active'}
													<ActionGuard recurso="fluxos_documentos" acao="excluir">
														<button
															class="btn btn-ghost btn-xs text-error shrink-0"
															onclick={() => handleDeleteDocument(doc._id)}
															aria-label="Excluir documento {doc.name}"
														>
															<svg
																xmlns="http://www.w3.org/2000/svg"
																class="h-4 w-4"
																fill="none"
																viewBox="0 0 24 24"
																stroke="currentColor"
																aria-hidden="true"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M6 18L18 6M6 6l12 12"
																/>
															</svg>
														</button>
													</ActionGuard>
												{/if}
											</div>
										{/each}
									</div>
								{:else}
									<div
										class="text-base-content/40 border-base-300 bg-base-200/50 rounded-lg border border-dashed p-4 text-center text-sm"
									>
										Nenhum documento anexado
									</div>
								{/if}
							</div>

							<!-- Seção de Notas/Comentários -->
							<div class="border-base-300 border-t pt-4">
								<div class="mb-3 flex items-center justify-between">
									<div class="flex items-center gap-2">
										<svg
											xmlns="http://www.w3.org/2000/svg"
											class="text-base-content/70 h-5 w-5"
											fill="none"
											viewBox="0 0 24 24"
											stroke="currentColor"
											aria-hidden="true"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
											/>
										</svg>
										<h4 class="text-base font-semibold">Notas e Comentários</h4>
										{#if step.notes}
											<span class="badge badge-sm badge-info">Atualizado</span>
										{/if}
									</div>
									<button
										class="btn btn-ghost btn-xs"
										onclick={() => openNotesModal(step)}
										aria-label="Editar notas"
									>
										<svg
											xmlns="http://www.w3.org/2000/svg"
											class="h-4 w-4"
											fill="none"
											viewBox="0 0 24 24"
											stroke="currentColor"
											aria-hidden="true"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
											/>
										</svg>
										{step.notes ? 'Editar' : 'Adicionar'}
									</button>
								</div>

								{#if step.notes}
									<div class="bg-base-100 border-base-300 rounded-lg border p-4">
										<p class="text-base-content/80 text-sm leading-relaxed whitespace-pre-wrap">
											{step.notes}
										</p>
										{#if step.notesUpdatedByName || step.notesUpdatedAt}
											<div
												class="border-base-300 text-base-content/50 mt-3 flex items-center gap-2 border-t pt-3 text-xs"
											>
												<svg
													xmlns="http://www.w3.org/2000/svg"
													class="h-3 w-3"
													fill="none"
													viewBox="0 0 24 24"
													stroke="currentColor"
													aria-hidden="true"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
													/>
												</svg>
												{#if step.notesUpdatedByName}
													<span
														>Atualizado por <strong class="text-base-content/70"
															>{step.notesUpdatedByName}</strong
														></span
													>
												{/if}
												{#if step.notesUpdatedAt}
													<span class="text-base-content/40">•</span>
													<span>{formatDate(step.notesUpdatedAt)}</span>
												{/if}
											</div>
										{/if}
									</div>
								{:else}
									<div
										class="text-base-content/40 border-base-300 bg-base-200/50 rounded-lg border border-dashed p-4 text-center text-sm"
									>
										Nenhuma nota ou comentário adicionado
									</div>
								{/if}
							</div>

							<!-- Datas de início/fim -->
							{#if step.startedAt || step.finishedAt}
								<div
									class="text-base-content/50 border-base-300 flex flex-wrap gap-4 border-t pt-3 text-xs"
								>
									{#if step.startedAt}
										<span class="flex items-center gap-1">
											<svg
												xmlns="http://www.w3.org/2000/svg"
												class="h-3 w-3"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
												aria-hidden="true"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"
												/>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
												/>
											</svg>
											Iniciado: {formatDate(step.startedAt)}
										</span>
									{/if}
									{#if step.finishedAt}
										<span class="flex items-center gap-1">
											<svg
												xmlns="http://www.w3.org/2000/svg"
												class="h-3 w-3"
												fill="none"
												viewBox="0 0 24 24"
												stroke="currentColor"
												aria-hidden="true"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
												/>
											</svg>
											Concluído: {formatDate(step.finishedAt)}
										</span>
									{/if}
								</div>
							{/if}
						</div>
					</div>
				{/each}
			</div>
		</section>
	{/if}

	<!-- Modal de Alterar Gestor -->
	{#if showAlterarGestorModal}
		<div class="modal modal-open">
			<div class="modal-box">
				<h3 class="text-lg font-bold">Alterar Gestor do Fluxo</h3>
				<p class="text-base-content/60 mt-2">Selecione o novo gestor responsável por este fluxo</p>

				{#if alterarGestorError}
					<div class="alert alert-error mt-4">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-6 w-6 shrink-0 stroke-current"
							fill="none"
							viewBox="0 0 24 24"
							aria-hidden="true"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
							/>
						</svg>
						<span>{alterarGestorError}</span>
					</div>
				{/if}

				<div class="form-control mt-4">
					<label class="label" for="novo-gestor-select">
						<span class="label-text">Novo Gestor</span>
					</label>
					<select
						id="novo-gestor-select"
						bind:value={novoGestorId}
						class="select select-bordered w-full"
					>
						<option value="">Selecione um usuário</option>
						{#if usuariosQuery.data}
							{#each usuariosQuery.data as usuario (usuario._id)}
								<option value={usuario._id}>{usuario.nome}</option>
							{/each}
						{/if}
					</select>
				</div>

				<div class="modal-action">
					<button class="btn" onclick={closeAlterarGestorModal} disabled={isAlterandoGestor}>
						Cancelar
					</button>
					<button
						class="btn btn-primary"
						onclick={handleAlterarGestor}
						disabled={isAlterandoGestor || !novoGestorId}
					>
						{#if isAlterandoGestor}
							<span class="loading loading-spinner loading-sm"></span>
						{/if}
						Alterar
					</button>
				</div>
			</div>
			<button
				type="button"
				class="modal-backdrop"
				onclick={closeAlterarGestorModal}
				aria-label="Fechar modal"
			></button>
		</div>
	{/if}

	<!-- Modal de Nova Sub-etapa -->
	{#if showSubEtapaModal && stepIdParaSubEtapas}
		<div class="modal modal-open">
			<div class="modal-box">
				<h3 class="text-lg font-bold">Nova Sub-etapa</h3>

				{#if subEtapaError}
					<div class="alert alert-error mt-4">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-6 w-6 shrink-0 stroke-current"
							fill="none"
							viewBox="0 0 24 24"
							aria-hidden="true"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
							/>
						</svg>
						<span>{subEtapaError}</span>
					</div>
				{/if}

				<form
					onsubmit={(e) => {
						e.preventDefault();
						handleCriarSubEtapa();
					}}
					class="mt-4 space-y-4"
				>
					<div class="form-control">
						<label class="label" for="sub-etapa-nome">
							<span class="label-text">Nome da Sub-etapa</span>
						</label>
						<input
							type="text"
							id="sub-etapa-nome"
							bind:value={subEtapaNome}
							class="input input-bordered w-full"
							placeholder="Ex: Revisar documentação"
							required
						/>
					</div>

					<div class="form-control">
						<label class="label" for="sub-etapa-descricao">
							<span class="label-text">Descrição (opcional)</span>
						</label>
						<textarea
							id="sub-etapa-descricao"
							bind:value={subEtapaDescricao}
							class="textarea textarea-bordered w-full"
							placeholder="Descreva a sub-etapa..."
							rows="2"
						></textarea>
					</div>

					<div class="modal-action">
						<button
							type="button"
							class="btn"
							onclick={closeSubEtapaModal}
							disabled={isCriandoSubEtapa}
						>
							Cancelar
						</button>
						<button type="submit" class="btn btn-primary" disabled={isCriandoSubEtapa}>
							{#if isCriandoSubEtapa}
								<span class="loading loading-spinner loading-sm"></span>
							{/if}
							Criar Sub-etapa
						</button>
					</div>
				</form>
			</div>
			<button
				type="button"
				class="modal-backdrop"
				onclick={closeSubEtapaModal}
				aria-label="Fechar modal"
			></button>
		</div>
	{/if}

	<!-- Toast de Notificação -->
	{#if toastMessage}
		<div class="toast toast-top toast-end z-50">
			<div
				class="alert {toastType === 'error'
					? 'alert-error'
					: toastType === 'success'
						? 'alert-success'
						: toastType === 'warning'
							? 'alert-warning'
							: 'alert-info'}"
			>
				<span>{toastMessage}</span>
				<button
					type="button"
					class="btn btn-sm btn-ghost"
					onclick={() => (toastMessage = null)}
					aria-label="Fechar notificação"
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-4 w-4"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						aria-hidden="true"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M6 18L18 6M6 6l12 12"
						/>
					</svg>
				</button>
			</div>
		</div>
	{/if}
</main>

<!-- Modal de Reatribuição -->
{#if showReassignModal && stepToReassign}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-lg font-bold">Reatribuir Responsável</h3>
			<p class="text-base-content/60 mt-2">
				Selecione o novo responsável pelo passo <strong>{stepToReassign.stepName}</strong>
			</p>

			<div class="form-control mt-4">
				<label class="label" for="assignee-select">
					<span class="label-text">Responsável</span>
					<span class="label-text-alt text-base-content/60"
						>Apenas funcionários do setor do passo</span
					>
				</label>
				{#if usuariosPorSetorQuery.isLoading}
					<div class="flex items-center justify-center py-4">
						<span class="loading loading-spinner loading-sm"></span>
					</div>
				{:else if usuariosPorSetorQuery.data && usuariosPorSetorQuery.data.length > 0}
					<select
						id="assignee-select"
						bind:value={newAssigneeId}
						class="select select-bordered w-full"
					>
						<option value="">Selecione um usuário</option>
						{#each usuariosPorSetorQuery.data as usuario (usuario._id)}
							<option value={usuario._id}>{usuario.nome}</option>
						{/each}
					</select>
				{:else if usuariosPorSetorQuery.data && usuariosPorSetorQuery.data.length === 0}
					<div class="alert alert-warning">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-6 w-6 shrink-0 stroke-current"
							fill="none"
							viewBox="0 0 24 24"
							aria-hidden="true"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
							/>
						</svg>
						<span>Não há funcionários cadastrados neste setor</span>
					</div>
				{/if}
			</div>

			<div class="modal-action">
				<button class="btn" onclick={closeReassignModal} disabled={isProcessing}> Cancelar </button>
				<button
					class="btn btn-primary"
					onclick={handleReassign}
					disabled={isProcessing || !newAssigneeId}
				>
					{#if isProcessing}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					Reatribuir
				</button>
			</div>
		</div>
		<button
			type="button"
			class="modal-backdrop"
			onclick={closeReassignModal}
			aria-label="Fechar modal"
		></button>
	</div>
{/if}

<!-- Modal de Notas -->
{#if showNotesModal && stepForNotes}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-lg font-bold">Notas do Passo</h3>
			<p class="text-base-content/60 mt-2">
				Adicione ou edite notas para o passo <strong>{stepForNotes.stepName}</strong>
			</p>

			<div class="form-control mt-4">
				<label class="label" for="notes-textarea">
					<span class="label-text">Notas</span>
				</label>
				<textarea
					id="notes-textarea"
					bind:value={editedNotes}
					class="textarea textarea-bordered w-full"
					rows="5"
					placeholder="Adicione observações, comentários ou informações relevantes..."
				></textarea>
			</div>

			<div class="modal-action">
				<button class="btn" onclick={closeNotesModal} disabled={isProcessing}> Cancelar </button>
				<button class="btn btn-primary" onclick={handleSaveNotes} disabled={isProcessing}>
					{#if isProcessing}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					Salvar
				</button>
			</div>
		</div>
		<button type="button" class="modal-backdrop" onclick={closeNotesModal} aria-label="Fechar modal"
		></button>
	</div>
{/if}

<!-- Modal de Upload -->
{#if showUploadModal && stepForUpload}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-lg font-bold">Upload de Documento</h3>
			<p class="text-base-content/60 mt-2">
				Anexe um documento ao passo <strong>{stepForUpload.stepName}</strong>
			</p>

			<div class="form-control mt-4">
				<label class="label" for="file-input">
					<span class="label-text">Arquivo</span>
				</label>
				<input
					type="file"
					id="file-input"
					class="file-input file-input-bordered w-full"
					onchange={handleFileSelect}
				/>
			</div>

			{#if uploadFile}
				<p class="text-base-content/60 mt-2 text-sm">
					Arquivo selecionado: <strong>{uploadFile.name}</strong>
				</p>
			{/if}

			<div class="modal-action">
				<button class="btn" onclick={closeUploadModal} disabled={isUploading}> Cancelar </button>
				<button
					class="btn btn-primary"
					onclick={handleUpload}
					disabled={isUploading || !uploadFile}
				>
					{#if isUploading}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					Enviar
				</button>
			</div>
		</div>
		<button
			type="button"
			class="modal-backdrop"
			onclick={closeUploadModal}
			aria-label="Fechar modal"
		></button>
	</div>
{/if}

<!-- Modal de Cancelamento -->
{#if showCancelModal}
	<div class="modal modal-open">
		<div class="modal-box">
			<h3 class="text-error text-lg font-bold">Cancelar Fluxo</h3>
			<p class="py-4">Tem certeza que deseja cancelar este fluxo?</p>
			<p class="text-base-content/60 text-sm">
				Esta ação não pode ser desfeita. Todos os passos pendentes serão marcados como cancelados.
			</p>

			<div class="modal-action">
				<button class="btn" onclick={() => (showCancelModal = false)} disabled={isProcessing}>
					Voltar
				</button>
				<button class="btn btn-error" onclick={handleCancelInstance} disabled={isProcessing}>
					{#if isProcessing}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					Cancelar Fluxo
				</button>
			</div>
		</div>
		<button
			type="button"
			class="modal-backdrop"
			onclick={() => (showCancelModal = false)}
			aria-label="Fechar modal"
		></button>
	</div>
{/if}
