"use client";

import { useTranslation } from "react-i18next";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import type { TicketNumberSpec } from "@/features/hall/hall-bet-rules";

type HallBetNumberInputProps = {
  id: string;
  label: string;
  value: string;
  onChange: (v: string) => void;
  spec: TicketNumberSpec;
  disabled?: boolean;
  helper?: string | null;
};

function sanitizeRoll(raw: string, maxChars: number): string {
  const u = raw.toUpperCase().replace(/[^0-9R]/g, "");
  return u.slice(0, maxChars);
}

function sanitizeDigits(raw: string, maxChars: number): string {
  return raw.replace(/\D/g, "").slice(0, maxChars);
}

/**
 * 号码输入：长度与字符集随玩法变化（产品文档 §5 各玩法号码定义）。
 */
export function HallBetNumberInput({
  id,
  label,
  value,
  onChange,
  spec,
  disabled,
  helper,
}: HallBetNumberInputProps) {
  const { t } = useTranslation("player");
  const handle = (raw: string) => {
    if (spec.mode === "roll") {
      onChange(sanitizeRoll(raw, spec.maxChars));
    } else {
      onChange(sanitizeDigits(raw, spec.maxChars));
    }
  };

  return (
    <div className="space-y-2">
      <Label htmlFor={id}>{label}</Label>
      <Input
        id={id}
        inputMode={spec.mode === "roll" ? "text" : "numeric"}
        autoComplete="off"
        spellCheck={false}
        disabled={disabled}
        value={value}
        onChange={(e) => handle(e.target.value)}
        className={cn("font-mono text-base tracking-widest")}
        placeholder={
          spec.mode === "roll"
            ? t("hall.numberInput.rollPlaceholder")
            : t("hall.numberInput.digitPlaceholder")
        }
        maxLength={spec.maxChars}
      />
      {helper ? <p className="text-xs text-muted-foreground">{helper}</p> : null}
    </div>
  );
}
