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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
/**
 * SearchInterface Module
 * Handles the creation and management of the search UI
 */

class SearchInterface {
    constructor(options) {
        this.options = options;
        this.isVisible = false;
        this.modal = null;
        this.input = null;
        this.resultsContainer = null;
        this.statsContainer = null;
    }

    /**
     * Create the search interface elements
     */
    create() {
        // Check if we're on the search page
        if (this.isSearchPage()) {
            this.enhanceSearchPage();
        } else {
            // On other pages, create the modal for search functionality
            this.createModal();
            this.enhanceSearchButton();
        }
        console.log('βœ… Search interface created');
    }

    /**
     * Check if we're on the search page
     */
    isSearchPage() {
        return window.location.pathname.includes('/search') ||
               window.location.pathname.includes('/search.html') ||
               window.location.pathname.endsWith('search/') ||
               document.querySelector('#search-results') !== null ||
               document.querySelector('.search-page') !== null ||
               document.querySelector('form[action*="search"]') !== null ||
               document.title.toLowerCase().includes('search') ||
               document.querySelector('h1')?.textContent.toLowerCase().includes('search');
    }

    /**
     * Enhance the existing search page using the template structure
     */
    enhanceSearchPage() {
        console.log('πŸ” Enhancing search page using existing template...');
        console.log('πŸ“„ Page URL:', window.location.href);
        console.log('πŸ“‹ Page title:', document.title);

        // Use the template's existing elements
        this.input = document.querySelector('#enhanced-search-page-input');
        this.resultsContainer = document.querySelector('#enhanced-search-page-results');

        console.log('πŸ”Ž Template search input found:', !!this.input);
        console.log('πŸ“¦ Template results container found:', !!this.resultsContainer);

        if (this.input && this.resultsContainer) {
            console.log('βœ… Using existing template structure - no additional setup needed');
            // The template's JavaScript will handle everything
            return;
        }

        // Fallback for non-template pages
        console.log('⚠️ Template elements not found, falling back to generic search page detection');
        this.fallbackToGenericSearchPage();
    }

    /**
     * Fallback for pages that don't use the template
     */
    fallbackToGenericSearchPage() {
        // Find existing search elements on generic pages
        this.input = document.querySelector('#searchbox input[type="text"]') ||
                    document.querySelector('input[name="q"]') ||
                    document.querySelector('.search input[type="text"]');

        // Find or create results container
        this.resultsContainer = document.querySelector('#search-results') ||
                               document.querySelector('.search-results') ||
                               this.createResultsContainer();

        // Create stats container
        this.statsContainer = this.createStatsContainer();

        // Hide default Sphinx search results if they exist
        this.hideDefaultResults();

        // Initialize with empty state
        this.showEmptyState();

        console.log('βœ… Generic search page enhanced');
    }

    /**
     * Create results container if it doesn't exist
     */
    createResultsContainer() {
        const container = document.createElement('div');
        container.id = 'enhanced-search-results';
        container.className = 'enhanced-search-results';

        // Add basic styling to ensure proper positioning
        container.style.cssText = `
            width: 100%;
            max-width: none;
            margin: 1rem 0;
            clear: both;
            position: relative;
            z-index: 1;
        `;

        // Find the best place to insert it within the main content area
        const insertLocation = this.findBestInsertLocation();

        if (insertLocation.parent && insertLocation.method === 'append') {
            insertLocation.parent.appendChild(container);
            console.log(`βœ… Results container added to: ${insertLocation.parent.className || insertLocation.parent.tagName}`);
        } else if (insertLocation.parent && insertLocation.method === 'after') {
            insertLocation.parent.insertAdjacentElement('afterend', container);
            console.log(`βœ… Results container added after: ${insertLocation.parent.className || insertLocation.parent.tagName}`);
        } else {
            // Last resort - create a wrapper in main content
            this.createInMainContent(container);
        }

        return container;
    }

    /**
     * Find the best location to insert search results
     */
    findBestInsertLocation() {
        // Try to find existing search-related elements first
        let searchResults = document.querySelector('.search-results, #search-results');
        if (searchResults) {
            return { parent: searchResults, method: 'append' };
        }

        // Look for search form and place results after it
        let searchForm = document.querySelector('#searchbox, .search form, form[action*="search"]');
        if (searchForm) {
            return { parent: searchForm, method: 'after' };
        }

        // Look for main content containers (common Sphinx/theme classes)
        const mainSelectors = [
            '.document .body',
            '.document .documentwrapper',
            '.content',
            '.main-content',
            '.page-content',
            'main',
            '.container .row .col',
            '.rst-content',
            '.body-content'
        ];

        for (const selector of mainSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                return { parent: element, method: 'append' };
            }
        }

        // Try to find any container that's not the body
        const anyContainer = document.querySelector('.container, .wrapper, .page, #content');
        if (anyContainer) {
            return { parent: anyContainer, method: 'append' };
        }

        return { parent: null, method: null };
    }

    /**
     * Create container in main content as last resort
     */
    createInMainContent(container) {
        // Create a wrapper section
        const wrapper = document.createElement('section');
        wrapper.className = 'search-page-content';
        wrapper.style.cssText = `
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 1rem;
        `;

        // Add a title
        const title = document.createElement('h1');
        title.textContent = 'Search Results';
        title.style.cssText = 'margin-bottom: 1rem;';
        wrapper.appendChild(title);

        // Add the container
        wrapper.appendChild(container);

        // Insert into body, but with proper styling
        document.body.appendChild(wrapper);

        console.log('⚠️ Created search results in body with wrapper - consider improving page structure');
    }

    /**
     * Create stats container
     */
    createStatsContainer() {
        const container = document.createElement('div');
        container.className = 'enhanced-search-stats';
        container.style.cssText = 'margin: 1rem 0; font-size: 0.9rem; color: #666;';

        // Insert before results
        if (this.resultsContainer && this.resultsContainer.parentNode) {
            this.resultsContainer.parentNode.insertBefore(container, this.resultsContainer);
        }

        return container;
    }

    /**
     * Hide default Sphinx search results
     */
    hideDefaultResults() {
        // Hide default search results that Sphinx might show
        const defaultResults = document.querySelectorAll(
            '.search-summary, .search li, #search-results .search, .searchresults'
        );
        defaultResults.forEach(el => {
            el.style.display = 'none';
        });
    }

    /**
     * Create the main search modal (legacy - kept for compatibility)
     */
    createModal() {
        // Enhanced search modal
        const modal = document.createElement('div');
        modal.id = 'enhanced-search-modal';
        modal.className = 'enhanced-search-modal';
        modal.innerHTML = `
            <div class="enhanced-search-backdrop"></div>
            <div class="enhanced-search-container">
                <div class="enhanced-search-header">
                    <div class="enhanced-search-input-wrapper">
                        <i class="fa-solid fa-magnifying-glass search-icon"></i>
                        <input
                            type="text"
                            id="enhanced-search-input"
                            class="enhanced-search-input"
                            placeholder="${this.options.placeholder}"
                            autofocus
                        >
                        <button class="enhanced-search-close" title="Close search">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                    </div>
                    <div class="enhanced-search-stats"></div>
                </div>
                <div class="enhanced-search-results"></div>
                <div class="enhanced-search-footer">
                    <div class="enhanced-search-shortcuts">
                        <span><kbd>↡</kbd> Open</span>
                        <span><kbd>↑</kbd><kbd>↓</kbd> Navigate</span>
                        <span><kbd>Esc</kbd> Close</span>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // Cache references
        this.modal = modal;
        this.input = modal.querySelector('#enhanced-search-input');
        this.resultsContainer = modal.querySelector('.enhanced-search-results');
        this.statsContainer = modal.querySelector('.enhanced-search-stats');

        // Add event handlers for closing the modal
        const closeButton = modal.querySelector('.enhanced-search-close');
        const backdrop = modal.querySelector('.enhanced-search-backdrop');

        if (closeButton) {
            closeButton.addEventListener('click', () => this.hideModal());
        }

        if (backdrop) {
            backdrop.addEventListener('click', () => this.hideModal());
        }

        // Hide modal by default
        modal.style.display = 'none';

        // Initialize with empty state
        this.showEmptyState();
    }

    /**
     * Replace or enhance existing search button to show modal
     */
    enhanceSearchButton() {
        // Find existing search button/form
        const searchForm = document.querySelector('#searchbox form') ||
                          document.querySelector('.search form') ||
                          document.querySelector('form[action*="search"]');

        if (searchForm) {
            // Prevent form submission and show modal instead
            searchForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.showModal();
            });
            console.log('βœ… Search form enhanced to show modal');
        }

        // Find search button specifically and enhance it
        const existingButton = document.querySelector('.search-button-field, .search-button__button');
        if (existingButton) {
            existingButton.addEventListener('click', (e) => {
                e.preventDefault();
                this.showModal();
            });
            console.log('βœ… Search button enhanced to show modal');
        }

        // Also look for search input fields and enhance them
        const searchInput = document.querySelector('#searchbox input[type="text"]') ||
                           document.querySelector('.search input[type="text"]');
        if (searchInput) {
            searchInput.addEventListener('focus', () => {
                this.showModal();
            });
            console.log('βœ… Search input enhanced to show modal on focus');
        }
    }

    /**
     * Show the search interface (focus input or show modal)
     */
    show() {
        if (this.modal) {
            this.showModal();
        } else if (this.input) {
            this.input.focus();
            this.input.select();
        }
    }

    /**
     * Hide the search interface (hide modal or blur input)
     */
    hide() {
        if (this.modal) {
            this.hideModal();
        } else if (this.input) {
            this.input.blur();
        }
    }

    /**
     * Show the modal
     */
    showModal() {
        if (this.modal) {
            this.modal.style.display = 'flex';
            this.modal.classList.add('visible');
            this.isVisible = true;
            // Focus the input after a brief delay to ensure modal is visible
            setTimeout(() => {
                if (this.input) {
                    this.input.focus();
                    this.input.select();
                }
            }, 100);
            console.log('πŸ” Search modal shown');
        }
    }

    /**
     * Hide the modal
     */
    hideModal() {
        if (this.modal) {
            this.modal.classList.remove('visible');
            this.isVisible = false;
            // Hide after animation completes
            setTimeout(() => {
                if (this.modal) {
                    this.modal.style.display = 'none';
                }
            }, 200);
            // Clear any search results
            this.showEmptyState();
            console.log('πŸ” Search modal hidden');
        }
    }

    /**
     * Get the search input element
     */
    getInput() {
        return this.input;
    }

    /**
     * Get the results container
     */
    getResultsContainer() {
        return this.resultsContainer;
    }

    /**
     * Get the stats container
     */
    getStatsContainer() {
        return this.statsContainer;
    }

    /**
     * Get the modal element
     */
    getModal() {
        return this.modal;
    }

    /**
     * Check if modal is visible
     */
    isModalVisible() {
        return this.isVisible && this.modal && this.modal.style.display !== 'none';
    }

    /**
     * Show empty state in results
     */
    showEmptyState() {
        if (this.resultsContainer) {
            this.resultsContainer.innerHTML = `
                <div class="search-empty-state">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <p>Start typing to search documentation...</p>
                    <div class="search-tips">
                        <strong>Search tips:</strong>
                        <ul>
                            <li>Use specific terms for better results</li>
                            <li>Try different keywords if you don't find what you're looking for</li>
                            <li>Search includes titles, content, headings, and tags</li>
                        </ul>
                    </div>
                </div>
            `;
        }
    }

    /**
     * Show no results state
     */
    showNoResults(query) {
        if (this.resultsContainer) {
            this.resultsContainer.innerHTML = `
                <div class="search-no-results">
                    <i class="fa-solid fa-search-minus"></i>
                    <p>No results found for "<strong>${this.escapeHtml(query)}</strong>"</p>
                    <div class="search-suggestions">
                        <strong>Try:</strong>
                        <ul>
                            <li>Checking for typos</li>
                            <li>Using different or more general terms</li>
                            <li>Using fewer keywords</li>
                        </ul>
                    </div>
                </div>
            `;
        }
    }

    /**
     * Show error state
     */
    showError(message = 'Search temporarily unavailable') {
        if (this.resultsContainer) {
            this.resultsContainer.innerHTML = `
                <div class="search-error">
                    <i class="fa-solid fa-exclamation-triangle"></i>
                    <p>${this.escapeHtml(message)}</p>
                </div>
            `;
        }
    }

    /**
     * Update search statistics
     */
    updateStats(query, count) {
        if (this.statsContainer) {
            if (count > 0) {
                this.statsContainer.innerHTML = `${count} result${count !== 1 ? 's' : ''} for "${this.escapeHtml(query)}"`;
            } else {
                this.statsContainer.innerHTML = `No results for "${this.escapeHtml(query)}"`;
            }
        }
    }

    /**
     * Clear search statistics
     */
    clearStats() {
        if (this.statsContainer) {
            this.statsContainer.innerHTML = '';
        }
    }

    /**
     * Get current search query
     */
    getQuery() {
        return this.input ? this.input.value.trim() : '';
    }

    /**
     * Set search query
     */
    setQuery(query) {
        if (this.input) {
            this.input.value = query;
        }
    }

    /**
     * Clear search query
     */
    clearQuery() {
        if (this.input) {
            this.input.value = '';
        }
    }

    /**
     * Focus the search input
     */
    focusInput() {
        if (this.input) {
            this.input.focus();
        }
    }

    /**
     * Get close button for event binding
     */
    getCloseButton() {
        return this.modal ? this.modal.querySelector('.enhanced-search-close') : null;
    }

    /**
     * Get backdrop for event binding
     */
    getBackdrop() {
        return this.modal ? this.modal.querySelector('.enhanced-search-backdrop') : null;
    }

    /**
     * Escape HTML to prevent XSS
     */
    escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    /**
     * Add CSS class to modal
     */
    addModalClass(className) {
        if (this.modal) {
            this.modal.classList.add(className);
        }
    }

    /**
     * Remove CSS class from modal
     */
    removeModalClass(className) {
        if (this.modal) {
            this.modal.classList.remove(className);
        }
    }

    /**
     * Check if modal has class
     */
    hasModalClass(className) {
        return this.modal ? this.modal.classList.contains(className) : false;
    }

    /**
     * Destroy the search interface
     */
    destroy() {
        if (this.modal) {
            this.modal.remove();
            this.modal = null;
            this.input = null;
            this.resultsContainer = null;
            this.statsContainer = null;
        }
        this.isVisible = false;
    }
}

// Make SearchInterface available globally
window.SearchInterface = SearchInterface;