<script lang="ts">
	interface Props {
		open: boolean;
		title: string;
		width?: string;
		children: import('svelte').Snippet;
		footer?: import('svelte').Snippet;
		onclose: () => void;
	}
	let { open, title, width = '520px', children, footer, onclose }: Props = $props();

	function handleBackdrop(e: MouseEvent) {
		if (e.target === e.currentTarget) onclose();
	}

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape') onclose();
	}
</script>

<svelte:window onkeydown={open ? handleKeydown : undefined} />

{#if open}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="backdrop" onmousedown={handleBackdrop}>
		<div class="modal" style="max-width: {width}">
			<div class="modal-header">
				<h2>{title}</h2>
				<button class="close-btn" onclick={onclose} aria-label="Close">
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
						<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
					</svg>
				</button>
			</div>
			<div class="modal-body">
				{@render children()}
			</div>
			{#if footer}
				<div class="modal-footer">
					{@render footer()}
				</div>
			{/if}
		</div>
	</div>
{/if}

<style>
	.backdrop {
		position: fixed;
		inset: 0;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
		backdrop-filter: blur(4px);
		animation: fadeIn 0.15s ease;
	}
	@keyframes fadeIn { from { opacity: 0; } }
	.modal {
		background: var(--surface-1);
		border: 1px solid var(--border-strong);
		border-radius: var(--radius-lg);
		width: 90vw;
		max-height: 85vh;
		display: flex;
		flex-direction: column;
		animation: slideUp 0.2s var(--ease);
	}
	@keyframes slideUp { from { transform: translateY(10px); opacity: 0; } }
	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 20px;
		border-bottom: 1px solid var(--border);
	}
	.modal-header h2 {
		font-size: var(--font-size-lg);
		font-weight: 600;
		color: var(--text-bright);
	}
	.close-btn {
		background: none;
		border: none;
		color: var(--text-dim);
		cursor: pointer;
		padding: 4px;
		border-radius: var(--radius-sm);
		transition: all var(--duration) var(--ease);
	}
	.close-btn:hover {
		color: var(--text);
		background: var(--surface-3);
	}
	.modal-body {
		padding: 20px;
		overflow-y: auto;
		flex: 1;
	}
	.modal-footer {
		padding: 14px 20px;
		border-top: 1px solid var(--border);
		display: flex;
		justify-content: flex-end;
		gap: 8px;
	}
</style>
