<?php
// pages/leads.php - Complete leads management page
?>

<div class="py-6">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Header -->
        <div class="md:flex md:items-center md:justify-between mb-6">
            <div class="flex-1 min-w-0">
                <h1 class="text-2xl font-bold leading-7 text-gray-900 sm:text-3xl sm:truncate">
                    Leads Management
                </h1>
                <p class="mt-1 text-sm text-gray-500">
                    Manage and analyze your leads with AI-powered insights
                </p>
            </div>
            <div class="mt-4 flex md:mt-0 md:ml-4">
                <a href="/lead-management/public/app/leads/create" 
                   class="ml-3 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    Add Lead
                </a>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 mb-6">
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-blue-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Total Leads</dt>
                                <dd class="text-lg font-medium text-gray-900"><?= count($leads) ?></dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-green-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Scored Leads</dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    <?= count(array_filter($leads, function($lead) { return !empty($lead['ai_score']); })) ?>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-yellow-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">High Priority</dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    <?= count(array_filter($leads, function($lead) { return ($lead['ai_score'] ?? 0) >= 80; })) ?>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-purple-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Emails Sent</dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    <?= array_sum(array_column($leads, 'email_generation_count')) ?>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="mb-4 bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded">
                <?= $_SESSION['success'] ?>
                <?php unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="mb-4 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
                <?= $_SESSION['error'] ?>
                <?php unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>

        <!-- Leads Table -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:px-6 flex justify-between items-center">
                <div>
                    <h3 class="text-lg leading-6 font-medium text-gray-900">All Leads</h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">AI-powered lead intelligence</p>
                </div>
                <div class="flex space-x-3">
                    <button onclick="batchScoreLeads()" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                        </svg>
                        AI Score Selected
                    </button>
                </div>
            </div>

            <div class="border-t border-gray-200">
                <?php if (empty($leads)): ?>
                    <div class="text-center py-12">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                        <h3 class="mt-2 text-sm font-medium text-gray-900">No leads</h3>
                        <p class="mt-1 text-sm text-gray-500">Get started by creating a new lead.</p>
                        <div class="mt-6">
                            <a href="/lead-management/public/app/leads/create" class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                Add Lead
                            </a>
                        </div>
                    </div>
                <?php else: ?>
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lead</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Contact</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">AI Score</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Source</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($leads as $lead): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="checkbox" name="lead_ids[]" value="<?= $lead['id'] ?>" class="lead-checkbox">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900">
                                        <?= htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']) ?>
                                    </div>
                                    <div class="text-sm text-gray-500">
                                        <?= htmlspecialchars($lead['company'] ?? 'No company') ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm text-gray-900"><?= htmlspecialchars($lead['email'] ?? 'No email') ?></div>
                                    <div class="text-sm text-gray-500"><?= htmlspecialchars($lead['phone'] ?? 'No phone') ?></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if ($lead['ai_score']): ?>
                                        <div class="flex items-center">
                                            <div class="w-16 bg-gray-200 rounded-full h-2.5 mr-2">
                                                <?php
                                                $scoreColor = match(true) {
                                                    ($lead['ai_score'] >= 80) => 'bg-red-600',
                                                    ($lead['ai_score'] >= 60) => 'bg-yellow-600',
                                                    default => 'bg-blue-600'
                                                };
                                                $textColor = match(true) {
                                                    ($lead['ai_score'] >= 80) => 'text-red-600',
                                                    ($lead['ai_score'] >= 60) => 'text-yellow-600',
                                                    default => 'text-blue-600'
                                                };
                                                ?>
                                                <div class="<?= $scoreColor ?> h-2.5 rounded-full" style="width: <?= $lead['ai_score'] ?>%"></div>
                                            </div>
                                            <span class="text-sm font-medium text-gray-900"><?= $lead['ai_score'] ?></span>
                                            <span class="ml-1 text-xs <?= $textColor ?>">
                                                (<?= $lead['ai_score_category'] ?? 'Not scored' ?>)
                                            </span>
                                        </div>
                                        <?php if ($lead['ai_score_reasoning']): ?>
                                            <div class="text-xs text-gray-500 mt-1" title="<?= htmlspecialchars($lead['ai_score_reasoning']) ?>">
                                                <?= substr(htmlspecialchars($lead['ai_score_reasoning']), 0, 50) ?>...
                                            </div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <button onclick="scoreSingleLead(<?= $lead['id'] ?>)" 
                                                class="inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded-md text-blue-700 bg-blue-100 hover:bg-blue-200">
                                            Score with AI
                                        </button>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php
                                    $statusColors = [
                                        'new' => 'bg-gray-100 text-gray-800',
                                        'contacted' => 'bg-blue-100 text-blue-800',
                                        'qualified' => 'bg-green-100 text-green-800',
                                        'converted' => 'bg-purple-100 text-purple-800',
                                        'unqualified' => 'bg-red-100 text-red-800'
                                    ];
                                    $statusColor = $statusColors[$lead['status']] ?? 'bg-gray-100 text-gray-800';
                                    ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?= $statusColor ?>">
                                        <?= ucfirst($lead['status']) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <?= ucfirst($lead['source'] ?? 'manual') ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <?= date('M j, Y', strtotime($lead['created_at'])) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <div class="flex space-x-2">
                                        <a href="/lead-management/public/app/leads/<?= $lead['id'] ?>/edit" 
                                           class="text-blue-600 hover:text-blue-900" title="Edit">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                            </svg>
                                        </a>
                                        <button onclick="generateEmail(<?= $lead['id'] ?>, 'follow_up')" 
                                                class="text-green-600 hover:text-green-900" title="Generate Follow-up Email">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                            </svg>
                                        </button>
                                        <button onclick="analyzeBehavior(<?= $lead['id'] ?>)" 
                                                class="text-purple-600 hover:text-purple-900" title="Analyze Behavior">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                                            </svg>
                                        </button>
                                        <a href="/lead-management/public/app/leads/<?= $lead['id'] ?>/delete" 
                                           onclick="return confirm('Are you sure you want to delete this lead?')"
                                           class="text-red-600 hover:text-red-900" title="Delete">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                            </svg>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- AI Modal for Results -->
<div id="aiModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 id="modalTitle" class="text-lg font-medium text-gray-900"></h3>
            <div id="modalContent" class="mt-2 px-7 py-3"></div>
            <div class="flex justify-end mt-4">
                <button onclick="closeModal()" class="px-4 py-2 bg-gray-300 text-gray-800 rounded hover:bg-gray-400">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.lead-checkbox');
    checkboxes.forEach(cb => cb.checked = checkbox.checked);
}

function scoreSingleLead(leadId) {
    showModal('AI Lead Scoring', `
        <div class="text-center py-4">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p class="mt-4">Scoring lead with AI...</p>
        </div>
    `);

    fetch('/lead-management/public/app/leads/' + leadId + '/score', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showModal('AI Lead Scoring', `
                <div class="bg-green-50 border border-green-200 rounded p-4">
                    <h4 class="font-semibold text-green-800">Score: ${data.score.score}</h4>
                    <p class="text-green-700 mt-2">${data.score.reasoning}</p>
                    <p class="text-sm text-green-600 mt-2">Confidence: ${(data.score.confidence * 100).toFixed(0)}%</p>
                    <p class="text-sm text-green-600">Category: ${data.score.category}</p>
                </div>
            `);
            setTimeout(() => location.reload(), 2000);
        } else {
            showModal('Error', `<div class="bg-red-50 border border-red-200 rounded p-4 text-red-800">${data.error}</div>`);
        }
    })
    .catch(error => {
        showModal('Error', `<div class="bg-red-50 border border-red-200 rounded p-4 text-red-800">Network error: ${error}</div>`);
    });
}

function generateEmail(leadId, emailType) {
    showModal('Generating Email', `
        <div class="text-center py-4">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600 mx-auto"></div>
            <p class="mt-4">Generating personalized email...</p>
        </div>
    `);

    fetch('/lead-management/public/app/leads/' + leadId + '/generate-email', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email_type: emailType })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showModal('AI Generated Email', `
                <div class="border rounded p-4">
                    <h4 class="font-semibold mb-2">Subject: ${data.email_content.subject}</h4>
                    <div class="bg-gray-50 p-3 rounded whitespace-pre-wrap text-sm">${data.email_content.body}</div>
                    <div class="mt-3 flex space-x-2">
                        <button onclick="copyToClipboard('${data.email_content.subject}\\n\\n${data.email_content.body.replace(/\n/g, '\\n')}')" 
                                class="px-3 py-1 bg-blue-600 text-white rounded text-sm">Copy Email</button>
                        <button onclick="sendGeneratedEmail(${leadId})" 
                                class="px-3 py-1 bg-green-600 text-white rounded text-sm">Send Now</button>
                    </div>
                </div>
            `);
        } else {
            showModal('Error', `<div class="bg-red-50 border border-red-200 rounded p-4 text-red-800">${data.error}</div>`);
        }
    });
}

function analyzeBehavior(leadId) {
    showModal('Analyzing Behavior', `
        <div class="text-center py-4">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mx-auto"></div>
            <p class="mt-4">Analyzing lead behavior patterns...</p>
        </div>
    `);

    fetch('/lead-management/public/app/leads/' + leadId + '/analyze-behavior')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showModal('Behavior Analysis', `
                <div class="space-y-3">
                    <div class="bg-blue-50 border border-blue-200 rounded p-3">
                        <h4 class="font-semibold text-blue-800">Engagement Level: ${data.analysis.engagement_level}</h4>
                    </div>
                    <div class="bg-yellow-50 border border-yellow-200 rounded p-3">
                        <h4 class="font-semibold text-yellow-800">Recommended Actions:</h4>
                        <p class="text-yellow-700 mt-1">${data.analysis.recommended_actions}</p>
                    </div>
                    <div class="bg-red-50 border border-red-200 rounded p-3">
                        <h4 class="font-semibold text-red-800">Risk Factors:</h4>
                        <p class="text-red-700 mt-1">${data.analysis.risk_factors || 'No significant risks detected'}</p>
                    </div>
                    <div class="bg-green-50 border border-green-200 rounded p-3">
                        <h4 class="font-semibold text-green-800">Next Best Contact:</h4>
                        <p class="text-green-700 mt-1">${data.analysis.next_best_contact}</p>
                    </div>
                </div>
            `);
        } else {
            showModal('Error', `<div class="bg-red-50 border border-red-200 rounded p-4 text-red-800">${data.error}</div>`);
        }
    });
}

function batchScoreLeads() {
    const selectedLeads = Array.from(document.querySelectorAll('.lead-checkbox:checked'))
        .map(cb => cb.value);
    
    if (selectedLeads.length === 0) {
        alert('Please select at least one lead to score');
        return;
    }
    
    showModal('Batch AI Scoring', `
        <div class="text-center py-4">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p class="mt-4">Scoring ${selectedLeads.length} leads with AI...</p>
        </div>
    `);
    
    // Implement batch scoring logic here
    setTimeout(() => {
        showModal('Batch Scoring Complete', `
            <div class="bg-green-50 border border-green-200 rounded p-4">
                <h4 class="font-semibold text-green-800">Batch Scoring Complete</h4>
                <p class="text-green-700 mt-2">Successfully scored ${selectedLeads.length} leads.</p>
            </div>
        `);
        setTimeout(() => location.reload(), 2000);
    }, 3000);
}

function showModal(title, content) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalContent').innerHTML = content;
    document.getElementById('aiModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('aiModal').classList.add('hidden');
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert('Email copied to clipboard!');
    });
}

function sendGeneratedEmail(leadId) {
    alert('Email sending functionality would be implemented here.');
    closeModal();
}

// Close modal when clicking outside
document.getElementById('aiModal').addEventListener('click', function(e) {
    if (e.target.id === 'aiModal') {
        closeModal();
    }
});
</script>