<script setup lang="ts">
import { shallowRef, watch } from 'vue';

const keyword = defineModel<string>('keyword', { default: '' });
const emit = defineEmits<{ search: [] }>();
const localKeyword = shallowRef(keyword.value);
watch(keyword, (value) => { localKeyword.value = value; });
function submit(): void { keyword.value = localKeyword.value.trim(); emit('search'); }
function clear(): void { localKeyword.value = ''; keyword.value = ''; emit('search'); }
</script>

<template>
  <form class="search-box" role="search" @submit.prevent="submit">
    <i class="fa-solid fa-magnifying-glass search-icon" aria-hidden="true"></i>
    <input v-model="localKeyword" aria-label="搜索商品" placeholder="搜索商品" />
    <button v-if="localKeyword" class="clear-search" type="button" aria-label="清除搜索" @click="clear"><i class="fa-solid fa-xmark"></i></button>
    <button class="submit-search" type="submit">搜索</button>
  </form>
</template>

<style scoped>
.search-box { position: relative; display: flex; align-items: center; width: 220px; height: 38px; border: 1px solid #c7c7c7; border-radius: 60px; background: #fff; overflow: hidden; }
.search-icon { position: absolute; left: 12px; color: #666; font-size: 14px; }
.search-box input { min-width: 0; flex: 1; height: 100%; padding: 0 2px 0 34px; border: 0; outline: 0; background: transparent; font-size: 16px; }
.search-box button { flex: 0 0 auto; height: 34px; padding: 0; border: 0; background: transparent; cursor: pointer; }
.search-box .clear-search { width: 28px; color: #777; font-size: 14px; }.search-box .submit-search { width: 50px; color: #ff6800; font-size: 16px; }
@media (max-width: 760px) { .search-box { width: 100%; } }
</style>
