

<?php $__env->startSection('title', 'Create Notification'); ?>

<?php $__env->startSection('content'); ?>
<div class="dashboard-grid">
    <div class="card" style="grid-column: 1 / -1;">
        <div class="card-header">
            <h2 class="card-title">Create New Notification</h2>
            <div class="stat-icon">🔔</div>
        </div>
        
        <?php if(!$firebaseConfigured): ?>
            <div style="background: #fef3c7; border: 1px solid #f59e0b; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <span style="font-size: 24px;">⚠️</span>
                    <div>
                        <strong>Firebase Not Configured</strong>
                        <p style="margin: 4px 0 0 0; color: #7c2d12;">Push notifications require Firebase configuration. This notification will be created but may not be delivered until Firebase is configured.</p>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <form action="<?php echo e(route('admin.notifications.store')); ?>" method="POST" enctype="multipart/form-data">
            <?php echo csrf_field(); ?>
            
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px;">
                <!-- Left Column: Main Content -->
                <div>
                    <div style="margin-bottom: 20px;">
                        <label for="title" style="display: block; margin-bottom: 8px; font-weight: 600;">Notification Title</label>
                        <input type="text" id="title" name="title" required maxlength="255" 
                               style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;"
                               placeholder="Enter notification title">
                        <small style="color: var(--text-secondary);">Keep it short and attention-grabbing (max 255 characters)</small>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="message" style="display: block; margin-bottom: 8px; font-weight: 600;">Notification Message</label>
                        <textarea id="message" name="message" required rows="4" 
                                  style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px; resize: vertical;"
                                  placeholder="Enter your notification message"></textarea>
                        <small style="color: var(--text-secondary);">This is the main content of your notification</small>
                    <div style="margin-bottom: 20px;">
                        <label for="image" style="display: block; margin-bottom: 8px; font-weight: 600;">Notification Image (Optional)</label>
                        <div style="display: flex; gap: 16px; align-items: flex-start;">
                            <div style="flex: 1;">
                                <input type="file" id="image" name="image" accept="image/*"
                                       style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px; background: white;">
                                <small style="color: var(--text-secondary);">Image to display in the notification (JPG, PNG, GIF)</small>
                            </div>
                            <div id="image_preview_container" style="display: none; width: 100px; height: 100px; border: 1px solid var(--border-color); border-radius: 8px; overflow: hidden; background: #eee;">
                                <img id="image_preview" src="" style="width: 100%; height: 100%; object-fit: cover;">
                            </div>
                        </div>
                    </div>

                    <div style="margin-bottom: 20px; background: #f8fafc; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                        <label style="display: block; margin-bottom: 12px; font-weight: 600;">Deep Link Builder</label>
                        
                        <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 12px; margin-bottom: 12px;">
                            <div>
                                <label style="font-size: 12px; font-weight: 600; color: var(--text-secondary);">Link Type</label>
                                <select id="dl_type" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    <option value="">Select Type...</option>
                                    <option value="ad">Ad Details</option>
                                    <option value="user">User Profile</option>
                                    <option value="plan">Premium Plan</option>
                                    <option value="custom">Custom URL</option>
                                </select>
                            </div>
                            
                            <!-- Dynamic Inputs -->
                            <div id="dl_input_container">
                                <!-- Ad Search -->
                                <div id="dl_ad_search_group" style="display: none; position: relative;">
                                    <label style="font-size: 12px; font-weight: 600; color: var(--text-secondary);">Search Ad</label>
                                    <input type="text" id="dl_ad_search" placeholder="Type ad title..." 
                                           style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    <div id="dl_ad_results" style="position: absolute; width: 100%; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 10; display: none;"></div>
                                </div>

                                <!-- User Search -->
                                <div id="dl_user_search_group" style="display: none; position: relative;">
                                    <label style="font-size: 12px; font-weight: 600; color: var(--text-secondary);">Search User</label>
                                    <input type="text" id="dl_user_search" placeholder="Type user name or email..." 
                                           style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;">
                                    <div id="dl_user_results" style="position: absolute; width: 100%; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 10; display: none;"></div>
                                </div>

                                <!-- Plan Select -->
                                <div id="dl_plan_select_group" style="display: none;">
                                    <label style="font-size: 12px; font-weight: 600; color: var(--text-secondary);">Select Plan</label>
                                    <select id="dl_plan_select" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;">
                                        <option value="VIP Buyer">VIP Buyer</option>
                                        <option value="VIP Seller">VIP Seller</option>
                                        <option value="VIP Pro">VIP Pro</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <label for="deep_link_url" style="display: block; margin-bottom: 4px; font-size: 14px; font-weight: 600;">Resulting URL</label>
                        <input type="url" id="deep_link_url" name="deep_link_url" 
                               style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px; background: #fff;"
                               placeholder="https://clxpro.com/...">
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="target_type" style="display: block; margin-bottom: 8px; font-weight: 600;">Target Type</label>
                        <select id="target_type" name="target_type" required 
                                style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;">
                            <option value="all">All Users</option>
                            <option value="single_user">Single User</option>
                            <option value="premium_plan">Premium Plan Users</option>
                            <option value="custom">Custom Targeting</option>
                        </select>
                        <small style="color: var(--text-secondary);">Choose who will receive this notification</small>
                    </div>

                    <!-- Target-specific fields -->
                    <div id="target_fields" style="margin-bottom: 20px; display: none;">
                        <!-- Single User Target with Search -->
                        <div id="single_user_fields" style="display: none;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Search and Select Users</label>
                            <div style="position: relative;">
                                <input type="text" id="user_search_input" placeholder="Type user name or email..." 
                                       style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;">
                                <div id="user_search_results" style="position: absolute; width: 100%; background: white; border: 1px solid var(--border-color); border-radius: 8px; max-height: 200px; overflow-y: auto; z-index: 100; display: none; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"></div>
                            </div>
                            <div id="selected_users" style="margin-top: 12px; display: flex; flex-wrap: wrap; gap: 8px;"></div>
                            <input type="hidden" name="target_value[user_ids][]" id="selected_user_ids">
                            <small style="color: var(--text-secondary); display: block; margin-top: 8px;">Search and click users to add them to the notification</small>
                        </div>

                        <!-- Premium Plan Target -->
                        <div id="premium_plan_fields" style="display: none;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Select Premium Plans</label>
                            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;">
                                <?php $__currentLoopData = $premiumPlans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $plan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <label style="display: flex; align-items: center; gap: 8px; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; cursor: pointer; transition: all 0.2s;">
                                        <input type="checkbox" name="target_value[plan_types][]" value="<?php echo e($plan); ?>">
                                        <span><?php echo e($plan); ?></span>
                                    </label>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                            <small style="color: var(--text-secondary);">Select which premium plan users should receive this notification</small>
                        </div>

                        <div id="custom_fields" style="display: none; margin-top: 20px;">
                            <div style="background: var(--bg-color); padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                <h4 style="margin: 0 0 12px 0; font-size: 14px;">📍 Location Targeting (Optional)</h4>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                    <div style="position: relative;">
                                        <label style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px;">City</label>
                                        <input type="text" id="city_input" name="target_value[city]" placeholder="Start typing city name..." 
                                               style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" autocomplete="off">
                                        <div id="city_results" class="location-autocomplete-results"></div>
                                    </div>
                                    <div style="position: relative;">
                                        <label style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px;">State</label>
                                        <input type="text" id="state_input" name="target_value[state]" placeholder="Start typing state name..." 
                                               style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" autocomplete="off">
                                        <div id="state_results" class="location-autocomplete-results"></div>
                                    </div>
                                    <div style="grid-column: span 2; position: relative;">
                                        <label style="font-size: 12px; font-weight: 600; display: block; margin-bottom: 4px;">Country</label>
                                        <input type="text" id="country_input" name="target_value[country]" placeholder="Start typing country name..." 
                                               style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" autocomplete="off">
                                        <div id="country_results" class="location-autocomplete-results"></div>
                                    </div>
                                </div>
                                <small style="color: var(--text-secondary); margin-top: 8px; display: block;">
                                    💡 Notifications will only be sent to users in the exact locations you specify
                                </small>
                                <div id="location_preview" style="margin-top: 12px; padding: 8px; background: #f0f9ff; border-radius: 6px; display: none;">
                                    <strong style="font-size: 12px; color: #0369a1;">Targeting:</strong>
                                    <span id="location_preview_text" style="font-size: 12px; color: #075985;"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label for="scheduled_at" style="display: block; margin-bottom: 8px; font-weight: 600;">Schedule Send Time (Optional)</label>
                        <input type="datetime-local" id="scheduled_at" name="scheduled_at" 
                               style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 16px;">
                        <small style="color: var(--text-secondary);">Leave empty to send immediately when you click 'Send Now'</small>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label style="display: flex; align-items: center; gap: 12px; cursor: pointer;">
                            <input type="checkbox" name="send_now" value="1">
                            <span style="font-weight: 600;">Send this notification immediately</span>
                        </label>
                        <small style="color: var(--text-secondary); display: block; margin-top: 4px;">If unchecked, the notification will be saved as a draft</small>
                    </div>
                    
                    <div style="margin-top: 24px; display: flex; gap: 16px; align-items: center;">
                        <button type="submit" style="padding: 14px 32px; background: linear-gradient(135deg, var(--primary-color) 0%, #4f46e5 100%); color: white; border: none; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.4); display: flex; align-items: center; gap: 8px;">
                            <span>🚀</span> Send Notification
                        </button>
                        <a href="<?php echo e(route('admin.notifications.index')); ?>" style="padding: 14px 32px; background: white; color: #4b5563; border: 1px solid #d1d5db; border-radius: 10px; font-size: 16px; font-weight: 600; text-decoration: none; cursor: pointer; transition: all 0.3s ease;">
                            Cancel
                        </a>
                    </div>
                </div>

                <!-- Right Column: Preview and Examples -->
                <div>
                    <div style="background: var(--bg-color); padding: 20px; border-radius: 12px; border: 1px solid var(--border-color);">
                        <h3 style="margin: 0 0 16px 0; font-size: 1.1rem;">Notification Preview</h3>
                        
                        <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color); margin-bottom: 16px;">
                            <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                                <div style="width: 40px; height: 40px; background: var(--primary-color); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;">CLX</div>
                                <div>
                                    <strong style="font-size: 14px;">CLX Pro</strong>
                                    <br><small style="color: var(--text-secondary);">Now</small>
                                </div>
                            </div>
                            <div>
                                <strong id="preview_title" style="display: block; margin-bottom: 4px;">Your notification title will appear here</strong>
                                <span id="preview_message" style="color: var(--text-secondary); font-size: 14px; display: block;">Your notification message will appear here</span>
                            </div>
                        </div>

                        <div style="margin-top: 16px;">
                            <h4 style="margin: 0 0 12px 0; font-size: 0.9rem;">Deep Link Examples</h4>
                            <div style="display: grid; gap: 8px;">
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>Ad Details:</strong><br>
                                    <code><?php echo e($deepLinkExamples['ad-details']); ?></code>
                                </div>
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>User Profile:</strong><br>
                                    <code><?php echo e($deepLinkExamples['user-profile']); ?></code>
                                </div>
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>Category:</strong><br>
                                    <code><?php echo e($deepLinkExamples['category']); ?></code>
                                </div>
                                <div style="padding: 8px; background: var(--card-bg); border-radius: 6px; font-size: 12px;">
                                    <strong>Premium Plans:</strong><br>
                                    <code><?php echo e($deepLinkExamples['premium-plans']); ?></code>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div style="margin-top: 16px; padding: 16px; background: #f8fafc; border-radius: 8px; border: 1px solid var(--border-color);">
                        <h4 style="margin: 0 0 12px 0; font-size: 0.9rem;">Targeting Tips</h4>
                        <ul style="margin: 0; padding-left: 20px; font-size: 14px; color: var(--text-secondary);">
                            <li><strong>All Users:</strong> Send to every active user</li>
                            <li><strong>Single User:</strong> Target specific users by ID</li>
                            <li><strong>Premium Plans:</strong> Target users with specific subscription plans</li>
                            <li><strong>Custom:</strong> Advanced targeting (API required)</li>
                        </ul>
                    </div>
                </div>
            </div>


            
            <style>
                button[type="submit"]:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.5);
                    filter: brightness(1.1);
                }
                a[href*="index"]:hover {
                    background: #f9fafb;
                    border-color: #9ca3af;
                    color: #1f2937;
                }
                
                /* Autocomplete styles */
                .location-autocomplete-results {
                    position: absolute;
                    width: 100%;
                    background: white;
                    border: 1px solid var(--border-color);
                    border-radius: 8px;
                    max-height: 200px;
                    overflow-y: auto;
                    z-index: 100;
                    display: none;
                    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                    margin-top: 4px;
                }
            </style>
        </form>
    </div>
</div>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
// Preview functionality
document.addEventListener('DOMContentLoaded', function() {
    const titleInput = document.getElementById('title');
    const messageInput = document.getElementById('message');
    const previewTitle = document.getElementById('preview_title');
    const previewMessage = document.getElementById('preview_message');
    const targetTypeSelect = document.getElementById('target_type');
    const targetFields = document.getElementById('target_fields');
    const singleUserFields = document.getElementById('single_user_fields');
    const premiumPlanFields = document.getElementById('premium_plan_fields');
    const customFields = document.getElementById('custom_fields');

    // Update preview
    titleInput.addEventListener('input', function() {
        previewTitle.textContent = this.value || 'Your notification title will appear here';
    });

    messageInput.addEventListener('input', function() {
        previewMessage.textContent = this.value || 'Your notification message will appear here';
    });

    // Show/hide target fields based on selection
    targetTypeSelect.addEventListener('change', function() {
        singleUserFields.style.display = 'none';
        premiumPlanFields.style.display = 'none';
        customFields.style.display = 'none';
        targetFields.style.display = 'block';
        
        if (this.value === 'all') {
            // "All Users" can still be filtered by location
            customFields.style.display = 'block';
        } else if (this.value === 'single_user') {
            singleUserFields.style.display = 'block';
        } else if (this.value === 'premium_plan') {
            premiumPlanFields.style.display = 'block';
            // Premium plans can be filtered by location
            customFields.style.display = 'block';
        } else if (this.value === 'custom') {
            customFields.style.display = 'block';
        } else {
            targetFields.style.display = 'none';
        }
    });

    // Image Preview
    const imageInput = document.getElementById('image');
    const imagePreviewContainer = document.getElementById('image_preview_container');
    const imagePreview = document.getElementById('image_preview');

    imageInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                imagePreview.src = e.target.result;
                imagePreviewContainer.style.display = 'block';
            }
            reader.readAsDataURL(file);
        } else {
            imagePreviewContainer.style.display = 'none';
        }
    });

    // Deep Link Builder Logic
    const dlType = document.getElementById('dl_type');
    const dlUrl = document.getElementById('deep_link_url');
    const dlAdGroup = document.getElementById('dl_ad_search_group');
    const dlUserGroup = document.getElementById('dl_user_search_group');
    const dlPlanGroup = document.getElementById('dl_plan_select_group');
    const dlAdSearch = document.getElementById('dl_ad_search');
    const dlUserSearch = document.getElementById('dl_user_search');
    const dlAdResults = document.getElementById('dl_ad_results');
    const dlUserResults = document.getElementById('dl_user_results');
    const dlPlanSelect = document.getElementById('dl_plan_select');

    dlUrl.setAttribute('readonly', true); // Make it readonly
    dlUrl.style.background = '#f9fafb';
    dlUrl.style.color = '#374151';
    dlUrl.style.cursor = 'not-allowed';

    dlType.addEventListener('change', function() {
        if (dlAdGroup) dlAdGroup.style.display = 'none';
        if (dlUserGroup) dlUserGroup.style.display = 'none';
        if (dlPlanGroup) dlPlanGroup.style.display = 'none';

        if (this.value === 'ad') {
            if (dlAdGroup) dlAdGroup.style.display = 'block';
        } else if (this.value === 'user') {
            if (dlUserGroup) dlUserGroup.style.display = 'block';
        } else if (this.value === 'plan') {
            if (dlPlanGroup) dlPlanGroup.style.display = 'block';
            updatePlanUrl();
        } else if (this.value === 'custom') {
            dlUrl.removeAttribute('readonly');
            dlUrl.style.background = '#fff';
            dlUrl.style.cursor = 'text';
            dlUrl.focus();
        } else {
            dlUrl.value = '';
            dlUrl.setAttribute('readonly', true);
            dlUrl.style.background = '#f9fafb';
            dlUrl.style.cursor = 'not-allowed';
        }
    });

    // Ad Search
    let adTimeout;
    dlAdSearch.addEventListener('input', function() {
        clearTimeout(adTimeout);
        const query = this.value;
        if (query.length < 2) { dlAdResults.style.display = 'none'; return; }
        
        adTimeout = setTimeout(() => {
            fetch(`<?php echo e(route('admin.notifications.search.ads')); ?>?q=${encodeURIComponent(query)}`)
                .then(res => res.json())
                .then(data => {
                    dlAdResults.innerHTML = '';
                    dlAdResults.style.display = 'block';
                    data.forEach(ad => {
                        const div = document.createElement('div');
                        div.style.padding = '8px';
                        div.style.cursor = 'pointer';
                        div.style.borderBottom = '1px solid #eee';
                        div.textContent = ad.title;
                        div.onclick = () => {
                            dlUrl.value = `https://clxpro.com/deeplink/ad-details?ad_id=${ad.id}`;
                            dlAdSearch.value = ad.title;
                            dlAdResults.style.display = 'none';
                        };
                        dlAdResults.appendChild(div);
                    });
                });
        }, 300);
    });

    // User Search (Deep Link)
    let userTimeout;
    dlUserSearch.addEventListener('input', function() {
        clearTimeout(userTimeout);
        const query = this.value;
        if (query.length < 2) { dlUserResults.style.display = 'none'; return; }
        
        userTimeout = setTimeout(() => {
            fetch(`<?php echo e(route('admin.notifications.search.users')); ?>?q=${encodeURIComponent(query)}`)
                .then(res => res.json())
                .then(data => {
                    dlUserResults.innerHTML = '';
                    dlUserResults.style.display = 'block';
                    data.forEach(user => {
                        const div = document.createElement('div');
                        div.style.padding = '8px';
                        div.style.cursor = 'pointer';
                        div.style.borderBottom = '1px solid #eee';
                        div.textContent = `${user.name} (${user.email})`;
                        div.onclick = () => {
                            dlUrl.value = `https://clxpro.com/deeplink/user-profile?user_id=${user.id}`;
                            dlUserSearch.value = user.name;
                            dlUserResults.style.display = 'none';
                        };
                        dlUserResults.appendChild(div);
                    });
                });
        }, 300);
    });

    // Plan Select
    function updatePlanUrl() {
        const plan = dlPlanSelect.value;
        dlUrl.value = `https://clxpro.com/deeplink/premium-plans?plan=${encodeURIComponent(plan)}`;
    }
    dlPlanSelect.addEventListener('change', updatePlanUrl);

    // ==================================
    // USER SEARCH AUTOCOMPLETE
    // ==================================
    const userSearchInput = document.getElementById('user_search_input');
    const userSearchResults = document.getElementById('user_search_results');
    const selectedUsersContainer = document.getElementById('selected_users');
    const selectedUserIdsInput = document.getElementById('selected_user_ids');
    let selectedUsers = [];
    let userSearchTimeout;

    userSearchInput.addEventListener('input', function() {
        clearTimeout(userSearchTimeout);
        const query = this.value;
        
        if (query.length < 2) {
            userSearchResults.style.display = 'none';
            return;
        }
        
        userSearchTimeout = setTimeout(() => {
            fetch(`<?php echo e(route('admin.notifications.search.users')); ?>?q=${encodeURIComponent(query)}`)
                .then(res => res.json())
                .then(data => {
                    userSearchResults.innerHTML = '';
                    if (data.length === 0) {
                        userSearchResults.innerHTML = '<div style="padding: 12px; color: #6b7280; text-align: center;">No users found</div>';
                    } else {
                        data.forEach(user => {
                            if (!selectedUsers.find(u => u.id === user.id)) {
                                const div = document.createElement('div');
                                div.style.cssText = 'padding: 12px; cursor: pointer; border-bottom: 1px solid #e5e7eb; transition: background 0.2s;';
                                div.innerHTML = `<strong>${user.name}</strong><br><small style="color: #6b7280;">${user.email}</small>`;
                                div.onmouseover = () => div.style.background = '#f3f4f6';
                                div.onmouseout = () => div.style.background = 'transparent';
                                div.onclick = () => addUser(user);
                                userSearchResults.appendChild(div);
                            }
                        });
                    }
                    userSearchResults.style.display = 'block';
                });
        }, 300);
    });

    function addUser(user) {
        if (!selectedUsers.find(u => u.id === user.id)) {
            selectedUsers.push(user);
            renderSelectedUsers();
            userSearchInput.value = '';
            userSearchResults.style.display = 'none';
        }
    }

    function removeUser(userId) {
        selectedUsers = selectedUsers.filter(u => u.id !== userId);
        renderSelectedUsers();
    }

    function renderSelectedUsers() {
        selectedUsersContainer.innerHTML = '';
        selectedUsers.forEach(user => {
            const tag = document.createElement('div');
            tag.style.cssText = 'display: flex; align-items: center; gap: 8px; padding: 6px 12px; background: #eef2ff; border: 1px solid #c7d2fe; border-radius: 6px; font-size: 14px;';
            tag.innerHTML = `
                <span style="color: #4f46e5; font-weight: 500;">${user.name}</span>
                <button type="button" onclick="event.preventDefault(); removeUser(${user.id})" 
                        style="background: none; border: none; color: #6b7280; cursor: pointer; font-size: 16px; line-height: 1; padding: 0 4px;">×</button>
            `;
            selectedUsersContainer.appendChild(tag);
        });
        
        // Update hidden input
        const form = document.querySelector('form');
        form.querySelectorAll('input[name="target_value[user_ids][]"]').forEach(el => {
            if (el.id !== 'selected_user_ids') el.remove();
        });
        
        selectedUsers.forEach(user => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'target_value[user_ids][]';
            input.value = user.id;
            form.appendChild(input);
        });
    }

    // Make removeUser global
    window.removeUser = removeUser;

    // Close autocomplete when clicking outside
    document.addEventListener('click', function(e) {
        if (!userSearchInput.contains(e.target) && !userSearchResults.contains(e.target)) {
            userSearchResults.style.display = 'none';
        }
    });

    // ==================================
    // LOCATION AUTOCOMPLETE
    // ==================================
    function setupLocationAutocomplete(inputId, resultsId, searchRoute) {
        const input = document.getElementById(inputId);
        const results = document.getElementById(resultsId);
        let timeout;

        input.addEventListener('input', function() {
            clearTimeout(timeout);
            const query = this.value;
            
            if (query.length < 2) {
                results.style.display = 'none';
                updateLocationPreview();
                return;
            }
            
            timeout = setTimeout(() => {
                fetch(`${searchRoute}?q=${encodeURIComponent(query)}`)
                    .then(res => res.json())
                    .then(data => {
                        results.innerHTML = '';
                        if (data.length === 0) {
                            results.innerHTML = '<div style="padding: 8px; color: #6b7280; font-size: 12px;">No locations found</div>';
                        } else {
                            data.forEach(item => {
                                const div = document.createElement('div');
                                div.style.cssText = 'padding: 8px; cursor: pointer; font-size: 13px; border-bottom: 1px solid #e5e7eb; transition: background 0.15s;';
                                div.textContent = item.label;
                                div.onmouseover = () => div.style.background = '#f3f4f6';
                                div.onmouseout = () => div.style.background = 'transparent';
                                div.onclick = () => {
                                    input.value = item.value;
                                    results.style.display = 'none';
                                    updateLocationPreview();
                                };
                                results.appendChild(div);
                            });
                        }
                        results.style.display = 'block';
                    });
            }, 300);
        });

        // Close on outside click
        document.addEventListener('click', function(e) {
            if (!input.contains(e.target) && !results.contains(e.target)) {
                results.style.display = 'none';
            }
        });

        // Update preview on change
        input.addEventListener('change', updateLocationPreview);
    }

    function updateLocationPreview() {
        const city = document.getElementById('city_input').value;
        const state = document.getElementById('state_input').value;
        const country = document.getElementById('country_input').value;
        const preview = document.getElementById('location_preview');
        const previewText = document.getElementById('location_preview_text');

        const parts = [];
        if (city) parts.push(city);
        if (state) parts.push(state);
        if (country) parts.push(country);

        if (parts.length > 0) {
            previewText.textContent = parts.join(', ');
            preview.style.display = 'block';
        } else {
            preview.style.display = 'none';
        }
    }

    // Setup location autocompletes
    setupLocationAutocomplete('city_input', 'city_results', '<?php echo e(route("admin.notifications.search.cities")); ?>');
    setupLocationAutocomplete('state_input', 'state_results', '<?php echo e(route("admin.notifications.search.states")); ?>');
    setupLocationAutocomplete('country_input', 'country_results', '<?php echo e(route("admin.notifications.search.countries")); ?>');

    // Initial check
    targetTypeSelect.dispatchEvent(new Event('change'));
});
</script>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\DND\Apps\CLXpro\clx_backend\resources\views/admin/notifications/create.blade.php ENDPATH**/ ?>