// Custom Status Page JavaScript
(function() {
    'use strict';
    
    // Wait for jQuery to be available
    function initCustomStatusPage() {
        if (typeof jQuery === 'undefined') {
            setTimeout(initCustomStatusPage, 100);
            return;
        }
        
        jQuery(document).ready(function($) {
            // Initialize page functionality
            initializeCustomStatusPage();
            
            function initializeCustomStatusPage() {
                // Form validation and submission
                setupFormValidation();
                
                // Color picker updates
                setupColorPickerHandlers();
                
                // Status type toggle
                setupStatusTypeToggle();
                
                // Edit functionality
                setupEditHandlers();
                
                // Delete functionality
                setupDeleteHandlers();
                
                // Toggle functionality
                setupToggleHandlers();
                
                // Icon picker functionality
                setupIconPicker();
                
                // Sync functionality
                setupSyncHandler();
                
                // Cache clear functionality
        
            }
            
            function setupFormValidation() {
                const form = $('.kdsamref-status-form');
                if (!form.length) return;
                
                form.on('submit', function(e) {
                    e.preventDefault();
                    
                    const slug = $('#status_slug').val().trim();
                    const label = $('#status_label').val().trim();
                    const color = $('#status_color').val();
                    const icon = $('#status_icon').val();
                    const iconFamily = $('#status_icon_family').val();
                    const enabled = $('#status_enabled').is(':checked') ? 1 : 0;
                    const type = $('#status_type').val();
                    const editSlug = $('#edit_slug').val();
                    
                    if (!slug || !label) {
                        showNotification('Status slug and label are required.', 'error');
                        return false;
                    }
                    
                    // Validate slug format
                    if (!/^[a-z0-9_-]+$/.test(slug)) {
                        showNotification('Status slug can only contain lowercase letters, numbers, hyphens, and underscores.', 'error');
                        return false;
                    }
                    
                    // Submit via AJAX
                    const formData = new FormData();
                    formData.append('action', 'kdsamref_save_custom_status');
                    formData.append('nonce', kdsamrefData.nonce);
                    formData.append('status_slug', slug);
                    formData.append('status_label', label);
                    formData.append('status_color', color);
                    formData.append('status_icon', icon);
                    formData.append('status_icon_family', iconFamily);
                    formData.append('status_enabled', enabled);
                    formData.append('status_type', type);
                    if (editSlug) {
                        formData.append('edit_slug', editSlug);
                    }
                    
                    $.ajax({
                        url: kdsamrefData.ajaxUrl,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.success) {
                                showNotification(response.data.message, 'success');
                                setTimeout(() => {
                                    window.location.reload();
                                }, 1000);
                            } else {
                                showNotification(response.data.message, 'error');
                            }
                        },
                        error: function() {
                            showNotification('An error occurred while saving the status.', 'error');
                        }
                    });
                });
            }
            
            function setupColorPickerHandlers() {
                $(document).on('change', 'input[type="color"]', function() {
                    const colorValue = $(this).val();
                    const statusItem = $(this).closest('.kdsamref-status-item');
                    
                    if (statusItem.length) {
                        const colorIndicator = statusItem.find('.kdsamref-status-color');
                        if (colorIndicator.length) {
                            colorIndicator.css('background-color', colorValue);
                        }
                    }
                });
            }
            
            function setupStatusTypeToggle() {
                const statusTypeSelect = $('#status_type');
                const slugField = $('#status_slug');
                
                if (statusTypeSelect.length && slugField.length) {
                    statusTypeSelect.on('change', function() {
                        const selectedValue = $(this).val();
                        
                        if (selectedValue && selectedValue !== 'custom') {
                            // Pre-fill slug with selected core status
                            slugField.val(selectedValue).prop('readonly', true);
                        } else {
                            slugField.val('').prop('readonly', false);
                        }
                    });
                }
            }
            
            function setupEditHandlers() {
                $(document).on('click', '.kdsamref-edit-btn', function(e) {
                    e.preventDefault();
                    
                    const slug = $(this).data('slug');
                    const statusCard = $(`.kdsamref-status-card[data-slug="${slug}"]`);
                    
                    if (!statusCard.length) {
                        showNotification('Status not found.', 'error');
                        return;
                    }
                    
                    // Get status data
                    const label = statusCard.find('.kdsamref-status-name').text();
                    const color = statusCard.find('.kdsamref-status-color-dot').css('background-color');
                    const icon = statusCard.find('.kdsamref-status-icon-display i').attr('class');
                    const type = statusCard.find('.kdsamref-type-badge').text().toLowerCase();
                    const enabled = statusCard.find('.kdsamref-toggle-btn').hasClass('kdsamref-active');
                    
                    // Convert RGB to hex if needed
                    let hexColor = '#007cba';
                    if (color && color.startsWith('rgb')) {
                        const hex = rgbToHex(color);
                        if (hex) {
                            hexColor = hex;
                        }
                    }
                    
                    // Extract icon class
                    let iconClass = 'fa-cog';
                    let iconFamily = 'fontawesome';
                    if (icon) {
                        const iconParts = icon.split(' ');
                        for (let part of iconParts) {
                            if (part.startsWith('fa-')) {
                                iconClass = part;
                                iconFamily = 'fontawesome';
                                break;
                            } else if (part.startsWith('dashicons-')) {
                                iconClass = part;
                                iconFamily = 'dashicons';
                                break;
                            }
                        }
                    }
                    
                    // Fill form
                    $('#status_slug').val(slug);
                    $('#status_label').val(label);
                    $('#status_color').val(hexColor);
                    $('#status_icon').val(iconClass);
                    $('#status_icon_family').val(iconFamily);
                    $('#status_type').val(type === 'custom' ? 'custom' : slug);
                    $('#status_enabled').prop('checked', enabled);
                    $('#edit_slug').val(slug);
                    
                    // Update icon preview
                    updateIconPreview(iconClass, iconFamily);
                    
                    // Change button text
                    $('.kdsamref-submit-btn').html('<span class="kdsamref-btn-icon">💾</span> Update Status');
                    $('#cancel-btn').show();
                    
                    // Scroll to form
                    $('html, body').animate({
                        scrollTop: $('.kdsamref-status-form').offset().top - 50
                    }, 500);
                });
            }
            
            function setupDeleteHandlers() {
                $(document).on('click', '.kdsamref-delete-btn', function(e) {
                    e.preventDefault();
                    
                    const slug = $(this).data('slug');
                    const statusCard = $(`.kdsamref-status-card[data-slug="${slug}"]`);
                    const statusName = statusCard.find('.kdsamref-status-name').text();
                    
                    const confirmMessage = `Are you sure you want to delete the status "${statusName}"? This action cannot be undone.`;
                    
                    if (confirm(confirmMessage)) {
                        const formData = new FormData();
                        formData.append('action', 'kdsamref_delete_custom_status');
                        formData.append('nonce', kdsamrefData.nonce);
                        formData.append('status_slug', slug);
                        
                        $.ajax({
                            url: kdsamrefData.ajaxUrl,
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function(response) {
                                if (response.success) {
                                    showNotification(response.data.message, 'success');
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 1000);
                                } else {
                                    showNotification(response.data.message, 'error');
                                }
                            },
                            error: function() {
                                showNotification('An error occurred while deleting the status.', 'error');
                            }
                        });
                    }
                });
            }
            
            function setupToggleHandlers() {
                $(document).on('click', '.kdsamref-toggle-btn', function(e) {
                    e.preventDefault();
                    
                    const slug = $(this).data('slug');
                    const currentEnabled = $(this).data('enabled');
                    const newEnabled = currentEnabled == 1 ? 0 : 1;
                    
                    // Update the status via AJAX
                    const formData = new FormData();
                    formData.append('action', 'kdsamref_save_custom_status');
                    formData.append('nonce', kdsamrefData.nonce);
                    formData.append('status_slug', slug);
                    formData.append('status_enabled', newEnabled);
                    
                    // Get current status data
                    const statusCard = $(`.kdsamref-status-card[data-slug="${slug}"]`);
                    const label = statusCard.find('.kdsamref-status-name').text();
                    const color = statusCard.find('.kdsamref-status-color-dot').css('background-color');
                    const icon = statusCard.find('.kdsamref-status-icon-display i').attr('class');
                    
                    // Convert RGB to hex if needed
                    let hexColor = '#007cba';
                    if (color && color.startsWith('rgb')) {
                        const hex = rgbToHex(color);
                        if (hex) {
                            hexColor = hex;
                        }
                    }
                    
                    // Extract icon class
                    let iconClass = 'fa-cog';
                    let iconFamily = 'fontawesome';
                    if (icon) {
                        const iconParts = icon.split(' ');
                        for (let part of iconParts) {
                            if (part.startsWith('fa-')) {
                                iconClass = part;
                                iconFamily = 'fontawesome';
                                break;
                            } else if (part.startsWith('dashicons-')) {
                                iconClass = part;
                                iconFamily = 'dashicons';
                                break;
                            }
                        }
                    }
                    
                    formData.append('status_label', label);
                    formData.append('status_color', hexColor);
                    formData.append('status_icon', iconClass);
                    formData.append('status_icon_family', iconFamily);
                    formData.append('status_type', 'custom');
                    
                    $.ajax({
                        url: kdsamrefData.ajaxUrl,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.success) {
                                // Update UI immediately
                                const btn = $(`.kdsamref-toggle-btn[data-slug="${slug}"]`);
                                if (newEnabled == 1) {
                                    btn.removeClass('kdsamref-inactive').addClass('kdsamref-active');
                                    btn.find('i').removeClass('fa-toggle-off').addClass('fa-toggle-on');
                                    btn.find('span').text('Active');
                                    btn.attr('title', 'Deactivate');
                                    btn.data('enabled', 1);
                                } else {
                                    btn.removeClass('kdsamref-active').addClass('kdsamref-inactive');
                                    btn.find('i').removeClass('fa-toggle-on').addClass('fa-toggle-off');
                                    btn.find('span').text('Inactive');
                                    btn.attr('title', 'Activate');
                                    btn.data('enabled', 0);
                                }
                                
                                // Update status state display
                                const statusState = statusItem.find('.kdsamref-status-state');
                                statusState.text(newEnabled == 1 ? 'Active' : 'Inactive');
                                
                                showNotification('Status updated successfully.', 'success');
                            } else {
                                showNotification(response.data.message, 'error');
                            }
                        },
                        error: function() {
                            showNotification('An error occurred while updating the status.', 'error');
                        }
                    });
                });
            }
            
            function setupIconPicker() {
                // Icon preview click to open picker
                $(document).on('click', '#icon_preview', function(e) {
                    e.preventDefault();
                    $('#kdsamref-icon-modal').css('display', 'flex').hide().fadeIn(300);
                    loadIcons('fontawesome');
                });
                
                // Modal close
                $(document).on('click', '.kdsamref-icon-modal-close', function() {
                    $('#kdsamref-icon-modal').fadeOut(300);
                });
                
                // Click outside modal to close
                $(document).on('click', '#kdsamref-icon-modal', function(e) {
                    if (e.target === this) {
                        $(this).fadeOut(300);
                    }
                });
                
                // Icon family tabs
                $(document).on('click', '.kdsamref-icon-tab', function() {
                    $('.kdsamref-icon-tab').removeClass('active');
                    $(this).addClass('active');
                    
                    const family = $(this).data('family');
                    loadIcons(family);
                });
                
                // Icon selection
                $(document).on('click', '.kdsamref-icon-option', function() {
                    const iconClass = $(this).data('icon');
                    const iconFamily = $(this).data('family');
                    
                    $('#status_icon').val(iconClass);
                    $('#status_icon_family').val(iconFamily);
                    updateIconPreview(iconClass, iconFamily);
                    
                    $('#kdsamref-icon-modal').fadeOut(300);
                });
                
                // Icon search functionality
                $(document).on('input', '#kdsamref-icon-search', function() {
                    const searchTerm = $(this).val().toLowerCase();
                    const currentFamily = $('.kdsamref-icon-tab.active').data('family');
                    
                    $('.kdsamref-icon-option').each(function() {
                        const iconClass = $(this).data('icon').toLowerCase();
                        const iconName = $(this).find('i').attr('title') || iconClass;
                        
                        if (iconClass.includes(searchTerm) || iconName.includes(searchTerm)) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                });
                
                // Clear search when changing tabs
                $(document).on('click', '.kdsamref-icon-tab', function() {
                    $('#kdsamref-icon-search').val('');
                    $('.kdsamref-icon-option').show();
                });
            }
            
            function loadIcons(family) {
                const iconGrid = $('#kdsamref-icon-grid');
                iconGrid.empty();
                
                let icons = [];
                
                if (family === 'fontawesome') {
                    icons = [
                        // Temel iconlar
                        'fa-cog', 'fa-check', 'fa-times', 'fa-clock', 'fa-fire', 'fa-star',
                        'fa-heart', 'fa-thumbs-up', 'fa-thumbs-down', 'fa-exclamation',
                        'fa-question', 'fa-info', 'fa-triangle-exclamation', 'fa-bell', 'fa-flag',
                        'fa-tag', 'fa-bookmark', 'fa-calendar', 'fa-calendar-check',
                        'fa-calendar-xmark', 'fa-calendar-plus', 'fa-calendar-minus',
                        'fa-clock', 'fa-hourglass', 'fa-hourglass-start', 'fa-hourglass-half',
                        'fa-hourglass-end', 'fa-stopwatch', 'fa-timer', 'fa-calendar',
                        
                        // Sipariş ve işlem iconları
                        'fa-shopping-cart', 'fa-shopping-bag', 'fa-box', 'fa-boxes',
                        'fa-truck', 'fa-shipping-fast', 'fa-route', 'fa-map-marker-alt',
                        'fa-location-dot', 'fa-phone', 'fa-envelope', 'fa-user',
                        'fa-users', 'fa-user-check', 'fa-user-clock', 'fa-user-cog',
                        'fa-user-edit', 'fa-user-plus', 'fa-user-minus', 'fa-user-times',
                        
                        // Ödeme ve finans iconları
                        'fa-credit-card', 'fa-money-bill', 'fa-coins', 'fa-wallet',
                        'fa-cash-register', 'fa-receipt', 'fa-file-invoice',
                        'fa-chart-line', 'fa-chart-bar', 'fa-chart-pie',
                        'fa-percentage', 'fa-dollar-sign', 'fa-euro-sign',
                        
                        // Durum ve bildirim iconları
                        'fa-circle-check', 'fa-circle-xmark', 'fa-circle-exclamation',
                        'fa-circle-info', 'fa-circle-question', 'fa-circle-plus',
                        'fa-circle-minus', 'fa-circle-pause', 'fa-circle-play',
                        'fa-circle-stop', 'fa-circle-dot', 'fa-circle-notch',
                        
                        // Aksiyon ve kontrol iconları
                        'fa-play', 'fa-pause', 'fa-stop', 'fa-forward', 'fa-backward',
                        'fa-fast-forward', 'fa-fast-backward', 'fa-step-forward',
                        'fa-step-backward', 'fa-redo', 'fa-undo', 'fa-sync',
                        'fa-rotate', 'fa-arrows-rotate', 'fa-refresh',
                        
                        // Dosya ve belge iconları
                        'fa-file', 'fa-file-alt', 'fa-file-text', 'fa-file-pdf',
                        'fa-file-word', 'fa-file-excel', 'fa-file-image',
                        'fa-file-video', 'fa-file-audio', 'fa-file-archive',
                        'fa-file-code', 'fa-file-contract', 'fa-file-invoice-dollar',
                        
                        // İletişim ve sosyal iconları
                        'fa-comment', 'fa-comments', 'fa-comment-dots',
                        'fa-comment-slash', 'fa-comment-medical', 'fa-comment-dollar',
                        'fa-phone-square', 'fa-phone-volume', 'fa-phone-slash',
                        'fa-envelope-open', 'fa-envelope-square', 'fa-at',
                        
                        // Güvenlik ve erişim iconları
                        'fa-lock', 'fa-unlock', 'fa-key', 'fa-shield',
                        'fa-shield-alt', 'fa-shield-check', 'fa-shield-virus',
                        'fa-user-shield', 'fa-user-lock', 'fa-user-secret',
                        'fa-eye', 'fa-eye-slash', 'fa-eye-low-vision',
                        
                        // Teknoloji ve sistem iconları
                        'fa-desktop', 'fa-laptop', 'fa-tablet', 'fa-mobile',
                        'fa-server', 'fa-database', 'fa-network-wired',
                        'fa-wifi', 'fa-bluetooth', 'fa-satellite-dish',
                        'fa-microchip', 'fa-memory', 'fa-hard-drive',
                        
                        // Sağlık ve tıp iconları
                        'fa-heartbeat', 'fa-heart-pulse', 'fa-stethoscope',
                        'fa-user-md', 'fa-user-nurse', 'fa-hospital',
                        'fa-clinic-medical', 'fa-pills', 'fa-prescription-bottle',
                        'fa-thermometer', 'fa-temperature-high', 'fa-temperature-low',
                        
                        // Yiyecek ve restoran iconları
                        'fa-utensils', 'fa-cutlery', 'fa-coffee', 'fa-mug-hot',
                        'fa-pizza-slice', 'fa-hamburger', 'fa-ice-cream',
                        'fa-cookie', 'fa-cake-candles', 'fa-wine-glass',
                        'fa-beer', 'fa-glass-martini', 'fa-cocktail',
                        
                        // Spor ve aktivite iconları
                        'fa-futbol', 'fa-basketball', 'fa-volleyball',
                        'fa-running', 'fa-walking', 'fa-biking',
                        'fa-swimming', 'fa-skiing', 'fa-snowboarding',
                        'fa-dumbbell', 'fa-heart', 'fa-fire',
                        
                        // Hava durumu ve doğa iconları
                        'fa-sun', 'fa-moon', 'fa-cloud', 'fa-cloud-rain',
                        'fa-cloud-sun', 'fa-cloud-moon', 'fa-bolt',
                        'fa-snowflake', 'fa-umbrella', 'fa-wind',
                        'fa-leaf', 'fa-tree', 'fa-seedling',
                        
                        // Ulaşım ve seyahat iconları
                        'fa-car', 'fa-bus', 'fa-train', 'fa-plane',
                        'fa-ship', 'fa-bicycle', 'fa-motorcycle',
                        'fa-taxi', 'fa-truck', 'fa-van-shuttle',
                        'fa-rocket', 'fa-helicopter', 'fa-satellite',
                        
                        // Eğlence ve medya iconları
                        'fa-music', 'fa-video', 'fa-camera', 'fa-photo-film',
                        'fa-gamepad', 'fa-dice', 'fa-chess',
                        'fa-trophy', 'fa-medal', 'fa-award',
                        'fa-gift', 'fa-birthday-cake', 'fa-party-horn',
                        
                        // İş ve ofis iconları
                        'fa-briefcase', 'fa-suitcase', 'fa-building',
                        'fa-industry', 'fa-warehouse', 'fa-store',
                        'fa-shopping-bag', 'fa-cart-shopping', 'fa-cart-plus',
                        'fa-cart-arrow-down', 'fa-cart-flatbed', 'fa-dolly',
                        
                        // Eğitim ve öğrenme iconları
                        'fa-graduation-cap', 'fa-book', 'fa-book-open',
                        'fa-chalkboard', 'fa-chalkboard-user', 'fa-school',
                        'fa-university', 'fa-library', 'fa-microscope',
                        'fa-flask', 'fa-atom', 'fa-dna',
                        
                        // Güvenlik ve acil durum iconları
                        'fa-exclamation-triangle', 'fa-radiation', 'fa-biohazard',
                        'fa-skull-crossbones', 'fa-virus', 'fa-virus-slash',
                        'fa-mask', 'fa-head-side-mask', 'fa-head-side-cough',
                        'fa-hand-holding-medical', 'fa-first-aid', 'fa-kit-medical'
                    ];
                } else if (family === 'dashicons') {
                    icons = [
                        // Temel iconlar
                        'dashicons-yes', 'dashicons-no', 'dashicons-clock', 'dashicons-flag',
                        'dashicons-star-filled', 'dashicons-star-empty', 'dashicons-heart',
                        'dashicons-thumbs-up', 'dashicons-thumbs-down', 'dashicons-warning',
                        'dashicons-info', 'dashicons-bell', 'dashicons-calendar',
                        'dashicons-calendar-alt', 'dashicons-hourglass', 'dashicons-marker',
                        'dashicons-location', 'dashicons-admin-generic', 'dashicons-admin-tools',
                        'dashicons-admin-plugins', 'dashicons-admin-settings',
                        
                        // Sipariş ve işlem iconları
                        'dashicons-cart', 'dashicons-products', 'dashicons-store',
                        'dashicons-carrot', 'dashicons-building', 'dashicons-businessman',
                        'dashicons-groups', 'dashicons-admin-users', 'dashicons-admin-user',
                        'dashicons-id-alt', 'dashicons-id', 'dashicons-businesswoman',
                        
                        // Ödeme ve finans iconları
                        'dashicons-money-alt', 'dashicons-chart-area', 'dashicons-chart-bar',
                        'dashicons-chart-line', 'dashicons-chart-pie', 'dashicons-calculator',
                        'dashicons-clipboard', 'dashicons-media-spreadsheet',
                        'dashicons-media-document', 'dashicons-media-text',
                        
                        // Durum ve bildirim iconları
                        'dashicons-yes-alt', 'dashicons-no-alt', 'dashicons-plus-alt',
                        'dashicons-minus-alt', 'dashicons-dismiss', 'dashicons-marker',
                        'dashicons-admin-site', 'dashicons-admin-home', 'dashicons-admin-links',
                        'dashicons-admin-page', 'dashicons-admin-post', 'dashicons-admin-media',
                        
                        // Aksiyon ve kontrol iconları
                        'dashicons-controls-play', 'dashicons-controls-pause',
                        'dashicons-controls-stop', 'dashicons-controls-forward',
                        'dashicons-controls-back', 'dashicons-controls-skipback',
                        'dashicons-controls-skipforward', 'dashicons-controls-repeat',
                        'dashicons-controls-volumeon', 'dashicons-controls-volumeoff',
                        
                        // Dosya ve belge iconları
                        'dashicons-media-default', 'dashicons-media-audio',
                        'dashicons-media-video', 'dashicons-media-interactive',
                        'dashicons-media-code', 'dashicons-media-archive',
                        'dashicons-media-spreadsheet', 'dashicons-media-document',
                        'dashicons-media-text', 'dashicons-media-images-alt',
                        'dashicons-media-images-alt2', 'dashicons-media-video-alt',
                        'dashicons-media-video-alt2', 'dashicons-media-video-alt3',
                        
                        // İletişim ve sosyal iconları
                        'dashicons-email', 'dashicons-email-alt', 'dashicons-email-alt2',
                        'dashicons-phone', 'dashicons-smartphone', 'dashicons-tablet',
                        'dashicons-desktop', 'dashicons-laptop', 'dashicons-admin-comments',
                        'dashicons-admin-network', 'dashicons-admin-site-alt',
                        'dashicons-admin-site-alt2', 'dashicons-admin-site-alt3',
                        
                        // Güvenlik ve erişim iconları
                        'dashicons-lock', 'dashicons-unlock', 'dashicons-shield',
                        'dashicons-shield-alt', 'dashicons-visibility', 'dashicons-hidden',
                        'dashicons-admin-users', 'dashicons-admin-user', 'dashicons-admin-network',
                        'dashicons-admin-generic', 'dashicons-admin-tools',
                        
                        // Teknoloji ve sistem iconları
                        'dashicons-admin-appearance', 'dashicons-admin-plugins',
                        'dashicons-admin-tools', 'dashicons-admin-settings',
                        'dashicons-admin-generic', 'dashicons-admin-network',
                        'dashicons-admin-site', 'dashicons-admin-home',
                        'dashicons-admin-links', 'dashicons-admin-page',
                        
                        // Sağlık ve tıp iconları
                        'dashicons-plus', 'dashicons-minus', 'dashicons-dismiss',
                        'dashicons-marker', 'dashicons-star-filled', 'dashicons-star-empty',
                        'dashicons-heart', 'dashicons-flag', 'dashicons-warning',
                        'dashicons-info', 'dashicons-yes', 'dashicons-no',
                        
                        // Yiyecek ve restoran iconları
                        'dashicons-carrot', 'dashicons-store', 'dashicons-cart',
                        'dashicons-products', 'dashicons-building', 'dashicons-admin-site',
                        'dashicons-admin-home', 'dashicons-admin-links',
                        'dashicons-admin-page', 'dashicons-admin-post',
                        
                        // Spor ve aktivite iconları
                        'dashicons-heart', 'dashicons-star-filled', 'dashicons-star-empty',
                        'dashicons-flag', 'dashicons-marker', 'dashicons-location',
                        'dashicons-admin-users', 'dashicons-admin-user',
                        'dashicons-groups', 'dashicons-businessman',
                        
                        // Hava durumu ve doğa iconları
                        'dashicons-sunny', 'dashicons-cloud', 'dashicons-rain',
                        'dashicons-lightning', 'dashicons-wind', 'dashicons-leaf',
                        'dashicons-tree', 'dashicons-marker', 'dashicons-location',
                        'dashicons-admin-site', 'dashicons-admin-home',
                        
                        // Ulaşım ve seyahat iconları
                        'dashicons-car', 'dashicons-bus', 'dashicons-train',
                        'dashicons-plane', 'dashicons-ship', 'dashicons-bicycle',
                        'dashicons-motorcycle', 'dashicons-taxi', 'dashicons-truck',
                        'dashicons-admin-site', 'dashicons-admin-home',
                        
                        // Eğlence ve medya iconları
                        'dashicons-format-video', 'dashicons-format-audio',
                        'dashicons-format-image', 'dashicons-format-gallery',
                        'dashicons-format-chat', 'dashicons-format-status',
                        'dashicons-format-aside', 'dashicons-format-quote',
                        'dashicons-format-links', 'dashicons-format-standard',
                        
                        // İş ve ofis iconları
                        'dashicons-building', 'dashicons-store', 'dashicons-cart',
                        'dashicons-products', 'dashicons-admin-site',
                        'dashicons-admin-home', 'dashicons-admin-links',
                        'dashicons-admin-page', 'dashicons-admin-post',
                        'dashicons-admin-media', 'dashicons-admin-comments',
                        
                        // Eğitim ve öğrenme iconları
                        'dashicons-book', 'dashicons-book-alt', 'dashicons-welcome-learn-more',
                        'dashicons-welcome-write-blog', 'dashicons-welcome-view-site',
                        'dashicons-welcome-widgets-menus', 'dashicons-welcome-comments',
                        'dashicons-welcome-add-page', 'dashicons-welcome-edit-page',
                        'dashicons-welcome-write-blog', 'dashicons-welcome-view-site',
                        
                        // Güvenlik ve acil durum iconları
                        'dashicons-shield', 'dashicons-shield-alt', 'dashicons-lock',
                        'dashicons-unlock', 'dashicons-warning', 'dashicons-info',
                        'dashicons-yes', 'dashicons-no', 'dashicons-dismiss',
                        'dashicons-marker', 'dashicons-admin-site'
                    ];
                }
                
                icons.forEach(icon => {
                    const iconName = icon.replace('fa-', '').replace('dashicons-', '').replace(/-/g, ' ');
                    const iconOption = $(`
                        <div class="kdsamref-icon-option" data-icon="${icon}" data-family="${family}" title="${iconName}">
                            <i class="${family === 'dashicons' ? 'dashicons' : 'fas'} ${icon}" title="${iconName}"></i>
                        </div>
                    `);
                    iconGrid.append(iconOption);
                });
            }
            
            function updateIconPreview(iconClass, iconFamily) {
                const preview = $('#icon_preview');
                const familyClass = iconFamily === 'dashicons' ? 'dashicons' : 'fas';
                preview.html(`<i class="${familyClass} ${iconClass}"></i>`);
            }
            
            // Cancel edit
            $(document).on('click', '#cancel-btn', function() {
                resetForm();
            });
            
            function resetForm() {
                $('.kdsamref-status-form')[0].reset();
                $('#edit_slug').val('');
                $('.kdsamref-submit-btn').html('<span class="kdsamref-btn-icon">💾</span> Save Status');
                $('#cancel-btn').hide();
                updateIconPreview('fa-cog', 'fontawesome');
            }
            
            function setupSyncHandler() {
                const syncBtn = $('#sync-orderable-pro-btn');
                if (!syncBtn.length) return;
                
                syncBtn.on('click', function(e) {
                    e.preventDefault();
                    
                    if (!confirm('This will sync custom statuses from Orderable Pro. Continue?')) {
                        return;
                    }
                    
                    const $btn = $(this);
                    const originalText = $btn.text();
                    $btn.prop('disabled', true).text('Syncing...');
                    
                    $.post(kdsamrefData.ajaxUrl, {
                        action: 'kdsamref_sync_orderable_pro_statuses',
                        nonce: kdsamrefData.nonce
                    }, function(response) {
                        if (response.success) {
                            showNotification(response.data.message, 'success');
                            setTimeout(() => {
                                window.location.reload();
                            }, 1000);
                        } else {
                            showNotification(response.data.message, 'error');
                        }
                    }).fail(function() {
                        showNotification('Sync failed. Please try again.', 'error');
                    }).always(function() {
                        $btn.prop('disabled', false).text(originalText);
                    });
                });
            }
            

            
            function showNotification(message, type = 'info', duration = 5000) {
                const typeClasses = {
                    'success': 'notice-success',
                    'error': 'notice-error', 
                    'warning': 'notice-warning',
                    'info': 'notice-info'
                };
                
                const notification = $(`
                    <div class="notice ${typeClasses[type] || 'notice-info'} is-dismissible">
                        <p>${message}</p>
                        <button type="button" class="notice-dismiss">
                            <span class="screen-reader-text">Dismiss</span>
                        </button>
                    </div>
                `);
                
                // Find the best place to insert notification
                const target = $('.kdsamref-page-header').length ? 
                              $('.kdsamref-page-header') : 
                              $('.wrap').first();
                
                target.after(notification);
                
                // Auto remove
                setTimeout(() => {
                    notification.fadeOut(300, function() { 
                        $(this).remove(); 
                    });
                }, duration);
                
                // Manual dismiss
                notification.find('.notice-dismiss').on('click', function() {
                    notification.fadeOut(300, function() { 
                        $(this).remove(); 
                    });
                });
            }
            
            // Helper function to convert RGB to HEX
            function rgbToHex(rgb) {
                const result = rgb.match(/\d+/g);
                if (result && result.length >= 3) {
                    return "#" + ((1 << 24) + (parseInt(result[0]) << 16) + (parseInt(result[1]) << 8) + parseInt(result[2])).toString(16).slice(1);
                }
                return null;
            }
            
            // Status list filtering
            $('#status-search').on('input', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.kdsamref-status-item').each(function() {
                    const statusName = $(this).find('.kdsamref-status-details h4').text().toLowerCase();
                    const statusSlug = $(this).find('.kdsamref-status-details code').text().toLowerCase();
                    
                    if (statusName.includes(searchTerm) || statusSlug.includes(searchTerm)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
            
            // Status source filtering
            $('#status-source-filter').on('change', function() {
                const selectedSource = $(this).val();
                
                $('.kdsamref-status-item').each(function() {
                    const statusSource = $(this).find('.kdsamref-status-source').text().toLowerCase();
                    
                    if (!selectedSource || statusSource.includes(selectedSource)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
        });
    }
    
    // Start initialization
    initCustomStatusPage();
})();