"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

function Input({ className, type, ref, ...props }: React.ComponentProps<"input">) {
  const attachInput = React.useCallback(
    (node: HTMLInputElement | null) => {
      const refCleanup = typeof ref === "function" ? ref(node) : undefined;
      if (ref && typeof ref !== "function") ref.current = node;
      if (!node) return;

      function preventNumberWheel(event: WheelEvent) {
        if (node?.ownerDocument.activeElement === node) event.preventDefault();
      }
      // React wheel handlers are passive; a native listener can prevent stepping
      // while preserving focus and normal scrolling outside the focused input.
      if (type === "number") {
        node.addEventListener("wheel", preventNumberWheel, { passive: false });
      }
      return () => {
        if (type === "number") {
          node.removeEventListener("wheel", preventNumberWheel);
        }
        if (typeof refCleanup === "function") refCleanup();
        else if (typeof ref === "function") ref(null);
        else if (ref) ref.current = null;
      };
    },
    [ref, type],
  );

  return (
    <input
      type={type}
      ref={attachInput}
      data-slot="input"
      className={cn(
        "h-11 w-full min-w-0 rounded-lg border border-input bg-transparent px-4 py-2 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-card dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
        type === "number" &&
          "[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",
        className,
      )}
      {...props}
    />
  );
}

export { Input };
