<template>
  <view :class="['custom-card', { 'is-selected': selected }]" @tap="emit('select')">
    <text class="custom-title">自选金额</text>

    <label class="custom-input-wrap">
      <text class="custom-currency">¥</text>
      <input
        class="custom-input"
        type="number"
        :maxlength="6"
        :value="modelValue"
        @focus="emit('select')"
        @input="handleInput"
      />
    </label>

    <view class="custom-hint">
      <text>请输入整数金额</text>
    </view>
  </view>
</template>

<script setup>
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  selected: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "select"]);
const MAX_CUSTOM_AMOUNT = 999999;

const handleInput = (event) => {
  const rawValue = event?.detail?.value ?? event?.target?.value ?? "";
  const amountText = String(rawValue).trim();
  const value = /^\d*$/.test(amountText)
    ? amountText
      ? String(Math.min(Number(amountText), MAX_CUSTOM_AMOUNT))
      : ""
    : props.modelValue;
  emit("select");
  emit("update:modelValue", value);
};
</script>

<style scoped lang="scss">
@import "./styles/index.scss";
</style>
