<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>

<svelte:head>
  <title>Preferencias de recordatorios</title>
  <meta name="robots" content="noindex,nofollow" />
</svelte:head>

<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} bind:value={freq} />
        <ul class="help">
          <li>Diario: cada día a la hora indicada</li>
          <li>Laborables: solo de lunes a viernes</li>
          <li>Semanal: los lunes</li>
        </ul>
      </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: 0.75rem;
  }
  .form {
    display: grid;
    gap: 0.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>
