<script lang="ts">
	interface Props {
		checked: boolean;
		id: string;
		label: string;
		disabled?: boolean;
		onchange?: (checked: boolean) => void;
	}

	let { checked = $bindable(false), id, label, disabled = false, onchange }: Props = $props();

	function handleInput(e: Event) {
		const target = e.target as HTMLInputElement;
		checked = target.checked;
		onchange?.(checked);
	}
</script>

<div class="toggle-wrapper" class:is-disabled={disabled}>
	<!-- 1. Interactive Switch Mechanism (Sits Left) -->
	<div class="toggle-control">
		<input type="checkbox" {id} {disabled} {checked} onchange={handleInput} class="toggle-input" />
		<label for={id} class="toggle-track">
			<span class="toggle-thumb"></span>
		</label>
	</div>

	<!-- 2. Visible Text Label (Sits Right) -->
	<label for={id} class="toggle-label-text">
		{label}
	</label>
</div>

<style>
	.toggle-wrapper {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		gap: 1.75rem;
		width: 100%;
	}

	.toggle-control {
		position: relative;
		display: inline-flex;
		align-items: center;
	}

	.toggle-input {
		position: absolute;
		width: 1px;
		height: 1px;
		padding: 0;
		margin: -1px;
		overflow: hidden;
		clip: rect(0, 0, 0, 0);
		border: 0;
	}

	.toggle-track {
		position: relative;
		display: inline-block;
		width: 3.75rem;
		height: 2rem;
		background-color: rgb(93, 45, 45);
		border-radius: 1rem;
		cursor: pointer;
		transition: background-color 0.2s ease;
		box-shadow: inset 0 1px 3px rgba(0,0,0,0.5);
	}

	.toggle-thumb {
		position: absolute;
		top: 0.25rem;
		left: 0.25rem;
		width: 1.5rem;
		height: 1.5rem;
		background-color: var(--color-accent);
		border-radius: 50%;
		transition: transform 0.2s ease;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
		filter: brightness(1.45);
	}

	.toggle-input:checked + .toggle-track {
		background-color: rgb(11, 70, 11);
	}

	.toggle-input:checked + .toggle-track .toggle-thumb {
		transform: translateX(1.75rem);
	}

	.toggle-input:focus-visible + .toggle-track {
		outline: 2px solid #3b82f6;
		outline-offset: 2px;
	}

	.toggle-label-text {
		font-weight: 600;
		cursor: pointer;
		user-select: none;
		color: var(--color-title);
	}

	.is-disabled {
		opacity: 0.5;
	}

	.is-disabled .toggle-track,
	.is-disabled .toggle-label-text {
		cursor: not-allowed;
	}
</style>
