File size: 8,160 Bytes
0c591a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import { useState, useEffect, useRef, useCallback } from "react"
import { cn } from "@/lib/utils"
import { Input } from "@/components/ui/input"
import { Search, X, Check, Loader2, ChevronLeft, ChevronRight } from "lucide-react"
import { searchStocks, StockResult } from "@/lib/api"

interface StockSearchProps {
  onSelect: (stock: StockResult) => void
  disabled?: boolean
  selectedStock?: StockResult | null
  onClear?: () => void
  onSearchChange?: (isSearching: boolean) => void
}

export function StockSearch({
  onSelect,
  disabled = false,
  selectedStock,
  onClear,
  onSearchChange,
}: StockSearchProps) {
  const [query, setQuery] = useState("")
  const [results, setResults] = useState<StockResult[]>([])
  const [isOpen, setIsOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [highlightedIndex, setHighlightedIndex] = useState(0)
  const inputRef = useRef<HTMLInputElement>(null)
  const listRef = useRef<HTMLDivElement>(null)
  const debounceRef = useRef<NodeJS.Timeout>()
  const nameScrollRef = useRef<HTMLDivElement>(null)

  const scrollName = (direction: 'left' | 'right') => {
    if (nameScrollRef.current) {
      const scrollAmount = direction === 'left' ? -80 : 80
      nameScrollRef.current.scrollBy({ left: scrollAmount, behavior: 'smooth' })
    }
  }

  // Debounced search
  const performSearch = useCallback(async (searchQuery: string) => {
    if (searchQuery.length < 1) {
      setResults([])
      setIsOpen(false)
      return
    }

    setIsLoading(true)
    try {
      const response = await searchStocks(searchQuery)
      setResults(response.results)
      setIsOpen(response.results.length > 0)
      setHighlightedIndex(0)
    } catch (error) {
      console.error("Stock search error:", error)
      setResults([])
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => {
    if (debounceRef.current) {
      clearTimeout(debounceRef.current)
    }

    debounceRef.current = setTimeout(() => {
      performSearch(query)
    }, 150) // 150ms debounce

    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current)
      }
    }
  }, [query, performSearch])

  // Notify parent when search state changes
  useEffect(() => {
    onSearchChange?.(query.length > 0)
  }, [query, onSearchChange])

  // Keyboard navigation
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!isOpen) return

    switch (e.key) {
      case "ArrowDown":
        e.preventDefault()
        setHighlightedIndex((prev) =>
          prev < results.length - 1 ? prev + 1 : prev
        )
        break
      case "ArrowUp":
        e.preventDefault()
        setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : 0))
        break
      case "Enter":
        e.preventDefault()
        if (results[highlightedIndex]) {
          handleSelect(results[highlightedIndex])
        }
        break
      case "Escape":
        e.preventDefault()
        setIsOpen(false)
        inputRef.current?.blur()
        break
    }
  }

  const handleSelect = (stock: StockResult) => {
    onSelect(stock)
    setQuery("")
    setIsOpen(false)
    setResults([])
  }

  const handleClear = () => {
    setQuery("")
    setResults([])
    setIsOpen(false)
    onClear?.()
    inputRef.current?.focus()
  }

  // Close on click outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        listRef.current &&
        !listRef.current.contains(e.target as Node) &&
        inputRef.current &&
        !inputRef.current.contains(e.target as Node)
      ) {
        setIsOpen(false)
      }
    }

    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])

  // Show selected stock
  if (selectedStock) {
    return (
      <div className="relative">
        <div className="flex items-center gap-1 px-2 py-2 bg-card border border-border rounded-lg">
          <Check className="w-4 h-4 text-emerald-500 shrink-0" />
          <button
            onClick={() => scrollName('left')}
            className="shrink-0 p-0.5 hover:bg-muted rounded transition-colors"
          >
            <ChevronLeft className="w-3 h-3 text-muted-foreground" />
          </button>
          <div
            ref={nameScrollRef}
            className="flex-1 overflow-x-auto whitespace-nowrap scrollbar-hide"
            style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
          >
            <span className="font-medium text-foreground text-sm">
              {selectedStock.name}
            </span>
            <span className="text-muted-foreground text-sm ml-1">
              ({selectedStock.symbol})
            </span>
          </div>
          <button
            onClick={() => scrollName('right')}
            className="shrink-0 p-0.5 hover:bg-muted rounded transition-colors"
          >
            <ChevronRight className="w-3 h-3 text-muted-foreground" />
          </button>
          <span className="text-xs text-muted-foreground px-1.5 py-0.5 bg-muted rounded shrink-0">
            {selectedStock.exchange}
          </span>
          {!disabled && (
            <button
              onClick={handleClear}
              className="p-0.5 hover:bg-muted rounded transition-colors shrink-0"
            >
              <X className="w-4 h-4 text-muted-foreground" />
            </button>
          )}
        </div>
      </div>
    )
  }

  return (
    <div className="relative">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <Input
          ref={inputRef}
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={handleKeyDown}
          onFocus={() => query.length > 0 && results.length > 0 && setIsOpen(true)}
          placeholder="Search U.S. listed companies..."
          disabled={disabled}
          className="pl-10 pr-10 bg-background border-input text-foreground focus:border-primary"
        />
        {isLoading && (
          <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground animate-spin" />
        )}
        {!isLoading && query && (
          <button
            onClick={() => {
              setQuery("")
              setResults([])
              setIsOpen(false)
            }}
            className="absolute right-3 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded"
          >
            <X className="w-4 h-4 text-muted-foreground" />
          </button>
        )}
      </div>

      {/* Dropdown */}
      {isOpen && results.length > 0 && (
        <div
          ref={listRef}
          className="absolute z-50 w-full mt-1 bg-card border border-border rounded-lg shadow-xl overflow-hidden"
        >
          <div className="max-h-64 overflow-y-auto">
            {results.map((stock, index) => (
              <button
                key={stock.symbol}
                onClick={() => handleSelect(stock)}
                onMouseEnter={() => setHighlightedIndex(index)}
                className={cn(
                  "w-full flex items-center gap-3 px-3 py-2 text-left transition-colors",
                  index === highlightedIndex
                    ? "bg-muted"
                    : "hover:bg-muted/50"
                )}
              >
                <span className="font-mono font-medium text-foreground min-w-[60px]">
                  {stock.symbol}
                </span>
                <span className="flex-1 text-sm text-muted-foreground truncate">
                  {stock.name}
                </span>
                <span className="text-xs text-muted-foreground px-2 py-0.5 bg-muted rounded">
                  {stock.exchange}
                </span>
              </button>
            ))}
          </div>
          <div className="px-3 py-2 border-t border-border text-xs text-muted-foreground">
            ↑↓ navigate · Enter select · Esc close
          </div>
        </div>
      )}
    </div>
  )
}

export default StockSearch