<script lang="ts">
  import SegmentedControl from '$lib/ui/inputs/SegmentedControl.svelte';
  import Card from '$lib/ui/layout/Card.svelte';
  import Button from '$lib/ui/atoms/Button.svelte';
  import { success as toastSuccess } from '$lib/stores/toasts';

	export let data: {
		pref: { freq: 'off' | 'daily' | 'weekly' | 'weekdays'; time: string | null };
		tz: string;
		next: string | null;
	};
	export let form: any;

	let freq: 'off' | 'daily' | 'weekly' | 'weekdays' = data.pref.freq;
	let time: string = data.pref.time ?? '08:30';
  $: if (form?.success) { try { toastSuccess('Preferencias guardadas.'); } catch {} }

  const options = [
    { label: 'Apagado', value: 'off' },
    { label: 'Diario', value: 'daily' },
    { label: 'L–V', value: 'weekdays' },
    { label: 'Semanal', value: 'weekly' }
  ];
</script>

<section class="page">
	<h1 class="title">Preferencias de recordatorios</h1>

  <Card>
    <form method="POST" class="form">
      <div>
        <label for="freq">Frecuencia</label>
        <SegmentedControl name="freq" options={options} bind:value={freq} />
        <p class="help">
          - Diario: cada día a la hora indicada. - Laborables: solo lunes a viernes. - Semanal: los lunes.
        </p>
      </div>

      <div>
        <label for="time">Hora (HH:MM)</label>
        <input id="time" name="time" type="time" step="60" bind:value={time} disabled={freq === 'off'} />
        <p class="help">Zona horaria: {data.tz}</p>
      </div>

      {#if form?.error}
        <div class="error">{form.error}</div>
      {/if}

      <div>
        <Button type="submit" variant="primary">Guardar</Button>
      </div>
    </form>
  </Card>

	<div class="section">
		<h2 class="subtitle">Próximo recordatorio</h2>
		<ul>
			<li>Servidor: {data.next ?? '—'}</li>
		</ul>
	</div>
</section>

<style>
  .page { max-width: 720px; margin: 1.5rem auto; padding: 0 1rem; }
  .title { font-size: 1.4rem; font-weight: 600; margin-bottom: .75rem; }
  .form { display: grid; gap: .75rem; }
  label { display: block; font-weight: 600; margin-bottom: 0.25rem; }
  .help { font-size: 0.9rem; color: var(--color-text-muted); margin-top: 0.25rem; }
  .error { color: var(--color-danger); }
  .section { margin-top: 1rem; }
  .subtitle { font-size: 1.1rem; font-weight: 600; }
</style>
