@extends('layouts.master')

@section('title', 'Help Center')

@section('content')
<div class="container-fluid">
    <!-- Hero Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="help-hero">
                <div class="help-hero-content">
                    <h1 class="display-5 fw-bold mb-3">
                        <i class="fas fa-balance-scale me-3"></i>
                        How can we help you today?
                    </h1>
                    <p class="lead mb-4">Search our knowledge base or browse categories below</p>
                    
                    <!-- Enhanced Search Bar -->
                    <div class="row justify-content-center">
                        <div class="col-lg-8">
                            <div class="search-wrapper">
                                <i class="fas fa-search search-icon"></i>
                                <input type="text" class="form-control form-control-lg search-input" 
                                       id="helpSearch" 
                                       placeholder="Search for help articles, FAQs, or topics..."
                                       autocomplete="off">
                                <div id="searchResults" class="search-results-dropdown"></div>
                            </div>
                            <!-- Quick Links -->
                            <div class="quick-links mt-3">
                                <span class="text-muted me-2">Popular:</span>
                                <a href="#" class="badge bg-light text-dark me-2" data-search="case management">Case Management</a>
                                <a href="#" class="badge bg-light text-dark me-2" data-search="billing">Billing & Invoicing</a>
                                <a href="#" class="badge bg-light text-dark me-2" data-search="document">Document Templates</a>
                                <a href="#" class="badge bg-light text-dark" data-search="calendar">Calendar & Scheduling</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Access Cards -->
    <div class="row mb-5">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="quick-access-card" data-category="getting-started">
                <div class="icon-wrapper bg-primary-soft">
                    <i class="fas fa-rocket text-primary"></i>
                </div>
                <h5 class="mt-3">Getting Started</h5>
                <p class="text-muted small mb-0">Setup guides and onboarding</p>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="quick-access-card" data-category="video-tutorials">
                <div class="icon-wrapper bg-danger-soft">
                    <i class="fas fa-play-circle text-danger"></i>
                </div>
                <h5 class="mt-3">Video Tutorials</h5>
                <p class="text-muted small mb-0">Watch step-by-step guides</p>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="quick-access-card" data-category="best-practices">
                <div class="icon-wrapper bg-success-soft">
                    <i class="fas fa-lightbulb text-success"></i>
                </div>
                <h5 class="mt-3">Best Practices</h5>
                <p class="text-muted small mb-0">Tips from legal experts</p>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="quick-access-card" data-category="troubleshooting">
                <div class="icon-wrapper bg-warning-soft">
                    <i class="fas fa-tools text-warning"></i>
                </div>
                <h5 class="mt-3">Troubleshooting</h5>
                <p class="text-muted small mb-0">Fix common issues</p>
            </div>
        </div>
    </div>

    <!-- Help Topics with Tabs -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <!-- Tab Navigation -->
                    <ul class="nav nav-pills help-tabs mb-4" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#all-topics" type="button">
                                <i class="fas fa-th-large me-2"></i>All Topics
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#case-mgmt" type="button">
                                <i class="fas fa-briefcase me-2"></i>Case Management
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#billing" type="button">
                                <i class="fas fa-file-invoice-dollar me-2"></i>Billing
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#documents" type="button">
                                <i class="fas fa-file-alt me-2"></i>Documents
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#reports" type="button">
                                <i class="fas fa-chart-bar me-2"></i>Reports
                            </button>
                        </li>
                    </ul>

                    <!-- Tab Content -->
                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="all-topics">
                            <div class="row" id="helpTopicsContainer">
                                @foreach($helpTopics as $topic)
                                <div class="col-lg-4 col-md-6 mb-4 help-topic-wrapper" data-category="{{ strtolower($topic['title']) }}">
                                    <div class="help-topic-card h-100">
                                        <div class="card-icon-header">
                                            <div class="icon-circle {{ $topic['colorClass'] ?? 'bg-primary-soft' }}">
                                                <i class="{{ $topic['icon'] }} {{ $topic['iconColor'] ?? 'text-primary' }}"></i>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <h5 class="card-title mb-2">{{ $topic['title'] }}</h5>
                                            <p class="text-muted small mb-3">{{ $topic['description'] }}</p>
                                            
                                            <div class="article-list">
                                                @foreach($topic['articles'] as $index => $article)
                                                <div class="article-item" data-bs-toggle="modal" data-bs-target="#articleModal" 
                                                     data-title="{{ $article['title'] }}" 
                                                     data-content="{{ $article['content'] }}">
                                                    <i class="fas fa-file-alt text-muted me-2"></i>
                                                    <span>{{ $article['title'] }}</span>
                                                    <i class="fas fa-chevron-right ms-auto text-muted"></i>
                                                </div>
                                                @endforeach
                                            </div>
                                            
                                            <a href="#" class="btn btn-link btn-sm p-0 mt-3">
                                                View all articles <i class="fas fa-arrow-right ms-1"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        </div>
                        
                        <!-- Other tab panes would follow similar structure -->
                        <div class="tab-pane fade" id="case-mgmt">
                            <div class="empty-state">
                                <i class="fas fa-briefcase fa-3x text-muted mb-3"></i>
                                <h5>Case Management Resources</h5>
                                <p class="text-muted">Filter content to show only case management topics</p>
                            </div>
                        </div>
                        
                        <div class="tab-pane fade" id="billing">
                            <div class="empty-state">
                                <i class="fas fa-file-invoice-dollar fa-3x text-muted mb-3"></i>
                                <h5>Billing Resources</h5>
                                <p class="text-muted">Filter content to show only billing topics</p>
                            </div>
                        </div>
                        
                        <div class="tab-pane fade" id="documents">
                            <div class="empty-state">
                                <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                <h5>Document Resources</h5>
                                <p class="text-muted">Filter content to show only document topics</p>
                            </div>
                        </div>
                        
                        <div class="tab-pane fade" id="reports">
                            <div class="empty-state">
                                <i class="fas fa-chart-bar fa-3x text-muted mb-3"></i>
                                <h5>Reports Resources</h5>
                                <p class="text-muted">Filter content to show only reports topics</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- FAQ Section -->
    <div class="row mt-5">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-4">
                        <h4 class="mb-0">
                            <i class="fas fa-comments text-info me-2"></i>
                            Frequently Asked Questions
                        </h4>
                        <div class="btn-group btn-group-sm" role="group">
                            <button type="button" class="btn btn-outline-secondary active" data-faq-filter="all">All</button>
                            <button type="button" class="btn btn-outline-secondary" data-faq-filter="general">General</button>
                            <button type="button" class="btn btn-outline-secondary" data-faq-filter="billing">Billing</button>
                            <button type="button" class="btn btn-outline-secondary" data-faq-filter="technical">Technical</button>
                        </div>
                    </div>
                    
                    <div class="accordion accordion-flush" id="faqAccordion">
                        @foreach($faqs as $index => $faq)
                        <div class="accordion-item faq-item" data-faq-category="{{ $faq['category'] ?? 'general' }}">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#faq-{{ $index }}">
                                    <span class="faq-question">{{ $faq['question'] }}</span>
                                    <span class="badge bg-light text-dark ms-2">{{ ucfirst($faq['category'] ?? 'general') }}</span>
                                </button>
                            </h2>
                            <div id="faq-{{ $index }}" class="accordion-collapse collapse">
                                <div class="accordion-body">
                                    <p class="mb-3">{{ $faq['answer'] }}</p>
                                    <div class="faq-footer">
                                        <span class="text-muted small me-3">Was this helpful?</span>
                                        <button class="btn btn-sm btn-outline-success me-2" onclick="rateFaq({{ $index }}, 'yes')">
                                            <i class="fas fa-thumbs-up"></i> Yes
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="rateFaq({{ $index }}, 'no')">
                                            <i class="fas fa-thumbs-down"></i> No
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Support Options -->
    <div class="row mt-5 mb-4">
        <div class="col-lg-4 mb-3">
            <div class="support-card">
                <div class="support-icon bg-success-soft">
                    <i class="fas fa-envelope text-success"></i>
                </div>
                <h5 class="mt-3">Email Support</h5>
                <p class="text-muted small">Get help via email within 24 hours</p>
                <button class="btn btn-outline-success btn-sm mt-2" data-bs-toggle="modal" data-bs-target="#contactModal">
                    Send Message
                </button>
            </div>
        </div>
        <div class="col-lg-4 mb-3">
            <div class="support-card">
                <div class="support-icon bg-primary-soft">
                    <i class="fas fa-comments text-primary"></i>
                </div>
                <h5 class="mt-3">Live Chat</h5>
                <p class="text-muted small">Chat with support team instantly</p>
                <button class="btn btn-outline-primary btn-sm mt-2" onclick="openLiveChat()">
                    Start Chat
                </button>
            </div>
        </div>
        <div class="col-lg-4 mb-3">
            <div class="support-card">
                <div class="support-icon bg-info-soft">
                    <i class="fas fa-phone text-info"></i>
                </div>
                <h5 class="mt-3">Phone Support</h5>
                <p class="text-muted small">Call us: +263 71 496 6574</p>
                <button class="btn btn-outline-info btn-sm mt-2">
                    Schedule Call
                </button>
            </div>
        </div>
    </div>

    <!-- System Status Banner -->
    <div class="row">
        <div class="col-12">
            <div class="alert alert-light border d-flex align-items-center" role="alert">
                <div class="status-indicator status-operational me-3"></div>
                <div class="flex-grow-1">
                    <strong>All Systems Operational</strong>
                    <span class="text-muted ms-2">Last checked: 5 minutes ago</span>
                </div>
                <a href="#" class="btn btn-sm btn-outline-secondary">View Status Page</a>
            </div>
        </div>
    </div>
</div>

<!-- Article Modal -->
<div class="modal fade" id="articleModal" tabindex="-1" aria-labelledby="articleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header border-0">
                <h5 class="modal-title" id="articleModalLabel">Article Title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="articleContent"></div>
                <hr class="my-4">
                <div class="article-feedback">
                    <h6>Was this article helpful?</h6>
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-outline-success">
                            <i class="fas fa-thumbs-up me-2"></i>Yes
                        </button>
                        <button type="button" class="btn btn-outline-danger">
                            <i class="fas fa-thumbs-down me-2"></i>No
                        </button>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 bg-light">
                <button type="button" class="btn btn-sm btn-outline-secondary">
                    <i class="fas fa-print me-2"></i>Print
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary">
                    <i class="fas fa-share-alt me-2"></i>Share
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Contact Modal -->
<div class="modal fade" id="contactModal" tabindex="-1" aria-labelledby="contactModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="contactModalLabel">
                    <i class="fas fa-envelope me-2"></i>Contact Support
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="contactForm">
                    <div class="mb-3">
                        <label for="contactName" class="form-label">Name</label>
                        <input type="text" class="form-control" id="contactName" required>
                    </div>
                    <div class="mb-3">
                        <label for="contactEmail" class="form-label">Email</label>
                        <input type="email" class="form-control" id="contactEmail" required>
                    </div>
                    <div class="mb-3">
                        <label for="contactSubject" class="form-label">Subject</label>
                        <select class="form-select" id="contactSubject" required>
                            <option value="">Select a topic...</option>
                            <option value="case">Case Management</option>
                            <option value="billing">Billing Issue</option>
                            <option value="technical">Technical Problem</option>
                            <option value="account">Account Question</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="contactMessage" class="form-label">Message</label>
                        <textarea class="form-control" id="contactMessage" rows="4" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="contactAttachment" class="form-label">Attachment (optional)</label>
                        <input type="file" class="form-control" id="contactAttachment">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="submitContactForm()">
                    <i class="fas fa-paper-plane me-2"></i>Send Message
                </button>
            </div>
        </div>
    </div>
</div>

<style>
:root {
    --primary-soft: #e7f1ff;
    --success-soft: #d4edda;
    --danger-soft: #f8d7da;
    --warning-soft: #fff3cd;
    --info-soft: #d1ecf1;
}

/* Hero Section */
.help-hero {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 4rem 2rem;
    border-radius: 1rem;
    color: white;
    margin-bottom: 2rem;
}

.help-hero-content {
    max-width: 900px;
    margin: 0 auto;
    text-align: center;
}

/* Enhanced Search */
.search-wrapper {
    position: relative;
}

.search-input {
    padding-left: 3rem;
    padding-right: 1rem;
    border-radius: 50px;
    border: none;
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    font-size: 1rem;
}

.search-input:focus {
    box-shadow: 0 4px 30px rgba(0,0,0,0.15);
    outline: none;
}

.search-icon {
    position: absolute;
    left: 1.2rem;
    top: 50%;
    transform: translateY(-50%);
    color: #6c757d;
    z-index: 10;
}

.search-results-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border-radius: 1rem;
    margin-top: 0.5rem;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    max-height: 400px;
    overflow-y: auto;
    display: none;
    z-index: 1000;
}

.search-results-dropdown.show {
    display: block;
}

.search-result-item {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background 0.2s;
}

.search-result-item:hover {
    background: #f8f9fa;
}

.search-result-item:last-child {
    border-bottom: none;
}

/* Quick Links */
.quick-links {
    text-align: center;
}

.quick-links .badge {
    cursor: pointer;
    padding: 0.5rem 1rem;
    transition: all 0.2s;
}

.quick-links .badge:hover {
    background: #6c757d !important;
    color: white !important;
    transform: translateY(-2px);
}

/* Quick Access Cards */
.quick-access-card {
    background: white;
    padding: 2rem 1.5rem;
    border-radius: 1rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;
    height: 100%;
}

.quick-access-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    border-color: #667eea;
}

.icon-wrapper {
    width: 60px;
    height: 60px;
    margin: 0 auto;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

.bg-primary-soft { background: var(--primary-soft); }
.bg-success-soft { background: var(--success-soft); }
.bg-danger-soft { background: var(--danger-soft); }
.bg-warning-soft { background: var(--warning-soft); }
.bg-info-soft { background: var(--info-soft); }

/* Help Tabs */
.help-tabs {
    border-bottom: 2px solid #e9ecef;
    overflow-x: auto;
    flex-wrap: nowrap;
}

.help-tabs .nav-link {
    color: #6c757d;
    border: none;
    border-bottom: 3px solid transparent;
    border-radius: 0;
    padding: 1rem 1.5rem;
    white-space: nowrap;
    transition: all 0.3s;
}

.help-tabs .nav-link:hover {
    background: transparent;
    color: #667eea;
}

.help-tabs .nav-link.active {
    color: #667eea;
    background: transparent;
    border-bottom-color: #667eea;
}

/* Help Topic Cards */
.help-topic-card {
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 1rem;
    transition: all 0.3s ease;
    overflow: hidden;
}

.help-topic-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    border-color: #667eea;
}

.card-icon-header {
    padding: 2rem 1.5rem 1rem;
    text-align: center;
}

.icon-circle {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
}

.article-list {
    border-top: 1px solid #e9ecef;
    padding-top: 1rem;
}

.article-item {
    display: flex;
    align-items: center;
    padding: 0.75rem;
    border-radius: 0.5rem;
    cursor: pointer;
    transition: all 0.2s;
    margin-bottom: 0.5rem;
}

.article-item:hover {
    background: #f8f9fa;
    transform: translateX(5px);
}

.article-item i.fa-chevron-right {
    font-size: 0.75rem;
}

/* FAQ Items */
.faq-item {
    border: none;
    border-bottom: 1px solid #e9ecef;
}

.faq-item:last-child {
    border-bottom: none;
}

.accordion-button {
    padding: 1.25rem 1.5rem;
    font-weight: 500;
    background: transparent;
}

.accordion-button:not(.collapsed) {
    background: #f8f9fa;
    color: #667eea;
    box-shadow: none;
}

.accordion-button:focus {
    box-shadow: none;
    border-color: transparent;
}

.accordion-button::after {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23667eea'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
}

.faq-question {
    flex-grow: 1;
}

.faq-footer {
    padding-top: 1rem;
    border-top: 1px solid #e9ecef;
}

/* Support Cards */
.support-card {
    background: white;
    padding: 2rem;
    border-radius: 1rem;
    text-align: center;
    border: 2px solid #e9ecef;
    transition: all 0.3s;
    height: 100%;
}

.support-card:hover {
    border-color: #667eea;
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.support-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

/* System Status */
.status-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    animation: pulse 2s infinite;
}

.status-operational {
    background: #28a745;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 4rem 2rem;
}

/* Responsive */
@media (max-width: 768px) {
    .help-hero {
        padding: 2rem 1rem;
    }
    
    .help-hero h1 {
        font-size: 1.75rem;
    }
    
    .help-tabs {
        font-size: 0.875rem;
    }
    
    .help-tabs .nav-link {
        padding: 0.75rem 1rem;
    }
}

/* Animations */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.help-topic-wrapper {
    animation: fadeIn 0.5s ease-out;
}

.help-topic-wrapper:nth-child(1) { animation-delay: 0.1s; }
.help-topic-wrapper:nth-child(2) { animation-delay: 0.2s; }
.help-topic-wrapper:nth-child(3) { animation-delay: 0.3s; }
</style>

<script>
// Enhanced Search with Live Results
let searchTimeout;
document.getElementById('helpSearch').addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase().trim();
    const resultsDropdown = document.getElementById('searchResults');
    
    clearTimeout(searchTimeout);
    
    if (searchTerm.length < 2) {
        resultsDropdown.classList.remove('show');
        filterTopics('');
        return;
    }
    
    searchTimeout = setTimeout(() => {
        // Filter visible topics
        filterTopics(searchTerm);
        
        // Show search results dropdown
        showSearchResults(searchTerm);
    }, 300);
});

function filterTopics(searchTerm) {
    const cards = document.querySelectorAll('.help-topic-wrapper');
    let visibleCount = 0;
    
    cards.forEach(card => {
        const title = card.querySelector('.card-title')?.textContent.toLowerCase() || '';
        const description = card.querySelector('.text-muted')?.textContent.toLowerCase() || '';
        const articles = card.querySelectorAll('.article-item span');
        
        let hasMatch = title.includes(searchTerm) || description.includes(searchTerm);
        
        if (!hasMatch) {
            articles.forEach(article => {
                if (article.textContent.toLowerCase().includes(searchTerm)) {
                    hasMatch = true;
                }
            });
        }
        
        if (hasMatch || searchTerm === '') {
            card.style.display = 'block';
            visibleCount++;
        } else {
            card.style.display = 'none';
        }
    });
    
    // Show no results message if needed
    const container = document.getElementById('helpTopicsContainer');
    let noResults = container.querySelector('.no-results');
    
    if (visibleCount === 0 && searchTerm !== '') {
        if (!noResults) {
            noResults = document.createElement('div');
            noResults.className = 'col-12 no-results text-center py-5';
            noResults.innerHTML = `
                <i class="fas fa-search fa-3x text-muted mb-3"></i>
                <h5>No results found</h5>
                <p class="text-muted">Try adjusting your search terms or browse categories above</p>
            `;
            container.appendChild(noResults);
        }
    } else if (noResults) {
        noResults.remove();
    }
}

function showSearchResults(searchTerm) {
    const resultsDropdown = document.getElementById('searchResults');
    
    // Collect matching articles
    const matches = [];
    const cards = document.querySelectorAll('.help-topic-wrapper');
    
    cards.forEach(card => {
        const topicTitle = card.querySelector('.card-title')?.textContent || '';
        const articles = card.querySelectorAll('.article-item');
        
        articles.forEach(article => {
            const articleTitle = article.querySelector('span')?.textContent || '';
            if (articleTitle.toLowerCase().includes(searchTerm)) {
                matches.push({
                    topic: topicTitle,
                    title: articleTitle,
                    element: article
                });
            }
        });
    });
    
    if (matches.length > 0) {
        let html = '';
        matches.slice(0, 5).forEach(match => {
            html += `
                <div class="search-result-item" onclick="this.querySelector('[data-bs-toggle]').click()">
                    <div class="d-flex align-items-start">
                        <i class="fas fa-file-alt text-muted me-3 mt-1"></i>
                        <div class="flex-grow-1">
                            <strong>${match.title}</strong>
                            <div class="small text-muted">${match.topic}</div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        if (matches.length > 5) {
            html += `
                <div class="text-center py-2 border-top">
                    <small class="text-muted">${matches.length - 5} more results...</small>
                </div>
            `;
        }
        
        resultsDropdown.innerHTML = html;
        resultsDropdown.classList.add('show');
    } else {
        resultsDropdown.classList.remove('show');
    }
}

// Close search results when clicking outside
document.addEventListener('click', function(e) {
    const searchWrapper = document.querySelector('.search-wrapper');
    const resultsDropdown = document.getElementById('searchResults');
    
    if (!searchWrapper.contains(e.target)) {
        resultsDropdown.classList.remove('show');
    }
});

// Quick link badges
document.querySelectorAll('.quick-links .badge').forEach(badge => {
    badge.addEventListener('click', function(e) {
        e.preventDefault();
        const searchTerm = this.getAttribute('data-search');
        document.getElementById('helpSearch').value = searchTerm;
        filterTopics(searchTerm.toLowerCase());
    });
});

// Quick access cards
document.querySelectorAll('.quick-access-card').forEach(card => {
    card.addEventListener('click', function() {
        const category = this.getAttribute('data-category');
        // Scroll to topics section
        document.querySelector('.help-tabs').scrollIntoView({ behavior: 'smooth' });
    });
});

// Article Modal
const articleModal = document.getElementById('articleModal');
if (articleModal) {
    articleModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        const title = button.getAttribute('data-title');
        const content = button.getAttribute('data-content');
        
        const modalTitle = articleModal.querySelector('.modal-title');
        const modalBody = articleModal.querySelector('#articleContent');
        
        modalTitle.textContent = title;
        modalBody.innerHTML = `<p>${content}</p>`;
    });
}

// FAQ Filtering
document.querySelectorAll('[data-faq-filter]').forEach(button => {
    button.addEventListener('click', function() {
        const filter = this.getAttribute('data-faq-filter');
        
        // Update active button
        document.querySelectorAll('[data-faq-filter]').forEach(btn => {
            btn.classList.remove('active');
        });
        this.classList.add('active');
        
        // Filter FAQ items
        const faqItems = document.querySelectorAll('.faq-item');
        faqItems.forEach(item => {
            const category = item.getAttribute('data-faq-category');
            if (filter === 'all' || category === filter) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
});

// FAQ Rating
function rateFaq(index, rating) {
    // Show thank you message
    const faqItem = document.querySelector(`#faq-${index}`);
    const footer = faqItem.querySelector('.faq-footer');
    
    footer.innerHTML = `
        <div class="alert alert-success mb-0" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            Thank you for your feedback!
        </div>
    `;
    
    // Here you would typically send the rating to your backend
    console.log(`FAQ ${index} rated: ${rating}`);
}

// Contact Form Submission
function submitContactForm() {
    const form = document.getElementById('contactForm');
    
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const formData = {
        name: document.getElementById('contactName').value,
        email: document.getElementById('contactEmail').value,
        subject: document.getElementById('contactSubject').value,
        message: document.getElementById('contactMessage').value
    };
    
    // Show loading state
    const submitBtn = event.target;
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Sending...';
    submitBtn.disabled = true;
    
    // Simulate API call
    setTimeout(() => {
        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('contactModal'));
        modal.hide();
        
        // Show success message
        const alert = document.createElement('div');
        alert.className = 'alert alert-success alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
        alert.style.zIndex = '9999';
        alert.innerHTML = `
            <i class="fas fa-check-circle me-2"></i>
            Your message has been sent successfully! We'll get back to you soon.
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(alert);
        
        // Reset form
        form.reset();
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        
        // Remove alert after 5 seconds
        setTimeout(() => alert.remove(), 5000);
        
        // Here you would typically send the data to your backend
        console.log('Contact form submitted:', formData);
    }, 1500);
}

// Live Chat
function openLiveChat() {
    // This would typically open your live chat widget
    alert('Opening live chat... This would integrate with your chat system (e.g., Intercom, Drift, etc.)');
    console.log('Live chat opened');
}

// Print article
document.querySelectorAll('.modal-footer button:has(.fa-print)').forEach(btn => {
    btn.addEventListener('click', function() {
        const modalContent = document.querySelector('#articleContent').innerHTML;
        const modalTitle = document.querySelector('#articleModalLabel').textContent;
        
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + modalTitle + '</title>');
        printWindow.document.write('<style>body{font-family:Arial,sans-serif;padding:20px;}</style>');
        printWindow.document.write('</head><body>');
        printWindow.document.write('<h1>' + modalTitle + '</h1>');
        printWindow.document.write(modalContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.print();
    });
});

// Share article
document.querySelectorAll('.modal-footer button:has(.fa-share-alt)').forEach(btn => {
    btn.addEventListener('click', function() {
        const modalTitle = document.querySelector('#articleModalLabel').textContent;
        const url = window.location.href;
        
        if (navigator.share) {
            navigator.share({
                title: modalTitle,
                text: 'Check out this help article',
                url: url
            }).catch(err => console.log('Error sharing:', err));
        } else {
            // Fallback: Copy to clipboard
            navigator.clipboard.writeText(url).then(() => {
                alert('Link copied to clipboard!');
            });
        }
    });
});

// Article feedback
document.querySelectorAll('.article-feedback button').forEach(btn => {
    btn.addEventListener('click', function() {
        const feedback = this.textContent.includes('Yes') ? 'positive' : 'negative';
        const parent = this.closest('.article-feedback');
        
        parent.innerHTML = `
            <div class="alert alert-success mb-0" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                Thank you for your feedback!
            </div>
        `;
        
        console.log('Article feedback:', feedback);
    });
});

// Smooth scroll for internal links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    });
});

// Initialize tooltips if Bootstrap tooltips are available
if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// Keyboard navigation for search
document.getElementById('helpSearch').addEventListener('keydown', function(e) {
    const resultsDropdown = document.getElementById('searchResults');
    
    if (e.key === 'Escape') {
        resultsDropdown.classList.remove('show');
        this.blur();
    }
});

// Auto-focus search on keyboard shortcut (Ctrl/Cmd + K)
document.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('helpSearch').focus();
    }
});

console.log('Help Center initialized successfully');
</script>
@endsection