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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
import React, { useState, useEffect, useCallback } from 'react';

interface Client {
  name: string;
  parentCode: string;
}

interface ClientLookupComponentProps {
  onClientSelect?: (client: Client) => void;
  onClientOnboard?: (client: Client) => void;
  placeholder?: string;
  className?: string;
}

const ClientLookupComponent: React.FC<ClientLookupComponentProps> = ({
  onClientSelect,
  onClientOnboard,
  placeholder = "Search by client name or parent code...",
  className = ""
}) => {
  // Master dataset
  const masterClients: Client[] = [
    { name: "Operating Engineers Health and Welfare Fund", parentCode: "OEF" },
    { name: "ANSTED", parentCode: "AMS" },
    { name: "AllianceRx Walgreens Prime", parentCode: "ARX" },
    { name: "Avnet, Inc.", parentCode: "AVN" },
    { name: "Chevron", parentCode: "CHV" },
    { name: "Maryland", parentCode: "MDH" },
    { name: "Empire Plan", parentCode: "NYS" }
  ];

  const [searchTerm, setSearchTerm] = useState('');
  const [filteredClients, setFilteredClients] = useState<Client[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const [hasSearched, setHasSearched] = useState(false);
  const [showOnboardingModal, setShowOnboardingModal] = useState(false);
  const [newClientName, setNewClientName] = useState('');
  const [newClientCode, setNewClientCode] = useState('');
  const [onboardingError, setOnboardingError] = useState('');

  // Debug: Log master data on component mount
  useEffect(() => {
    console.log('ClientLookupComponent mounted with master clients:', masterClients);
  }, []);

  // Debounced search function
  const performSearch = async (term: string) => {
    console.log('performSearch called with:', term); // Debug log
    
    if (!term.trim()) {
      setFilteredClients([]);
      setShowResults(false);
      setHasSearched(false);
      return;
    }

    setIsLoading(true);
    setShowResults(true);
    setHasSearched(true);
    setSelectedIndex(-1);

    // Simulate 2-second loading
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Filter clients based on search term
    const searchTerm = term.toLowerCase().trim();
    console.log('Searching for:', searchTerm); // Debug log
    console.log('Master clients:', masterClients); // Debug log
    
    const filtered = masterClients.filter(client => {
      const nameMatch = client.name.toLowerCase().includes(searchTerm);
      const codeMatch = client.parentCode.toLowerCase().includes(searchTerm);
      console.log(`Client: ${client.name} (${client.parentCode}) - Name match: ${nameMatch}, Code match: ${codeMatch}`); // Debug log
      return nameMatch || codeMatch;
    });

    console.log('Filtered results:', filtered); // Debug log
    setFilteredClients(filtered);
    setIsLoading(false);
  };

  // Debounced search effect
  useEffect(() => {
    console.log('Search term changed:', searchTerm); // Debug log
    const timer = setTimeout(() => {
      console.log('Debounce timer triggered for:', searchTerm); // Debug log
      performSearch(searchTerm);
    }, 300); // 300ms debounce

    return () => {
      console.log('Clearing timer for:', searchTerm); // Debug log
      clearTimeout(timer);
    };
  }, [searchTerm]);

  const handleClientSelect = (client: Client) => {
    // Clear all search state to close the widget
    setSearchTerm('');
    setShowResults(false);
    setSelectedIndex(-1);
    setFilteredClients([]);
    setHasSearched(false);
    
    // Call the parent component's selection handler
    if (onClientSelect) {
      onClientSelect(client);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!showResults || filteredClients.length === 0) return;

    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setSelectedIndex(prev => 
          prev < filteredClients.length - 1 ? prev + 1 : prev
        );
        break;
      case 'ArrowUp':
        e.preventDefault();
        setSelectedIndex(prev => prev > 0 ? prev - 1 : -1);
        break;
      case 'Enter':
        e.preventDefault();
        if (selectedIndex >= 0 && selectedIndex < filteredClients.length) {
          handleClientSelect(filteredClients[selectedIndex]);
        }
        break;
      case 'Escape':
        setShowResults(false);
        setSelectedIndex(-1);
        break;
    }
  };

  const highlightText = (text: string, term: string) => {
    if (!term) return text;
    
    const regex = new RegExp(`(${term})`, 'gi');
    const parts = text.split(regex);
    
    return parts.map((part, index) => 
      regex.test(part) ? (
        <span key={index} style={{ 
          backgroundColor: '#fef3c7', 
          fontWeight: 'bold',
          color: '#92400e'
        }}>
          {part}
        </span>
      ) : part
    );
  };

  const handleClientOnboarding = () => {
    setShowOnboardingModal(true);
    setNewClientName('');
    setNewClientCode('');
    setOnboardingError('');
  };

  const handleOnboardingSubmit = () => {
    // Validate inputs
    if (!newClientName.trim()) {
      setOnboardingError('Client name is required');
      return;
    }
    if (!newClientCode.trim()) {
      setOnboardingError('Parent code is required');
      return;
    }

    // Check if parent code already exists
    const existingClient = masterClients.find(
      client => client.parentCode.toLowerCase() === newClientCode.trim().toLowerCase()
    );
    if (existingClient) {
      setOnboardingError('Parent code already exists');
      return;
    }

    const newClient: Client = {
      name: newClientName.trim(),
      parentCode: newClientCode.trim().toUpperCase()
    };

    // Close modal and reset form
    setShowOnboardingModal(false);
    setNewClientName('');
    setNewClientCode('');
    setOnboardingError('');
    
    // Clear all search state
    setSearchTerm('');
    setShowResults(false);
    setFilteredClients([]);
    setHasSearched(false);
    setSelectedIndex(-1);

    // Call the onboarding callback
    if (onClientOnboard) {
      onClientOnboard(newClient);
    }
  };

  const handleOnboardingCancel = () => {
    setShowOnboardingModal(false);
    setNewClientName('');
    setNewClientCode('');
    setOnboardingError('');
  };

  return (
    <div className={className} style={{ position: 'relative', width: '100%' }}>
      {/* Search Input */}
      <div style={{ position: 'relative' }}>
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          style={{
            width: '100%',
            padding: '12px 16px',
            paddingRight: '40px',
            borderRadius: '8px',
            border: '2px solid #d1d5db',
            fontSize: '16px',
            transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
            outline: 'none',
            ...(showResults && {
              borderColor: '#667eea',
              boxShadow: '0 0 0 3px rgba(102, 126, 234, 0.1)'
            })
          }}
          onFocus={() => {
            if (hasSearched && searchTerm.trim()) {
              setShowResults(true);
            }
          }}
        />
        
        {/* Search Icon / Test Button */}
        <div style={{
          position: 'absolute',
          right: '12px',
          top: '50%',
          transform: 'translateY(-50%)',
          color: '#9ca3af'
        }}>
          {searchTerm ? (
            <button
              onClick={() => performSearch(searchTerm)}
              style={{
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                fontSize: '14px',
                color: '#667eea',
                padding: '2px'
              }}
              title="Force search"
            >
              πŸ”
            </button>
          ) : (
            'πŸ”'
          )}
        </div>
      </div>

      {/* Results Dropdown */}
      {showResults && (
        <div style={{
          position: 'absolute',
          top: '100%',
          left: 0,
          right: 0,
          background: 'white',
          border: '2px solid #667eea',
          borderTop: 'none',
          borderRadius: '0 0 8px 8px',
          boxShadow: '0 8px 25px rgba(0, 0, 0, 0.15)',
          zIndex: 1000,
          maxHeight: '300px',
          overflowY: 'auto'
        }}>
          {isLoading ? (
            // Loading State
            <div style={{
              padding: '20px',
              textAlign: 'center',
              color: '#6b7280'
            }}>
              <div style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '12px'
              }}>
                <div style={{
                  width: '20px',
                  height: '20px',
                  border: '2px solid #f3f4f6',
                  borderTop: '2px solid #667eea',
                  borderRadius: '50%',
                  animation: 'spin 1s linear infinite'
                }} />
                <span>Searching clients...</span>
              </div>
              
              <style>
                {`
                  @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                  }
                `}
              </style>
            </div>
          ) : filteredClients.length > 0 ? (
            // Results List
            <div>
              <div style={{
                padding: '8px 16px',
                backgroundColor: '#f8fafc',
                borderBottom: '1px solid #e2e8f0',
                fontSize: '12px',
                fontWeight: '600',
                color: '#6b7280',
                textTransform: 'uppercase',
                letterSpacing: '0.5px'
              }}>
                {filteredClients.length} Client{filteredClients.length !== 1 ? 's' : ''} Found
              </div>
              
              {filteredClients.map((client, index) => (
                <div
                  key={`${client.parentCode}-${index}`}
                  onClick={() => handleClientSelect(client)}
                  style={{
                    padding: '12px 16px',
                    cursor: 'pointer',
                    borderBottom: index < filteredClients.length - 1 ? '1px solid #f3f4f6' : 'none',
                    backgroundColor: selectedIndex === index ? '#f0f9ff' : 'white',
                    transition: 'background-color 0.2s ease'
                  }}
                  onMouseEnter={() => setSelectedIndex(index)}
                  onMouseLeave={() => setSelectedIndex(-1)}
                >
                  <div style={{
                    fontWeight: '600',
                    color: '#1f2937',
                    marginBottom: '4px',
                    fontSize: '14px'
                  }}>
                    {highlightText(client.name, searchTerm.trim())}
                  </div>
                  
                  <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px'
                  }}>
                    <span style={{
                      fontSize: '12px',
                      color: '#6b7280'
                    }}>
                      Parent Code:
                    </span>
                    <span style={{
                      fontSize: '12px',
                      fontWeight: '600',
                      color: '#667eea',
                      backgroundColor: '#ede9fe',
                      padding: '2px 6px',
                      borderRadius: '4px'
                    }}>
                      {highlightText(client.parentCode, searchTerm.trim())}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            // No Results with Onboarding Option
            <div style={{
              padding: '20px',
              textAlign: 'center',
              color: '#6b7280'
            }}>
              <div style={{ fontSize: '24px', marginBottom: '8px' }}>πŸ”</div>
              <div style={{ fontWeight: '600', marginBottom: '4px' }}>
                No clients found
              </div>
              <div style={{ fontSize: '14px', marginBottom: '16px' }}>
                Try searching with a different client name or parent code
              </div>
              
              {/* Onboarding Button */}
              <button
                onClick={handleClientOnboarding}
                style={{
                  backgroundColor: '#667eea',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  padding: '10px 16px',
                  fontSize: '14px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'background-color 0.2s ease',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  margin: '0 auto'
                }}
                onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#5a67d8'}
                onMouseOut={(e) => e.currentTarget.style.backgroundColor = '#667eea'}
              >
                <span>βž•</span>
                Onboarding new Client
              </button>
            </div>
          )}
        </div>
      )}

      {/* Search Tips */}
      {searchTerm && !showResults && !hasSearched && (
        <div style={{
          position: 'absolute',
          top: '100%',
          left: 0,
          right: 0,
          background: '#f8fafc',
          border: '1px solid #e2e8f0',
          borderRadius: '0 0 8px 8px',
          padding: '12px 16px',
          fontSize: '12px',
          color: '#6b7280',
          zIndex: 999
        }}>
          πŸ’‘ Press Enter or wait to search for clients matching "{searchTerm}"
        </div>
      )}

      {/* Onboarding Modal */}
      {showOnboardingModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          zIndex: 2000,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '12px',
            padding: '24px',
            width: '90%',
            maxWidth: '500px',
            boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
            position: 'relative'
          }}>
            {/* Modal Header */}
            <div style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              marginBottom: '20px'
            }}>
              <h3 style={{
                margin: 0,
                fontSize: '18px',
                fontWeight: '600',
                color: '#1f2937'
              }}>
                Onboard New Client
              </h3>
              <button
                onClick={handleOnboardingCancel}
                style={{
                  background: 'none',
                  border: 'none',
                  fontSize: '20px',
                  cursor: 'pointer',
                  color: '#9ca3af',
                  padding: '4px'
                }}
              >
                βœ•
              </button>
            </div>

            {/* Error Message */}
            {onboardingError && (
              <div style={{
                backgroundColor: '#fef2f2',
                border: '1px solid #fecaca',
                borderRadius: '6px',
                padding: '12px',
                marginBottom: '16px',
                color: '#dc2626',
                fontSize: '14px'
              }}>
                {onboardingError}
              </div>
            )}

            {/* Form Fields */}
            <div style={{ marginBottom: '16px' }}>
              <label style={{
                display: 'block',
                fontSize: '14px',
                fontWeight: '600',
                color: '#374151',
                marginBottom: '6px'
              }}>
                Client Name *
              </label>
              <input
                type="text"
                value={newClientName}
                onChange={(e) => setNewClientName(e.target.value)}
                placeholder="Enter client name"
                style={{
                  width: '100%',
                  padding: '10px 12px',
                  border: '2px solid #d1d5db',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s ease',
                  boxSizing: 'border-box'
                }}
                onFocus={(e) => e.currentTarget.style.borderColor = '#667eea'}
                onBlur={(e) => e.currentTarget.style.borderColor = '#d1d5db'}
              />
            </div>

            <div style={{ marginBottom: '24px' }}>
              <label style={{
                display: 'block',
                fontSize: '14px',
                fontWeight: '600',
                color: '#374151',
                marginBottom: '6px'
              }}>
                Parent Code *
              </label>
              <input
                type="text"
                value={newClientCode}
                onChange={(e) => setNewClientCode(e.target.value.toUpperCase())}
                placeholder="Enter parent code (e.g., ABC)"
                maxLength={10}
                style={{
                  width: '100%',
                  padding: '10px 12px',
                  border: '2px solid #d1d5db',
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none',
                  transition: 'border-color 0.2s ease',
                  textTransform: 'uppercase',
                  boxSizing: 'border-box'
                }}
                onFocus={(e) => e.currentTarget.style.borderColor = '#667eea'}
                onBlur={(e) => e.currentTarget.style.borderColor = '#d1d5db'}
              />
            </div>

            {/* Modal Actions */}
            <div style={{
              display: 'flex',
              gap: '12px',
              justifyContent: 'flex-end'
            }}>
              <button
                onClick={handleOnboardingCancel}
                style={{
                  backgroundColor: 'white',
                  color: '#6b7280',
                  border: '2px solid #d1d5db',
                  borderRadius: '6px',
                  padding: '10px 20px',
                  fontSize: '14px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease'
                }}
                onMouseOver={(e) => {
                  e.currentTarget.style.backgroundColor = '#f9fafb';
                  e.currentTarget.style.borderColor = '#9ca3af';
                }}
                onMouseOut={(e) => {
                  e.currentTarget.style.backgroundColor = 'white';
                  e.currentTarget.style.borderColor = '#d1d5db';
                }}
              >
                Cancel
              </button>
              <button
                onClick={handleOnboardingSubmit}
                style={{
                  backgroundColor: '#667eea',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  padding: '10px 20px',
                  fontSize: '14px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'background-color 0.2s ease'
                }}
                onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#5a67d8'}
                onMouseOut={(e) => e.currentTarget.style.backgroundColor = '#667eea'}
              >
                Onboard Client
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ClientLookupComponent;