<script lang="ts">
  let {
    id = '',
    name = '',
    type = 'text',
    value = $bindable(''),
    placeholder = '',
    label = '',
    required = false,
    disabled = false,
    error = '',
    helpText = '',
    invalid = false,
  } = $props();

  const inputId = $derived(id || `input-${Math.random().toString(36).slice(2)}`);
  const errorId = $derived(`${inputId}-error`);
  const helpId = $derived(`${inputId}-help`);
</script>

<div>
  {#if label}
    <label
      for={inputId}
      class="mb-1.5 block text-sm font-medium text-stein-700"
    >
      {label}
      {#if required}
        <span class="text-error">*</span>
      {/if}
    </label>
  {/if}
  <input
    {type}
    {name}
    {placeholder}
    {required}
    {disabled}
    bind:value
    id={inputId}
    aria-required={required}
    aria-invalid={invalid || !!error}
    aria-describedby={[error ? errorId : '', helpText ? helpId : ''].filter(Boolean).join(' ')}
    class="h-12 w-full rounded-lg border bg-white px-4 py-3 text-base text-stein-800 outline-none placeholder:text-stein-400 {error || invalid
      ? 'border-error ring-2 ring-error-subtle'
      : 'border-stein-300 hover:border-stein-400 focus:border-wald-500 focus:ring-2 focus:ring-wald-100'} disabled:bg-stein-100 disabled:opacity-60"
  />
  {#if error}
    <p id={errorId} class="mt-1.5 text-[0.8125rem] text-error" role="alert">
      {error}
    </p>
  {:else if helpText}
    <p id={helpId} class="mt-1.5 text-[0.8125rem] text-stein-500">
      {helpText}
    </p>
  {/if}
</div>
