File size: 9,673 Bytes
da50982
1755110
32848dd
0f84bab
1755110
 
 
e8b2dd9
1755110
 
 
 
 
 
2036b1c
 
da50982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca5c7a4
 
 
 
 
 
da50982
 
2036b1c
 
da50982
 
 
 
 
ca5c7a4
2036b1c
da50982
 
1755110
 
e8b2dd9
1755110
 
 
 
 
 
2036b1c
da50982
2036b1c
0079c66
da50982
1755110
da50982
 
 
 
 
 
 
 
 
 
 
2036b1c
 
 
 
 
 
 
 
 
 
 
 
 
 
a3c4ae7
 
 
 
 
 
 
2036b1c
 
 
 
 
 
 
 
 
 
da50982
2036b1c
a3c4ae7
da50982
 
 
1755110
da50982
2036b1c
da50982
 
 
 
1755110
 
 
da50982
1755110
 
 
 
 
da50982
 
 
 
 
1755110
 
0079c66
1755110
 
 
0f84bab
 
1755110
 
 
 
1879400
da50982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2036b1c
da50982
2036b1c
 
 
 
 
 
da50982
 
 
a860f16
d95ad15
a860f16
 
 
da50982
 
 
 
 
 
 
 
1755110
0f84bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8b2dd9
 
 
 
 
 
 
 
1755110
32848dd
e8b2dd9
 
 
 
 
 
 
32848dd
 
 
 
 
 
 
e8b2dd9
 
 
 
 
 
 
 
 
 
1755110
0079c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1755110
 
 
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import { useState, useRef, useEffect } from 'react';
import { Plus, Trash, Activity } from 'lucide-react';
import Sparkline from './Sparkline';
import Logo from './Logo';

interface WatchlistSidebarProps {
  watchlist: string[];
  watchlistQuotes: Record<string, { price: number; changePercent: number }>;
  activeTicker: string;
  onSelectTicker: (ticker: string) => void;
  onAddTicker: (ticker: string) => Promise<void>;
  onRemoveTicker: (ticker: string) => Promise<void>;
}

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';

// Typo mapping to automatically resolve company names to correct tickers
const TYPO_MAP: Record<string, string> = {
  "GOOGLE": "GOOGL",
  "ALPHABET": "GOOGL",
  "FACEBOOK": "META",
  "META PLATFORMS": "META",
  "APPLE": "AAPL",
  "AMAZON": "AMZN",
  "MICROSOFT": "MSFT",
  "NETFLIX": "NFLX",
  "TESLA": "TSLA",
  "RELIANCE": "RELIANCE.NS",
  "TCS": "TCS.NS",
  "TATA CONSULTANCY": "TCS.NS",
  "INFOSYS": "INFY",
  "NVIDIA": "NVDA",
  "AMD": "AMD",
  "INTEL": "INTC",
  "ADOBE": "ADBE",
  "SALESFORCE": "CRM",
  "COCA COLA": "KO",
  "PEPSI": "PEP",
  "ADANI": "ADANIENT.NS",
  "ADANI ENTERPRISES": "ADANIENT.NS",
  "ADANIENT": "ADANIENT.NS",
  "ADANIPORTS": "ADANIPORTS.NS",
  "ADANIPOWER": "ADANIPOWER.NS"
};

// Popular default suggestions to show when search is empty
const DEFAULT_SUGGESTIONS = [
  { symbol: "AAPL", name: "Apple Inc." },
  { symbol: "TSLA", name: "Tesla Inc." },
  { symbol: "META", name: "Meta Platforms" },
  { symbol: "GOOGL", name: "Alphabet (Google)" },
  { symbol: "MSFT", name: "Microsoft Corp." },
  { symbol: "ADANIENT.NS", name: "Adani Enterprises" },
  { symbol: "RELIANCE.NS", name: "Reliance Industries" }
];

export default function WatchlistSidebar({
  watchlist,
  watchlistQuotes,
  activeTicker,
  onSelectTicker,
  onAddTicker,
  onRemoveTicker,
}: WatchlistSidebarProps) {
  const [newTicker, setNewTicker] = useState('');
  const [suggestions, setSuggestions] = useState<{ symbol: string; name: string }[]>([]);
  const [showDropdown, setShowDropdown] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tickerToDelete, setTickerToDelete] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown on click outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowDropdown(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Debounced dynamic search from Yahoo Finance proxy API
  useEffect(() => {
    const query = newTicker.trim();
    if (query.length < 2) {
      setSuggestions([]);
      return;
    }

    const delayDebounce = setTimeout(async () => {
      setLoading(true);
      try {
        const response = await fetch(`${API_URL}/api/v1/stocks/search?q=${encodeURIComponent(query)}`);
        if (response.ok) {
          const data = await response.json();
          if (Array.isArray(data)) {
            setSuggestions(data);
          } else {
            setSuggestions([]);
          }
        } else {
          setSuggestions([]);
        }
      } catch (err) {
        console.error('Error fetching stock suggestions:', err);
      } finally {
        setLoading(false);
      }
    }, 300);

    return () => clearTimeout(delayDebounce);
  }, [newTicker]);

  // Determine what suggestions to display
  const displaySuggestions = (newTicker.trim().length >= 2 && Array.isArray(suggestions)) ? suggestions : DEFAULT_SUGGESTIONS;

  const handleAdd = async (ticker: string) => {
    let cleanTicker = ticker.trim().toUpperCase();
    if (!cleanTicker) return;

    // Apply auto-correct map if matched
    if (TYPO_MAP[cleanTicker]) {
      cleanTicker = TYPO_MAP[cleanTicker];
    }

    try {
      await onAddTicker(cleanTicker);
      setNewTicker('');
      setShowDropdown(false);
    } catch (err) {
      console.error('Error adding ticker:', err);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    handleAdd(newTicker);
  };

  const handleRemove = async (ticker: string, e: React.MouseEvent) => {
    e.stopPropagation(); // Avoid selecting as active ticker
    setTickerToDelete(ticker);
  };

  return (
    <section className="left-sidebar glass-panel watchlist-container" style={{ position: 'relative', overflow: 'hidden' }}>
      <div className="panel-title" style={{ position: 'relative', zIndex: 2 }}>
        <span>Watchlist</span>
        <Activity size={18} color="#94a3b8" />
      </div>
      
      <div style={{ position: 'relative', zIndex: 10 }} ref={dropdownRef}>
        <form className="watchlist-search" onSubmit={handleSubmit}>
          <input 
            type="text" 
            placeholder="Add ticker (e.g. AAPL)..."
            value={newTicker}
            onChange={(e) => {
              setNewTicker(e.target.value);
              setShowDropdown(true);
            }}
            onFocus={() => setShowDropdown(true)}
          />
          <button className="add-btn" type="submit" aria-label="Add ticker">
            <Plus size={18} />
          </button>
        </form>

        {showDropdown && displaySuggestions.length > 0 && (
          <div className="suggestions-dropdown">
            {loading && (
              <div style={{ padding: '8px 14px', fontSize: '11px', color: 'var(--text-muted)' }}>
                Searching global markets...
              </div>
            )}
            {displaySuggestions.map((item) => (
              <div 
                key={item.symbol} 
                className="suggestion-item"
                onMouseDown={(e) => {
                  e.preventDefault(); // Keep input focused & prevent unmount before state updates
                  setNewTicker(item.symbol);
                  setShowDropdown(false);
                }}
              >
                <span className="suggestion-symbol">{item.symbol}</span>
                <span className="suggestion-name">{item.name}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Subtle background Logo watermark */}
      <div style={{
        position: 'absolute',
        top: '60%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        opacity: 0.035,
        pointerEvents: 'none',
        zIndex: 1,
        userSelect: 'none'
      }}>
        <Logo size={180} />
      </div>

      <div className="watchlist-items" style={{ position: 'relative', zIndex: 2 }}>
        {watchlist.map((ticker) => {
          const quote = watchlistQuotes ? watchlistQuotes[ticker] : null;
          const isPositive = quote ? quote.changePercent >= 0 : true;
          return (
            <div 
              key={ticker}
              className={`watchlist-item ${activeTicker === ticker ? 'active' : ''}`}
              onClick={() => onSelectTicker(ticker)}
            >
              <div style={{ display: 'flex', flexDirection: 'column', gap: '2px', alignItems: 'flex-start', flex: 1 }}>
                <span className="ticker-symbol">{ticker}</span>
                {quote && (
                  <span className={`ticker-quote-badge ${isPositive ? 'text-bull' : 'text-bear'}`} style={{ fontSize: '11px', fontWeight: 500 }}>
                    ${quote.price.toFixed(2)} ({isPositive ? '+' : ''}{quote.changePercent.toFixed(2)}%)
                  </span>
                )}
              </div>

              {quote && (
                <div style={{ marginRight: '6px', display: 'flex', alignItems: 'center' }}>
                  <Sparkline symbol={ticker} change={quote.changePercent} width={60} height={20} />
                </div>
              )}

              <button 
                className="delete-ticker-btn"
                onClick={(e) => handleRemove(ticker, e)}
                aria-label={`Remove ${ticker} from watchlist`}
              >
                <Trash size={14} />
              </button>
            </div>
          );
        })}
      </div>

      {tickerToDelete && (
        <div className="custom-modal-overlay">
          <div className="custom-modal-content glass-panel liquid-glass animate-fade-rise" style={{ border: '1px solid rgba(255, 23, 68, 0.3)' }}>
            <h3 style={{ fontSize: '18px', fontWeight: 600, color: 'var(--text-primary)', marginBottom: '12px' }}>
              Confirm Deletion
            </h3>
            <p style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '24px', lineHeight: '150%' }}>
              Are you sure you want to remove <strong style={{ color: 'var(--neon-cyan)' }}>{tickerToDelete}</strong> from your watchlist?
            </p>
            <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
              <button 
                onClick={() => setTickerToDelete(null)}
                className="modal-cancel-btn"
              >
                Cancel
              </button>
              <button 
                onClick={async () => {
                  const ticker = tickerToDelete;
                  setTickerToDelete(null);
                  try {
                    await onRemoveTicker(ticker);
                  } catch (err) {
                    console.error('Error removing ticker:', err);
                  }
                }}
                className="modal-confirm-btn"
              >
                Remove
              </button>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}