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

  interface Props {
    id?: string;
    value?: string | null;
    label?: string;
    required?: boolean;
    validation?: {
      pattern?: string;
      hint: string;
    };
    disabled?: boolean;

    notice?: Snippet;
  }

  let { id, value = $bindable(), label, required, validation, disabled, notice }: Props = $props();

  let visible = $state(false);
</script>

<fieldset class="fieldset">
  <legend class="fieldset-legend">
    <span>
      {label}
      {#if required}
        <span class="text-red-700">*</span>
      {/if}
    </span>
  </legend>
  <div class="relative flex items-center">
    <input
      {id}
      bind:value
      class="input pr-9"
      class:validator={required || validation}
      type={visible ? 'text' : 'password'}
      required={required ? true : null}
      pattern={validation?.pattern}
      disabled={disabled ? true : null}
      data-input-visible="false"
    />
    <button
      type="button"
      class="absolute right-2 cursor-pointer z-10"
      class:hidden={!visible}
      onclick={() => (visible = !visible)}
    >
      <Icon icon="heroicons:eye-16-solid" width={22} />
    </button>
    <button
      type="button"
      class="absolute right-2 cursor-pointer z-10"
      class:hidden={visible}
      onclick={() => (visible = !visible)}
    >
      <Icon icon="heroicons:eye-slash-16-solid" width={22} />
    </button>
  </div>
  <p class="fieldset-label">
    {#if notice}
      {@render notice()}
    {/if}
  </p>
  {#if validation}
    <p class="validator-hint mt-0">{validation.hint}</p>
  {/if}
</fieldset>
