<!-- #region ScheduleConfig [C:3] [TYPE Component] [SEMANTICS translate, schedule, cron, trigger, config] -->
<!-- @BRIEF Component component: lib/components/translate/ScheduleConfig.svelte -->
<!-- @RELATION DEPENDS_ON -> [TranslateApi] -->
<!-- @UX_STATE idle -> No schedule configured -->
<!-- @UX_STATE editing -> Configuring schedule -->
<!-- @UX_STATE enabled -> Schedule active -->
<!-- @UX_STATE disabled -> Schedule inactive -->
<!-- @UX_STATE no_prior_run_warning -> No prior manual run, show warning -->
<!-- @UX_FEEDBACK Next-3-executions preview; toast on save/error -->
<!-- @UX_RECOVERY Enable/disable toggle; delete schedule -->
<script lang="ts">
	import { t } from '$lib/i18n/index.svelte.js';
	import { addToast } from '$lib/toasts.svelte.js';
	import HelpTooltip from "$lib/ui/HelpTooltip.svelte";
	import {
		fetchSchedule,
		setSchedule,
		deleteSchedule,
		enableSchedule,
		disableSchedule,
		fetchNextExecutions
	} from '$lib/api/translate.js';

	let { jobId = '' } = $props();

	/** @type {'idle'|'editing'|'enabled'|'disabled'|'no_prior_run_warning'} */
	let uxState = $state('idle');
	let cronExpression = $state('0 2 * * *');
	let timezone = $state('UTC');
	let executionMode = $state('full');
	let isEnabled = $state(false);
	let isLoading = $state(true);
	let nextExecutions = $state([]);
	let hasPriorRun = $state(true);
	let scheduleExists = $state(false);
	let isEditing = $derived(uxState === 'editing');

	$effect(() => {
		if (jobId) loadSchedule();
	});

	async function loadSchedule() {
		isLoading = true;
		try {
			const sch = await fetchSchedule(jobId);
			if (sch && sch.cron_expression) {
				cronExpression = sch.cron_expression;
				timezone = sch.timezone || 'UTC';
				executionMode = sch.execution_mode || 'full';
				isEnabled = sch.is_active !== false;
				scheduleExists = true;
				uxState = isEnabled ? 'enabled' : 'disabled';
				loadNextExecutions();
			} else {
				uxState = 'idle';
			}
		} catch (err) {
			// 404 = no schedule
			uxState = 'idle';
		} finally {
			isLoading = false;
		}
	}

	async function loadNextExecutions() {
		try {
			const result = await fetchNextExecutions(jobId, 3);
			nextExecutions = result?.next_executions || [];
		} catch (err) {
			nextExecutions = [];
		}
	}

	async function handleSave() {
		try {
			const payload = {
				cron_expression: cronExpression,
				timezone: timezone,
				is_active: isEnabled,
				execution_mode: executionMode,
			};
			await setSchedule(jobId, payload);
			addToast($t.translate?.schedule?.saved || 'Schedule saved', 'success');
			scheduleExists = true;
			uxState = isEnabled ? 'enabled' : 'disabled';
			loadNextExecutions();
		} catch (err) {
			addToast(err?.message || ($t.translate?.schedule?.save_failed || 'Failed to save schedule'), 'error');
		}
	}

	async function handleDelete() {
		try {
			await deleteSchedule(jobId);
			addToast($t.translate?.schedule?.deleted || 'Schedule deleted', 'success');
			scheduleExists = false;
			uxState = 'idle';
			cronExpression = '0 2 * * *';
			nextExecutions = [];
		} catch (err) {
			addToast(err?.message || ($t.translate?.schedule?.delete_failed || 'Failed to delete schedule'), 'error');
		}
	}

	async function handleToggle() {
		try {
			if (isEnabled) {
				await disableSchedule(jobId);
				isEnabled = false;
				uxState = 'disabled';
				addToast($t.translate?.schedule?.disabled_toast || 'Schedule disabled', 'info');
			} else {
				if (!scheduleExists) {
					await handleSave();
					return;
				}
				await enableSchedule(jobId);
				isEnabled = true;
				uxState = 'enabled';
				addToast($t.translate?.schedule?.enabled_toast || 'Schedule enabled', 'success');
				loadNextExecutions();
			}
		} catch (err) {
			addToast(err?.message || ($t.translate?.schedule?.toggle_failed || 'Failed to toggle schedule'), 'error');
		}
	}

	function getCronDescription(cron) {
		const parts = cron.split(' ');
		if (parts.length !== 5) return cron;
		if (parts[1] === '*' && parts[2] === '*' && parts[4] === '*') {
			const hour = parts[0] === '*' ? '' : parts[0];
			const min = parts[1];
			if (parts[0] === '*') {
				return ($t.translate?.schedule?.description_every_hour || 'at :{minute} past the hour').replace('{minute}', min);
			}
			return ($t.translate?.schedule?.description_daily || 'Daily at {hour}:{minute}').replace('{hour}', hour).replace('{minute}', min);
		}
		return ($t.translate?.schedule?.description_cron || 'Cron: {cron}').replace('{cron}', cron);
	}

	const commonTimezones = [
		'UTC', 'US/Eastern', 'US/Central', 'US/Mountain', 'US/Pacific',
		'Europe/London', 'Europe/Berlin', 'Europe/Moscow', 'Europe/Paris',
		'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Kolkata', 'Australia/Sydney',
	];
</script>

<div class="bg-white border border-gray-200 rounded-lg p-4 space-y-4">
	<div class="flex items-center justify-between">
		<h3 class="text-lg font-semibold text-gray-900">{$t.translate?.schedule?.title || 'Schedule Configuration'}</h3>
		{#if !isLoading && scheduleExists}
			<button
				onclick={handleToggle}
				class="inline-flex items-center px-3 py-1.5 text-sm rounded-full {isEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}"
			>
				<span class="w-2 h-2 rounded-full mr-2 {isEnabled ? 'bg-green-500' : 'bg-gray-400'}"></span>
				{isEnabled ? ($t.translate?.schedule?.enabled || 'Enabled') : ($t.translate?.schedule?.disabled || 'Disabled')}
			</button>
		{/if}
	</div>

	{#if isLoading}
		<div class="h-24 bg-gray-50 rounded-lg animate-pulse"></div>

	{:else if uxState === 'idle'}
		<div class="text-center py-6">
			<svg class="w-12 h-12 text-gray-300 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
			</svg>
			<p class="text-sm text-gray-500 mb-1">{$t.translate?.schedule?.no_schedule || 'No schedule configured'}</p>
			<p class="text-xs text-gray-400 mb-4">{$t.translate?.schedule?.no_schedule_hint || 'Set up a recurring schedule for automatic translations'}</p>
			<button onclick={() => (uxState = 'editing')} class="px-4 py-2 text-sm text-white bg-primary rounded-lg hover:bg-primary-hover">
				{$t.translate?.schedule?.create_schedule || 'Create Schedule'}
			</button>
		</div>

	{:else if uxState === 'editing' || uxState === 'enabled' || uxState === 'disabled'}
		<div class="space-y-4">
			<!-- Cron expression -->
			<div>
				<span class="flex items-center gap-1.5 mb-1">
				<label class="text-sm font-medium text-gray-700">{$t.translate?.schedule?.cron_expression || 'Cron Expression'}</label>
				<HelpTooltip text={$t.translate?.schedule?.help_cron || ""} />
				</span>
				<div class="flex gap-2">
					<input
						type="text"
						bind:value={cronExpression}
						placeholder="0 2 * * *"
						disabled={!isEditing}
						class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus-visible:ring-2 focus-visible:ring-primary-ring disabled:bg-gray-50 disabled:text-gray-500"
					/>
					<select
						bind:value={cronExpression}
						disabled={!isEditing}
						class="px-3 py-2 border border-gray-300 rounded-lg text-sm disabled:bg-gray-50 disabled:text-gray-500"
					>
						<option value="0 2 * * *">{$t.translate?.schedule?.preset_daily || 'Daily at 02:00'}</option>
						<option value="0 */6 * * *">{$t.translate?.schedule?.preset_every_6h || 'Every 6 hours'}</option>
						<option value="30 1 * * 0">{$t.translate?.schedule?.preset_weekly || 'Weekly (Sun 01:30)'}</option>
						<option value="0 3 1 * *">{$t.translate?.schedule?.preset_monthly || 'Monthly (1st at 03:00)'}</option>
						<option value="*/15 * * * *">{$t.translate?.schedule?.preset_every_15min || 'Every 15 min'}</option>
					</select>
				</div>
				<p class="text-xs text-gray-400 mt-1">
					{getCronDescription(cronExpression)}
				</p>
			</div>

			<!-- Timezone -->
			<div>
				<span class="flex items-center gap-1.5 mb-1">
				<label class="text-sm font-medium text-gray-700">{$t.translate?.schedule?.timezone || 'Timezone'}</label>
				<HelpTooltip text={$t.translate?.schedule?.help_timezone || ""} />
				</span>
				<select
					bind:value={timezone}
					disabled={!isEditing}
					class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm disabled:bg-gray-50 disabled:text-gray-500"
				>
					{#each commonTimezones as tz}
						<option value={tz}>{tz}</option>
					{/each}
				</select>
			</div>

			<!-- Execution mode -->
			<div>
				<span class="flex items-center gap-1.5 mb-1">
				<label class="text-sm font-medium text-gray-700">{$t.translate?.schedule?.execution_mode || 'Execution Mode'}</label>
				<HelpTooltip text={$t.translate?.schedule?.help_execution_mode || ""} />
				</span>
				<div class="flex gap-4">
					<label class="inline-flex items-center cursor-pointer">
						<input type="radio" bind:group={executionMode} value="full" class="sr-only peer" disabled={!isEditing} />
						<div class="px-4 py-2 text-sm border border-gray-300 rounded-lg peer-checked:border-blue-500 peer-checked:bg-primary-light peer-checked:text-blue-700 hover:border-gray-400 {isEditing ? '' : 'opacity-70'}">
							<div class="font-medium">{$t.translate?.schedule?.mode_full || 'Full'}</div>
							<div class="text-xs text-gray-500 mt-0.5">{$t.translate?.schedule?.mode_full_desc || 'Translate all rows every run'}</div>
						</div>
					</label>
					<label class="inline-flex items-center cursor-pointer">
						<input type="radio" bind:group={executionMode} value="new_key_only" class="sr-only peer" disabled={!isEditing} />
						<div class="px-4 py-2 text-sm border border-gray-300 rounded-lg peer-checked:border-blue-500 peer-checked:bg-primary-light peer-checked:text-blue-700 hover:border-gray-400 {isEditing ? '' : 'opacity-70'}">
							<div class="font-medium">{$t.translate?.schedule?.mode_new_keys || 'New Keys Only'}</div>
							<div class="text-xs text-gray-500 mt-0.5">{$t.translate?.schedule?.mode_new_keys_desc || 'Only translate rows with new key values'}</div>
						</div>
					</label>
				</div>
			</div>

			<!-- Next executions preview -->
			{#if nextExecutions.length > 0}
				<div class="bg-gray-50 rounded-lg p-3">
					<p class="text-xs font-medium text-gray-600 mb-2">{$t.translate?.schedule?.next_executions || 'Next Executions'}</p>
					{#each nextExecutions as dt, i}
						<p class="text-xs text-gray-500 font-mono">{i + 1}. {new Date(dt).toLocaleString()}</p>
					{/each}
				</div>
			{/if}

			<!-- Prior run warning -->
			{#if uxState === 'no_prior_run_warning'}
				<div class="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
					<p class="text-xs text-yellow-700">
						⚠ {$t.translate?.schedule?.no_prior_run_warning || 'No prior successful manual run. Schedule may run with default settings. Consider running manually first.'}
					</p>
				</div>
			{/if}

			<!-- Actions -->
			<div class="flex justify-between items-center pt-2">
				{#if scheduleExists}
					<button onclick={handleDelete} class="px-3 py-1.5 text-sm text-red-600 hover:text-red-700">
						{$t.translate?.schedule?.delete_schedule || 'Delete Schedule'}
					</button>
				{:else}
					<div></div>
				{/if}
				<div class="flex gap-2">
					{#if scheduleExists && (uxState === 'enabled' || uxState === 'disabled')}
						<button onclick={() => (uxState = 'editing')} class="px-4 py-2 text-sm text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">
							{$t.translate?.schedule?.edit || 'Edit'}
						</button>
					{/if}
					{#if uxState === 'editing'}
						<button onclick={handleSave} class="px-4 py-2 text-sm text-white bg-primary rounded-lg hover:bg-primary-hover">
							{scheduleExists ? ($t.translate?.schedule?.update || 'Update') : ($t.translate?.schedule?.create || 'Create')}
						</button>
					{/if}
				</div>
			</div>
		</div>
	{/if}
</div>
<!-- #endregion ScheduleConfig -->
