<script lang="ts">
  // 네이티브 <select> 래퍼. TextInput과 동일 시각 시스템.
  // options 배열을 그룹 없이 단순 평면 리스트로 받는다.
  import { ChevronDown } from 'lucide-svelte';

  export interface SelectOption {
    value: string;
    label: string;
    disabled?: boolean;
  }

  interface Props {
    value?: string;
    options: SelectOption[];
    label?: string;
    error?: string;
    hint?: string;
    placeholder?: string;
    id?: string;
    name?: string;
    disabled?: boolean;
    required?: boolean;
    class?: string;
  }

  let {
    value = $bindable(''),
    options,
    label,
    error,
    hint,
    placeholder,
    id: idProp,
    name,
    disabled = false,
    required = false,
    class: className = '',
    ...rest
  }: Props = $props();

  const autoId = $props.id();
  let inputId = $derived(idProp ?? `select-${autoId}`);
  let hintId = $derived(`${inputId}-hint`);
  let errorId = $derived(`${inputId}-error`);
  let describedBy = $derived(
    [error ? errorId : null, hint && !error ? hintId : null].filter(Boolean).join(' ') || undefined
  );

  let selectClass = $derived(
    [
      'w-full h-9 pl-3 pr-9 rounded-md text-sm bg-bg text-text appearance-none',
      'border outline-none transition-colors',
      error
        ? 'border-error focus:border-error focus:ring-2 focus:ring-error/30'
        : 'border-default focus:border-accent focus:ring-2 focus:ring-accent-ring',
      'disabled:opacity-50 disabled:cursor-not-allowed',
    ].join(' ')
  );
</script>

<div class={'flex flex-col gap-1 ' + className}>
  {#if label}
    <label for={inputId} class="text-xs font-medium text-dim">
      {label}
      {#if required}<span class="text-error">*</span>{/if}
    </label>
  {/if}

  <div class="relative">
    <select
      id={inputId}
      bind:value
      {name}
      {disabled}
      {required}
      class={selectClass}
      aria-invalid={error ? 'true' : undefined}
      aria-describedby={describedBy}
      {...rest}
    >
      {#if placeholder}
        <option value="" disabled selected={value === ''}>{placeholder}</option>
      {/if}
      {#each options as opt (opt.value)}
        <option value={opt.value} disabled={opt.disabled}>{opt.label}</option>
      {/each}
    </select>
    <div
      class="absolute inset-y-0 right-0 flex items-center pr-2.5 text-faint pointer-events-none"
    >
      <ChevronDown size={16} />
    </div>
  </div>

  {#if error}
    <p id={errorId} class="text-xs text-error">{error}</p>
  {:else if hint}
    <p id={hintId} class="text-xs text-faint">{hint}</p>
  {/if}
</div>
