"use client";

import type { SelectHTMLAttributes } from "react";
import { cn } from "@/lib/cn";

type FloatDropdownProps = SelectHTMLAttributes<HTMLSelectElement> & {
  label: string;
  error?: string;
  options: readonly string[];
  placeholder?: string;
  defaultValue?: string;
};

/* Floating-label select: the label is permanently docked in the top
   border (selects can't use the placeholder-shown trick). CSS-only. */
export default function FloatDropdown({
  label,
  error,
  options,
  placeholder = "Select",
  defaultValue = "",
  required,
  id,
  className,
  ...props
}: FloatDropdownProps) {
  return (
    <div className={cn("min-w-0", className)}>
      <div className="relative">
        <select
          id={id}
          required={required}
          defaultValue={defaultValue}
          {...props}
          className={cn(
            "peer block h-12 w-full appearance-none rounded-xl border bg-white px-3.5 pr-10 pt-2 text-sm font-normal text-ink focus:outline-none focus-visible:outline-none",
            error
              ? "border-red-400 focus:border-red-500"
              : "border-[#d5dce8] focus:border-brand"
          )}
        >
          <option value="" disabled>
            {placeholder}
          </option>
          {options.map((o) => (
            <option key={o} value={o}>
              {o}
            </option>
          ))}
        </select>
        <label
          htmlFor={id}
          className={cn(
            "pointer-events-none absolute left-3 top-0 -translate-y-1/2 bg-white px-1 text-xs font-semibold",
            error ? "text-red-500" : "text-muted peer-focus:text-brand"
          )}
        >
          {label}
          {required && (
            <span aria-hidden="true" className="ml-0.5 text-red-500">*</span>
          )}
        </label>
        <svg
          width="16"
          height="16"
          viewBox="0 0 16 16"
          fill="none"
          aria-hidden="true"
          className="pointer-events-none absolute right-3.5 top-1/2 -translate-y-1/2 text-muted"
        >
          <path
            d="M4 6l4 4 4-4"
            stroke="currentColor"
            strokeWidth="1.6"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </div>
      {error && (
        <span className="mt-1 block text-xs font-normal text-red-600">
          {error}
        </span>
      )}
    </div>
  );
}
