<script lang="ts">
  import type { Snippet } from 'svelte';

  interface Props {
    id?: string;
    value?: string | null;
    values: { [value: string]: string };
    defaultValue?: string;
    label?: string;
    required?: boolean;
    validation?: {
      hint: string;
    };
    disabled?: boolean;

    size?: 'sm';
    dynamicWidth?: boolean;

    notice?: Snippet;
  }

  let {
    id,
    value = $bindable(),
    values,
    defaultValue,
    label,
    required,
    validation,
    disabled,
    size,
    dynamicWidth,
    notice
  }: Props = $props();
</script>

<fieldset class="fieldset">
  <legend class="fieldset-legend">
    <span>
      {label}
      {#if required}
        <span class="text-red-700">*</span>
      {/if}
    </span>
  </legend>
  <select
    {id}
    bind:value
    class="select"
    class:select-sm={size === 'sm'}
    class:w-full={dynamicWidth}
    class:validator={required || validation}
    required={required ? true : null}
    disabled={disabled ? true : null}
  >
    {#if defaultValue != null}
      <option disabled selected>{defaultValue}</option>
    {/if}
    {#each Object.entries(values) as [v, label] (v)}
      <option value={v} selected={v === value}>{label}</option>
    {/each}
  </select>
  <p class="fieldset-label">
    {#if notice}
      {@render notice()}
    {/if}
  </p>
  {#if validation}
    <p class="validator-hint mt-0">{validation.hint}</p>
  {/if}
</fieldset>
