import React, { useState, useRef, useCallback, useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { searchAccommodation, cleanSearchTitle, AccommodationSearchItem, AutocompleteRequest } from '../utils/api'; import { useSearchHistory } from './SearchHistory/useSearchHistory'; import SearchHistoryDropdown from './SearchHistory/SearchHistoryDropdown'; import BusinessNameInputModal from './BusinessNameInputModal'; type SearchType = 'url' | 'name' | 'manual'; export type { SearchType }; const isValidUrl = (string: string): boolean => { try { const url = new URL(string); return url.protocol === 'http:' || url.protocol === 'https:'; } catch { return false; } }; // URL 형태로 판단되는 입력: 프로토콜/www. 시작 또는 도메인 형태(naver.me/xxx 등) const isUrlLike = (value: string): boolean => { const trimmed = value.trim(); return /^(https?:\/\/|www\.)/i.test(trimmed) || /^[a-z0-9-]+(\.[a-z0-9-]+)+([/?#]|$)/i.test(trimmed); }; const sanitizeUrlInput = (value: string): string => { return value.replace(/[^\x00-\x7F]/g, ''); }; // 텍스트 안에 포함된 첫 번째 URL을 추출 (없으면 null) const extractUrl = (text: string): string | null => { const match = text.match(/(https?:\/\/|www\.)[^\s]+/i); return match ? match[0] : null; }; interface SearchInputFormProps { onAnalyze?: (value: string, type: SearchType) => void; onAutocomplete?: (data: AutocompleteRequest) => void; onManualInput?: (businessName: string, address: string, category: string, officialSiteUrl?: string) => void; /** 직접입력 버튼 클릭 시 기본 동작(모달 열기)을 대체합니다. 제공 시 모달을 직접 관리해야 합니다. */ onManualButtonClick?: () => void; error?: string | null; } const SearchInputForm: React.FC = ({ onAnalyze, onAutocomplete, onManualInput, onManualButtonClick, error: externalError, }) => { const { t } = useTranslation(); const [inputValue, setInputValue] = useState(''); const [searchType] = useState('name'); const [isFocused, setIsFocused] = useState(false); const [isManualModalOpen, setIsManualModalOpen] = useState(false); const [localError, setLocalError] = useState(''); const [autocompleteResults, setAutocompleteResults] = useState([]); const [isAutocompleteLoading, setIsAutocompleteLoading] = useState(false); const [showAutocomplete, setShowAutocomplete] = useState(false); const [selectedItem, setSelectedItem] = useState(null); const [highlightedIndex, setHighlightedIndex] = useState(-1); const { filteredHistory, showHistory, openHistory, closeHistory, hideOnInput, deleteItem } = useSearchHistory('name'); const debounceRef = useRef(null); const autocompleteRef = useRef(null); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (autocompleteRef.current && !autocompleteRef.current.contains(event.target as Node)) { setShowAutocomplete(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); const handleAutocompleteSearch = useCallback(async (query: string) => { if (!query.trim()) { setAutocompleteResults([]); setShowAutocomplete(false); return; } setIsAutocompleteLoading(true); try { const response = await searchAccommodation(query); setAutocompleteResults(response.items || []); setShowAutocomplete(response.items && response.items.length > 0); } catch { setAutocompleteResults([]); setShowAutocomplete(false); } finally { setIsAutocompleteLoading(false); } }, []); const handleSelectAutocomplete = (item: AccommodationSearchItem) => { const cleanTitle = cleanSearchTitle(item.title); setInputValue(cleanTitle); setSelectedItem({ ...item, title: cleanTitle }); setShowAutocomplete(false); setAutocompleteResults([]); setHighlightedIndex(-1); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (showAutocomplete && autocompleteResults.length > 0) { switch (e.key) { case 'ArrowDown': e.preventDefault(); setHighlightedIndex(prev => prev < autocompleteResults.length - 1 ? prev + 1 : 0); return; case 'ArrowUp': e.preventDefault(); setHighlightedIndex(prev => prev > 0 ? prev - 1 : autocompleteResults.length - 1); return; case 'Enter': e.preventDefault(); if (highlightedIndex >= 0 && highlightedIndex < autocompleteResults.length) { handleSelectAutocomplete(autocompleteResults[highlightedIndex]); } return; case 'Escape': e.preventDefault(); setShowAutocomplete(false); setHighlightedIndex(-1); return; } } if (e.key === 'Enter') { e.preventDefault(); } }; const handleStart = () => { const trimmed = inputValue.trim(); if (!trimmed) { setLocalError(t('landing.hero.errorInputRequired')); return; } if (isValidUrl(trimmed)) { setLocalError(''); onAnalyze?.(trimmed, 'url'); return; } setLocalError(''); if (selectedItem && onAutocomplete) { onAutocomplete({ address: selectedItem.address, roadAddress: selectedItem.roadAddress, title: selectedItem.title, }); } else if (onAnalyze) { onAnalyze(inputValue, searchType); } }; const applyInputChange = (value: string) => { setInputValue(value); setSelectedItem(null); setHighlightedIndex(-1); hideOnInput(value); if (localError) setLocalError(''); if (debounceRef.current) clearTimeout(debounceRef.current); if (isValidUrl(value)) { setAutocompleteResults([]); setShowAutocomplete(false); } else { debounceRef.current = setTimeout(() => handleAutocompleteSearch(value), 300); } }; // 모바일 키보드 클립보드 추천 등 paste 이벤트 없이 여러 글자가 한 번에 들어오는 경우 처리 const handleChange = (value: string) => { const isBulkInsert = value.length - inputValue.length > 1; if (isBulkInsert) { const extracted = extractUrl(value); if (extracted && extracted !== value.trim()) { applyInputChange(sanitizeUrlInput(extracted)); return; } if (isUrlLike(value)) { const sanitized = sanitizeUrlInput(value); if (sanitized !== value) { applyInputChange(sanitized); return; } } } applyInputChange(value); }; const handlePaste = (e: React.ClipboardEvent) => { const pastedText = e.clipboardData.getData('text'); // 붙여넣은 텍스트에 URL이 포함되어 있고 URL 외 다른 텍스트도 있으면 URL만 추출해서 입력창에 넣기 const extracted = extractUrl(pastedText); if (extracted && extracted !== pastedText.trim()) { e.preventDefault(); applyInputChange(sanitizeUrlInput(extracted)); return; } const input = e.currentTarget; const start = input.selectionStart ?? inputValue.length; const end = input.selectionEnd ?? inputValue.length; const merged = inputValue.slice(0, start) + pastedText + inputValue.slice(end); // 붙여넣은 후 완성될 전체 값이 URL 형태일 때만 비영문 문자 제거 if (!isUrlLike(merged)) return; const sanitized = sanitizeUrlInput(merged); if (sanitized === merged) return; e.preventDefault(); applyInputChange(sanitized); }; const handleManualButtonClick = () => { if (onManualButtonClick) { onManualButtonClick(); } else { setIsManualModalOpen(true); } }; const error = externalError || localError; return (
{/* 유형 라벨 */} {/*
{t('landing.hero.searchTypeLabel')}
*/} {/* 입력 필드 */}
handleChange(e.target.value)} onPaste={handlePaste} onFocus={() => { setIsFocused(true); if (autocompleteResults.length > 0) setShowAutocomplete(true); openHistory(inputValue); }} onBlur={() => { setIsFocused(false); setTimeout(() => closeHistory(), 150); }} onKeyDown={handleKeyDown} placeholder={t('landing.hero.placeholderCombined')} className={`hero-input ${inputValue ? 'has-value' : ''}`} /> {/* 최근 검색 히스토리 */} {showHistory && !showAutocomplete && ( { closeHistory(); setInputValue(item.value); if (item.type === 'name') { setSelectedItem({ title: item.value, address: item.address || '', roadAddress: item.roadAddress || '' }); } }} onDelete={(e, value) => { e.preventDefault(); e.stopPropagation(); deleteItem(value); }} className="hero-autocomplete-dropdown" itemClassName="hero-autocomplete-item" titleClassName="hero-autocomplete-title" addressClassName="hero-autocomplete-address" /> )} {/* 자동완성 결과 */} {showAutocomplete && (
{isAutocompleteLoading ? (
{t('landing.hero.searching')}
) : ( autocompleteResults.map((item, index) => ( )) )}
)}
{/* 입력 clear 버튼 */} {inputValue && ( )}
{t('landing.hero.guideCombined')} {error &&

{error}

}
또는
e.key === 'Enter' && handleManualButtonClick()}> {t('landing.hero.searchTypeManual')}

{t('landing.hero.manualButtonDesc')}

{/* onManualButtonClick 미제공 시 모달을 내부에서 관리 */} {!onManualButtonClick && isManualModalOpen && ( setIsManualModalOpen(false)} onSubmit={(businessName, address, category, officialSiteUrl) => { setIsManualModalOpen(false); onManualInput?.(businessName, address, category, officialSiteUrl); }} /> )}
); }; export default SearchInputForm;