<template>
    <form @submit.prevent="search">
        <div class="input-group mb-3 d-flex">
            <input type="text" class="form-control" placeholder="Search" v-model="searchQuery" @input="preventLeadingSpace" />
            <button type="submit" class="btn btn-primary">
                <i class="bx bx-search bx-md"></i>
            </button>
        </div>
    </form>
</template>

<script setup>
    import { ref, watch } from 'vue';

    const props = defineProps({
        maxlength: {
            type: Number,
            default: 30,
            required: false,
        },
        initKeyword: {
            type: String,
        },
    });

    const emits = defineEmits(['update:data']);
    const searchQuery = ref('');

    watch(
        () => props.initKeyword,
        (newVal, oldVal) => {
            searchQuery.value = newVal;
        },
    );

    // 검색 실행 함수 (버튼 클릭 or 엔터 공통)
    const search = () => {
        const trimmedQuery = searchQuery.value.trimStart();
        if (trimmedQuery === '') {
            emits('update:data', '');
            return;
        }
        if (trimmedQuery.length < 2) {
            alert('검색어는 최소 2글자 이상 입력해주세요.');
            searchQuery.value = '';
            return;
        }

        // 길이 제한 처리
        if (trimmedQuery.length > props.maxlength) {
            searchQuery.value = trimmedQuery.slice(0, props.maxlength);
        } else {
            searchQuery.value = trimmedQuery;
        }

        emits('update:data', searchQuery.value);
    };

    // 좌측 공백 제거
    const preventLeadingSpace = () => {
        searchQuery.value = searchQuery.value.trimStart();
    };
</script>
