<?php
/**
 * Name: Admin Columns Manager
 * Description: Manage, reorder, hide, and customize admin list table columns for all post types with drag-and-drop interface and custom fields support for developers
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "E-Commerce Order Management",
 *     "description": "Add custom columns showing order total, payment status, and shipping method directly in the WooCommerce orders list for faster processing."
 *   },
 *   {
 *     "title": "Membership Site Tracking",
 *     "description": "Display member subscription level, expiration date, and last login directly in the users table without opening each profile."
 *   },
 *   {
 *     "title": "Content Publisher Workflow",
 *     "description": "Show author name, word count, and SEO score columns in posts list to quickly identify articles needing attention before publication."
 *   }
 * ]
 * Added: 2025-10-01
 * Tags: columns, admin, tables, custom fields, reorder, manage
 * WhereToFind: {
 *   "location": "Switchboard → Columns Manager",
 *   "url": "admin.php?page=admin-columns-manager",
 *   "instructions": "Manage, reorder, hide, and customize admin list table columns for all post types",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardAdminColumnsManager {
    
    private $settings;
    
    public function __construct() {
        $this->settings = get_option('switchboard_admin-columns-manager_settings', []);
        if (!is_array($this->settings)) {
            $this->settings = [];
        }

        // Apply column modifications
        add_action('admin_init', [$this, 'apply_column_modifications']);

        // Admin menu
        add_action('admin_menu', [$this, 'add_admin_menu']);

        // Enqueue admin assets
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);

        // AJAX handlers
        add_action('wp_ajax_save_column_config', [$this, 'ajax_save_column_config']);
        add_action('wp_ajax_get_post_type_columns', [$this, 'ajax_get_post_type_columns']);
        add_action('wp_ajax_get_custom_fields', [$this, 'ajax_get_custom_fields']);
        add_action('wp_ajax_get_post_type_taxonomies', [$this, 'ajax_get_post_type_taxonomies']);
    }

    /**
     * Add admin menu for Columns Manager
     */
    public function add_admin_menu() {
        add_submenu_page(
            'switchboard',
            __('Columns Manager', 'wpswitchboard'),
            __('Columns Manager', 'wpswitchboard'),
            'manage_options',
            'admin-columns-manager',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Enqueue admin assets only on our page
     */
    public function enqueue_admin_assets($hook) {
        // Check if we're on the columns manager page (check both hook and GET parameter)
        $is_columns_page = (
            (isset($_GET['page']) && $_GET['page'] === 'admin-columns-manager') ||
            strpos($hook, 'admin-columns-manager') !== false
        );

        if (!$is_columns_page) {
            return;
        }

        // Enqueue the main Switchboard admin CSS (contains all sb-module-* and sb-module-* classes)
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-admin',
                SWITCHBOARD_URL . 'switchboard-admin.css',
                [],
                SWITCHBOARD_VERSION
            );
        }

        // Enqueue jQuery UI for drag-and-drop
        wp_enqueue_script('jquery-ui-sortable');
    }

    public function apply_column_modifications() {
        if (empty($this->settings)) return;

        foreach ($this->settings as $post_type => $config) {
            // Validate config structure
            if (empty($config['columns']) || !is_array($config['columns'])) continue;

            // Validate post type exists
            if (!post_type_exists($post_type)) continue;

            // Manage columns
            add_filter("manage_{$post_type}_posts_columns", function($columns) use ($config) {
                return $this->modify_columns($columns, $config);
            }, 999);

            // Add CSS classes to column headers
            add_filter("manage_{$post_type}_posts_columns", function($columns) use ($config) {
                return $this->add_column_classes($columns, $config);
            }, 9999);

            // Populate ALL columns (both custom and our quick-add columns)
            add_action("manage_{$post_type}_posts_custom_column", function($column, $post_id) use ($config) {
                $this->populate_column($column, $post_id, $config);
            }, 10, 2);

            // Make columns sortable if needed
            add_filter("manage_edit-{$post_type}_sortable_columns", function($columns) use ($config) {
                return $this->make_sortable($columns, $config);
            });

            // Handle custom sorting queries (only on edit screen for this post type)
            add_action('pre_get_posts', function($query) use ($post_type) {
                // Only run on admin list table queries
                if (!is_admin() || !$query->is_main_query()) {
                    return;
                }

                $screen = get_current_screen();
                if (!$screen || $screen->id !== 'edit-' . $post_type) {
                    return;
                }

                $this->handle_column_sorting($query, $post_type);
            });

            // Add column styles and JS for classes (only on edit screens)
            add_action('admin_head', function() use ($config, $post_type) {
                $screen = get_current_screen();
                if ($screen && $screen->id === 'edit-' . $post_type) {
                    $this->add_column_styles($config);
                    $this->add_column_header_classes_js($config, $post_type);
                }
            }, 10);
        }
    }
    
    private function modify_columns($columns, $config) {
        $new_columns = [];
        $enabled_columns = array_filter($config['columns'], function($col) {
            return !empty($col['enabled']);
        });

        // If no columns are configured or enabled, return original columns
        if (empty($enabled_columns)) {
            return $columns;
        }

        // Check if Compact Tables wants compact date format
        $compact_tables_settings = get_option('switchboard_compact-tables_settings', []);
        $use_compact_date = !empty($compact_tables_settings['compact_date']) && $compact_tables_settings['compact_date'] === '1';

        // Sort by order
        usort($enabled_columns, function($a, $b) {
            return ($a['order'] ?? 0) - ($b['order'] ?? 0);
        });

        foreach ($enabled_columns as $col) {
            $col_id = $col['id'];

            // Integration with Compact Tables: convert date to compact_date if enabled
            if ($col_id === 'date' && $use_compact_date) {
                $col_id = 'compact_date';
                $new_columns[$col_id] = esc_html__('Published', 'wpswitchboard');
                continue;
            }

            // Use custom label if provided, otherwise fall back to WordPress default
            // For taxonomy columns, if no custom label is set, use WordPress's dynamic label for translation support
            if (!empty($col['label'])) {
                $new_columns[$col_id] = esc_html($col['label']);
            } elseif (isset($columns[$col_id])) {
                // Use the current WordPress column label (translated by Polylang if active)
                $new_columns[$col_id] = $columns[$col_id];
            } else {
                $new_columns[$col_id] = esc_html($col_id);
            }
        }

        return $new_columns;
    }
    
    private function add_column_classes($columns, $config) {
        // This filter runs after modify_columns, just return columns as-is
        // Classes will be added via JavaScript
        return $columns;
    }
    
    private function populate_column($column, $post_id, $config) {
        $col_config = null;
        foreach ($config['columns'] as $col) {
            if ($col['id'] === $column) {
                $col_config = $col;
                break;
            }
        }

        if (!$col_config) return;

        // Start output for wrapping
        ob_start();

        // Handle quick-add columns with special logic
        switch ($column) {
            case 'modified':
                echo esc_html(get_the_modified_date('Y-m-d H:i', $post_id));
                break;

            case 'thumbnail':
                if (has_post_thumbnail($post_id)) {
                    // Use 'thumbnail' size with CSS class instead of inline styles
                    echo get_the_post_thumbnail($post_id, 'thumbnail', ['class' => 'switchboard-column-thumbnail']);
                } else {
                    echo '<span class="switchboard-column-empty">—</span>';
                }
                break;

            case 'post_id':
                echo esc_html($post_id);
                break;

            case 'word_count':
                $post = get_post($post_id);
                if ($post) {
                    $content = strip_shortcodes($post->post_content);
                    $content = wp_strip_all_tags($content);
                    $word_count = str_word_count($content);
                    echo esc_html(number_format($word_count));
                } else {
                    echo '—';
                }
                break;

            case 'slug':
                $post = get_post($post_id);
                if ($post) {
                    echo '<code class="switchboard-column-slug">' . esc_html($post->post_name) . '</code>';
                } else {
                    echo '—';
                }
                break;

            default:
                // Handle custom field columns
                if (!empty($col_config['meta_key'])) {
                    $value = get_post_meta($post_id, $col_config['meta_key'], true);
                    if (empty($value)) {
                        echo '—';
                    } elseif (is_array($value)) {
                        // Handle serialized/array meta values
                        echo esc_html(implode(', ', array_map('strval', $value)));
                    } else {
                        echo esc_html($value);
                    }
                }
                break;
        }

        // Get content - NO html_before/after wrapping to prevent XSS
        // Users should use CSS classes instead for styling
        $content = ob_get_clean();
        echo $content;
    }
    
    private function make_sortable($columns, $config) {
        foreach ($config['columns'] as $col) {
            if (!empty($col['sortable'])) {
                // For custom meta fields, use meta_key
                if (!empty($col['meta_key'])) {
                    $columns[$col['id']] = $col['meta_key'];
                } else {
                    // For built-in quick-add columns, use column ID
                    $columns[$col['id']] = $col['id'];
                }
            }
        }
        return $columns;
    }

    private function handle_column_sorting($query, $post_type) {
        $orderby = $query->get('orderby');
        if (!$orderby) {
            return;
        }

        // Handle sorting for quick-add columns
        switch ($orderby) {
            case 'modified':
                $query->set('orderby', 'modified');
                return;

            case 'post_id':
                $query->set('orderby', 'ID');
                return;

            case 'word_count':
                $query->set('orderby', 'title');
                return;

            case 'slug':
                $query->set('orderby', 'name');
                return;
        }

        // Handle sorting for custom meta field columns
        $config = isset($this->settings[$post_type]) ? $this->settings[$post_type] : null;
        if ($config && !empty($config['columns'])) {
            foreach ($config['columns'] as $col) {
                if (!empty($col['sortable']) && !empty($col['meta_key']) && $orderby === $col['meta_key']) {
                    $query->set('meta_key', $col['meta_key']);
                    $query->set('orderby', 'meta_value');
                    return;
                }
            }
        }
    }
    
    private function add_column_styles($config) {
        static $styles_added = [];
        $style_key = md5(serialize($config));

        // Only add styles once per config
        if (isset($styles_added[$style_key])) {
            return;
        }
        $styles_added[$style_key] = true;

        // Check if Compact Tables wants compact date format
        $compact_tables_settings = get_option('switchboard_compact-tables_settings', []);
        $use_compact_date = !empty($compact_tables_settings['compact_date']) && $compact_tables_settings['compact_date'] === '1';

        // Base styles for thumbnail and other quick-add columns
        $base_styles = '
            /* Override fixed table layout so min-width is respected */
            .wp-list-table.fixed {
                table-layout: auto !important;
            }
            /* Keep admin sidebar above scrolling table content */
            #adminmenuwrap,
            #adminmenuback {
                z-index: 10 !important;
            }
            /* Prevent columns from collapsing to unreadable widths */
            .wp-list-table th {
                white-space: nowrap;
            }
            .wp-list-table td {
                min-width: 50px;
                word-break: normal;
                overflow-wrap: break-word;
            }
            /* Thumbnail column styles */
            .wp-list-table .column-thumbnail {
                width: 60px;
            }
            .wp-list-table .switchboard-column-thumbnail {
                max-width: 50px;
                max-height: 50px;
                width: auto;
                height: auto;
                object-fit: cover;
                border-radius: 4px;
                vertical-align: middle;
            }
            .wp-list-table .switchboard-column-empty {
                color: #999;
            }
            .wp-list-table .switchboard-column-slug {
                font-size: 12px;
                background: #f0f0f1;
                padding: 2px 6px;
                border-radius: 3px;
            }
            /* Default widths for common columns to prevent cramping */
            .wp-list-table .column-post_id,
            .wp-list-table .column-switchboard_id {
                width: 50px;
            }
            .wp-list-table .column-modified,
            .wp-list-table .column-compact_date {
                width: 120px;
            }
            .wp-list-table .column-word_count,
            .wp-list-table .column-post_views {
                width: 90px;
            }
            .wp-list-table .column-slug {
                width: 150px;
            }
            .wp-list-table .column-tags,
            .wp-list-table .column-categories {
                width: 120px;
            }
            /* Taxonomy columns - auto width with minimum, prevent word-breaking */
            .wp-list-table [class*="column-taxonomy-"] {
                min-width: 100px;
                word-break: normal;
                overflow-wrap: normal;
            }
            .wp-list-table .column-featured_image {
                width: 80px;
            }
        ';

        // Dynamic column widths (user-configured)
        $width_styles = [];
        foreach ($config['columns'] as $col) {
            if (!empty($col['width'])) {
                $col_id = esc_attr($col['id']);

                // Integration with Compact Tables: apply date settings to compact_date
                if ($col['id'] === 'date' && $use_compact_date) {
                    $col_id = 'compact_date';
                }

                // Validate width format - allow numbers with px, %, em, rem units, or 'auto'
                $width = trim($col['width']);
                $is_valid_width = preg_match('/^(\d+(?:\.\d+)?)(px|%|em|rem)$/i', $width) || strtolower($width) === 'auto';
                if ($is_valid_width) {
                    $escaped_width = esc_attr($width);
                    // Force width uses min-width, max-width, and !important to override table layout
                    if (!empty($col['force_width'])) {
                        $width_styles[] = ".column-{$col_id} { width: {$escaped_width} !important; min-width: {$escaped_width} !important; max-width: {$escaped_width} !important; }";
                    } else {
                        $width_styles[] = ".column-{$col_id} { width: {$escaped_width}; }";
                    }
                }
            }
        }

        // Output styles
        echo '<style>';
        echo $base_styles;
        if (!empty($width_styles)) {
            echo implode("\n", $width_styles);
        }
        echo '</style>';
    }
    
    private function add_column_header_classes_js($config, $post_type) {
        static $js_added = [];
        $js_key = $post_type;

        // Only add JS once per post type
        if (isset($js_added[$js_key])) {
            return;
        }
        $js_added[$js_key] = true;

        // Check if Compact Tables wants compact date format
        $compact_tables_settings = get_option('switchboard_compact-tables_settings', []);
        $use_compact_date = !empty($compact_tables_settings['compact_date']) && $compact_tables_settings['compact_date'] === '1';

        $class_map = [];
        foreach ($config['columns'] as $col) {
            if (!empty($col['class'])) {
                $col_id = $col['id'];
                // Integration with Compact Tables: apply date class to compact_date
                if ($col_id === 'date' && $use_compact_date) {
                    $col_id = 'compact_date';
                }
                $class_map[$col_id] = $col['class'];
            }
        }

        if (empty($class_map)) {
            return;
        }
        
        ?>
        <script>
        jQuery(document).ready(function($) {
            var classMap = <?php echo wp_json_encode($class_map); ?>;
            $.each(classMap, function(colId, className) {
                // Escape column ID for safe selector usage
                var escapedColId = colId.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, '\\$&');
                // Add class only to tbody cells
                // Special handling for 'cb' column: WordPress uses th.check-column in tbody (no column-cb class)
                if (colId === 'cb') {
                    $('tbody th.check-column').addClass(className);
                } else {
                    $('tbody td.column-' + escapedColId + ', tbody th.column-' + escapedColId).addClass(className);
                }
            });
        });
        </script>
        <?php
    }
    
    public function ajax_get_post_type_columns() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        // Check user capability
        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized access.', 'wpswitchboard'));
            return;
        }

        $post_type = sanitize_text_field($_POST['post_type'] ?? 'post');

        // Validate post type exists
        if (!post_type_exists($post_type)) {
            wp_send_json_error(esc_html__('Invalid post type.', 'wpswitchboard'));
            return;
        }

        // Get default columns (returns associative array like ['title' => 'Title'])
        $columns_raw = $this->get_default_columns($post_type);

        // Transform to array of objects for JavaScript
        $columns = [];
        foreach ($columns_raw as $column_id => $column_label) {
            $columns[] = [
                'id' => $column_id,
                // Strip HTML tags from labels (WordPress sometimes includes HTML in column labels)
                'label' => wp_strip_all_tags($column_label),
                'enabled' => true,
                'meta_key' => '',
                'class' => '',
                'width' => '',
                'html_before' => '',
                'html_after' => '',
                'sortable' => false
            ];
        }

        // Load fresh settings from database
        $all_settings = get_option('switchboard_admin-columns-manager_settings', []);
        $saved_config = $all_settings[$post_type] ?? [];

        // If there's saved config with columns, use it; otherwise use WordPress defaults
        if (!empty($saved_config['columns']) && is_array($saved_config['columns'])) {
            $columns = $saved_config['columns'];
        }
        // If saved config is explicitly empty array, return WordPress defaults
        // This ensures "Reset to Defaults" works correctly

        wp_send_json_success([
            'columns' => $columns,
            'saved_config' => $saved_config
        ]);
    }

    public function ajax_get_custom_fields() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        // Check user capability
        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized access.', 'wpswitchboard'));
            return;
        }

        $post_type = sanitize_text_field($_POST['post_type'] ?? 'post');

        // Validate post type exists
        if (!post_type_exists($post_type)) {
            wp_send_json_error(esc_html__('Invalid post type.', 'wpswitchboard'));
            return;
        }

        global $wpdb;
        $meta_keys = $wpdb->get_col($wpdb->prepare(
            "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} pm
            INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
            WHERE p.post_type = %s
            AND meta_key NOT LIKE '\_%'
            ORDER BY meta_key
            LIMIT 5000",
            $post_type
        ));

        wp_send_json_success(['fields' => $meta_keys]);
    }

    /**
     * AJAX handler to get taxonomies for a post type
     */
    public function ajax_get_post_type_taxonomies() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        // Check user capability
        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized access.', 'wpswitchboard'));
            return;
        }

        $post_type = sanitize_text_field($_POST['post_type'] ?? 'post');

        // Validate post type exists
        if (!post_type_exists($post_type)) {
            wp_send_json_error(esc_html__('Invalid post type.', 'wpswitchboard'));
            return;
        }

        // Get all taxonomies registered for this post type
        $taxonomies = get_object_taxonomies($post_type, 'objects');

        $taxonomy_list = [];
        foreach ($taxonomies as $taxonomy) {
            // Skip non-public taxonomies
            if (!$taxonomy->public && !$taxonomy->show_ui) {
                continue;
            }

            $taxonomy_list[] = [
                'slug' => $taxonomy->name,
                'label' => $taxonomy->labels->name,
                'column_id' => 'taxonomy-' . $taxonomy->name
            ];
        }

        wp_send_json_success(['taxonomies' => $taxonomy_list]);
    }

    private function get_default_columns($post_type) {
        $post_type_obj = get_post_type_object($post_type);
        if (!$post_type_obj) return [];

        // Use WordPress's WP_List_Table to get the actual default columns
        // This ensures we get all columns that would normally appear
        if (!class_exists('WP_Posts_List_Table')) {
            require_once ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php';
        }

        $columns = [];
        $original_screen_id = null;

        try {
            // Set the current screen to trick WordPress into thinking we're on the actual post type screen
            $screen = get_current_screen();
            $original_screen_id = $screen ? $screen->id : null;

            // Temporarily set screen
            set_current_screen('edit-' . $post_type);

            // Temporarily disable Polylang filters on taxonomy labels to prevent translation issues
            // when retrieving default columns for the settings interface
            if (function_exists('PLL')) {
                remove_filter('get_term', [PLL()->filters_term, 'get_term'], 10);
            }

            // Create list table instance to get columns
            // Suppress warnings as screen context might not be perfect
            $list_table = @new WP_Posts_List_Table([
                'screen' => 'edit-' . $post_type
            ]);

            // Get the columns from the list table
            $columns = $list_table->get_columns();

            // Re-enable Polylang filters
            if (function_exists('PLL')) {
                add_filter('get_term', [PLL()->filters_term, 'get_term'], 10, 2);
            }
        } catch (Exception $e) {
            // If anything fails, return empty array
            error_log('Admin Columns Manager: Failed to get default columns - ' . $e->getMessage());

            // Re-enable Polylang filters even on error
            if (function_exists('PLL')) {
                add_filter('get_term', [PLL()->filters_term, 'get_term'], 10, 2);
            }
        } finally {
            // Always restore original screen
            if ($original_screen_id) {
                set_current_screen($original_screen_id);
            }
        }

        return $columns;
    }
    
    public function ajax_save_column_config() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized access.', 'wpswitchboard'));
            return;
        }

        $post_type = sanitize_text_field($_POST['post_type'] ?? '');
        $columns = json_decode(stripslashes($_POST['columns'] ?? '[]'), true);
        if (!is_array($columns)) {
            $columns = [];
        }

        if (empty($post_type) || !post_type_exists($post_type)) {
            wp_send_json_error(esc_html__('Invalid post type.', 'wpswitchboard'));
            return;
        }

        // Validate each column object
        $validated_columns = [];
        foreach ($columns as $col) {
            if (!is_array($col)) continue;

            $col_id = sanitize_key($col['id'] ?? '');

            // Skip if no ID
            if (empty($col_id)) continue;

            // Required fields with defaults
            $validated_col = [
                'id' => $col_id,
                'label' => sanitize_text_field($col['label'] ?? ''),
                'enabled' => !empty($col['enabled']),
                'order' => absint($col['order'] ?? 0),
                'meta_key' => preg_replace('/[^a-zA-Z0-9_\-]/', '', $col['meta_key'] ?? ''),
                'class' => sanitize_html_class($col['class'] ?? ''),
                'width' => sanitize_text_field($col['width'] ?? ''),
                'force_width' => !empty($col['force_width']),
                'sortable' => !empty($col['sortable'])
            ];

            $validated_columns[] = $validated_col;
        }

        // Load fresh settings from database to preserve other post types
        $all_settings = get_option('switchboard_admin-columns-manager_settings', []);

        // Save configuration for this post type
        $all_settings[$post_type] = [
            'columns' => $validated_columns
        ];

        update_option('switchboard_admin-columns-manager_settings', $all_settings);

        // Update instance variable
        $this->settings = $all_settings;

        wp_send_json_success(['message' => esc_html__('Configuration saved successfully.', 'wpswitchboard')]);
    }

    /**
     * Render the admin page for Columns Manager
     */
    public function render_admin_page() {
        ?>
        <style>
            /* Taxonomy list styles */
            .sb-module-taxonomy-items {
                display: flex;
                flex-direction: column;
                gap: 6px;
            }
            .sb-module-taxonomy-item {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 8px 12px;
                background: #fff;
                border: 1px solid #e2e4e7;
                border-radius: 6px;
                cursor: pointer;
                font-size: 13px;
                color: #1e1e1e;
                transition: all 0.15s ease;
                text-align: left;
                width: 100%;
            }
            .sb-module-taxonomy-item:hover:not(.added) {
                border-color: var(--primary-500, #3b82f6);
                background: var(--primary-50, #eff6ff);
            }
            .sb-module-taxonomy-item.added {
                background: #f0f0f1;
                color: #757575;
                cursor: not-allowed;
            }
            .sb-module-taxonomy-item svg {
                flex-shrink: 0;
                color: #757575;
            }
            .sb-module-taxonomy-item:hover:not(.added) svg {
                color: var(--primary-500, #3b82f6);
            }
            .sb-module-taxonomy-item span:first-of-type {
                flex: 1;
            }
            .sb-module-taxonomy-added {
                font-size: 10px;
                color: #757575;
                background: #e0e0e0;
                padding: 2px 6px;
                border-radius: 3px;
                text-transform: uppercase;
            }
            .sb-module-empty-text {
                color: #757575;
                font-size: 13px;
                margin: 0;
                padding: 8px 0;
            }
            .sb-module-loading {
                color: #757575;
                font-size: 13px;
            }
        </style>
        <div class="wrap sb-module-wrap">
            <!-- Header -->
            <div class="sb-module-header">
                <div class="sb-module-header-left">
                    <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 0a2 2 0 012 2v8a2 2 0 01-2 2m-6 0a2 2 0 002 2h2a2 2 0 002-2"></path>
                    </svg>
                    <div>
                        <h1 class="sb-module-title">
                            <?php esc_html_e('Admin Columns Manager', 'wpswitchboard'); ?>
                            <span class="switchboard-badge">SWITCHBOARD</span>
                        </h1>
                        <p class="sb-module-subtitle"><?php esc_html_e('Customize and manage admin list table columns for all post types with drag-and-drop interface', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-header-right">
                    <a href="https://docs.wpswitchboard.com/modules/admin/admin-columns-manager" target="_blank" class="sb-module-help-link">
                        <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                        <?php esc_html_e('Help', 'wpswitchboard'); ?>
                    </a>
                </div>
            </div>

            <!-- Main Content -->
            <div class="sb-module-container">
                <div class="sb-module-layout-3col">
                    <!-- Left Column: Post Types -->
                    <div class="sb-module-post-types-sidebar">
                        <div class="sb-module-card">
                            <div class="sb-module-card-header">
                                <h2 class="sb-module-card-title"><?php esc_html_e('Post Types', 'wpswitchboard'); ?></h2>
                            </div>
                            <div class="sb-module-card-body">
                                <div id="scm-post-types-list">
                                    <?php
                                    // Get all post types that have an admin UI
                                    $all_post_types = get_post_types([], 'objects');
                                    $post_types = [];

                                    // List of internal/system post types to exclude
                                    $excluded_types = [
                                        'attachment', 'nav_menu_item', 'revision', 'custom_css', 'customize_changeset',
                                        'oembed_cache', 'user_request', 'wp_block', 'wp_template', 'wp_template_part',
                                        'wp_global_styles', 'wp_navigation', 'acf-field-group', 'acf-field', 'acf-post-type',
                                        'acf-taxonomy', 'acf-ui-options-page', 'wpcf7_contact_form', 'flamingo_inbound',
                                        'flamingo_outbound', 'flamingo_contact', 'wpseo_locations', 'yst_prominent_words',
                                        'schema-template', 'rank_math_schema', 'aioseo-redirects', 'custom-fonts',
                                        'astra-advanced-hook', 'elementor_library', 'e-landing-page',
                                    ];

                                    foreach ($all_post_types as $pt) {
                                        if (in_array($pt->name, $excluded_types)) continue;
                                        if ($pt->show_ui && ($pt->public || $pt->publicly_queryable)) {
                                            $post_types[$pt->name] = $pt;
                                        }
                                    }

                                    $first_post_type = !empty($post_types) ? array_key_first($post_types) : 'post';
                                    foreach ($post_types as $pt): ?>
                                        <button type="button"
                                                class="sb-module-post-type-item <?php echo ($pt->name === $first_post_type) ? 'active' : ''; ?>"
                                                data-post-type="<?php echo esc_attr($pt->name); ?>">
                                            <?php echo esc_html($pt->label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                                <input type="hidden" id="scm-post-type-select" value="<?php echo esc_attr($first_post_type); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Middle Column: Columns Management -->
                    <div class="sb-module-columns-main">
                        <div class="sb-module-card">
                            <div class="sb-module-card-header">
                                <div class="sb-module-card-header-left">
                                    <h2 class="sb-module-card-title"><?php esc_html_e('Manage Columns', 'wpswitchboard'); ?></h2>
                                    <p class="sb-module-card-desc"><?php esc_html_e('Drag to reorder, toggle to enable/disable, or click to configure advanced options', 'wpswitchboard'); ?></p>
                                </div>
                                <div class="sb-module-card-header-right">
                                    <a href="https://docs.wpswitchboard.com/modules/admin/admin-columns-manager" target="_blank" class="sb-module-help-link">
                                        <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                                        Help
                                    </a>
                                    <button type="button" id="scm-add-custom-column" class="sb-module-button sb-module-button-primary">
                                        <?php esc_html_e('Add Column', 'wpswitchboard'); ?>
                                    </button>
                                </div>
                            </div>
                            <div class="sb-module-card-body">
                                <div id="scm-columns-list" class="sb-module-columns-list">
                                    <div class="sb-module-loading">
                                        <div class="sb-module-spinner"></div>
                                        <p><?php esc_html_e('Loading columns...', 'wpswitchboard'); ?></p>
                                    </div>
                                </div>
                            </div>
                            <div class="sb-module-card-footer">
                                <div id="scm-save-indicator" class="sb-module-save-indicator">
                                    <svg fill="currentColor" viewBox="0 0 16 16"><path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z"/></svg>
                                    <span><?php esc_html_e('Saved', 'wpswitchboard'); ?></span>
                                </div>
                                <div class="sb-module-button-group" style="margin-left: auto;">
                                    <button type="button" id="scm-reset-columns" class="sb-module-button sb-module-button-secondary">
                                        <?php esc_html_e('Reset', 'wpswitchboard'); ?>
                                    </button>
                                    <button type="button" id="scm-save-columns" class="sb-module-button sb-module-button-primary">
                                        <?php esc_html_e('Save', 'wpswitchboard'); ?>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column: Quick Add -->
                    <div class="sb-module-quick-add-sidebar">
                        <div class="sb-module-card">
                            <div class="sb-module-card-header">
                                <h2 class="sb-module-card-title"><?php esc_html_e('Quick Add', 'wpswitchboard'); ?></h2>
                            </div>
                            <div class="sb-module-card-body">
                                <div class="sb-module-quick-add-grid">
                                    <button type="button" class="sb-module-quick-add-btn" data-type="id">
                                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path></svg>
                                        <span><?php esc_html_e('ID', 'wpswitchboard'); ?></span>
                                    </button>
                                    <button type="button" class="sb-module-quick-add-btn" data-type="modified">
                                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        <span><?php esc_html_e('Last Modified', 'wpswitchboard'); ?></span>
                                    </button>
                                    <button type="button" class="sb-module-quick-add-btn" data-type="thumbnail">
                                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                        <span><?php esc_html_e('Featured Image', 'wpswitchboard'); ?></span>
                                    </button>
                                    <button type="button" class="sb-module-quick-add-btn" data-type="word_count">
                                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                                        <span><?php esc_html_e('Word Count', 'wpswitchboard'); ?></span>
                                    </button>
                                    <button type="button" class="sb-module-quick-add-btn" data-type="slug">
                                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path></svg>
                                        <span><?php esc_html_e('Slug', 'wpswitchboard'); ?></span>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Taxonomies Section -->
                        <div class="sb-module-card" style="margin-top: 16px;">
                            <div class="sb-module-card-header">
                                <h2 class="sb-module-card-title"><?php esc_html_e('Taxonomies', 'wpswitchboard'); ?></h2>
                            </div>
                            <div class="sb-module-card-body">
                                <div id="scm-taxonomies-list" class="sb-module-taxonomy-list">
                                    <p class="sb-module-loading"><?php esc_html_e('Loading taxonomies...', 'wpswitchboard'); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Toast Notification -->
            <div id="scm-toast" class="sb-module-toast">
                <div class="sb-module-toast-content">
                    <svg class="sb-module-toast-icon" fill="currentColor" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/><path d="M10.97 4.97a.235.235 0 0 0-.02.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05z"/></svg>
                    <span class="sb-module-toast-message"></span>
                </div>
            </div>
        </div>

        <?php $this->render_admin_page_scripts(); ?>
        <?php
    }


    /**
     * Render scripts for the admin page
     */
    private function render_admin_page_scripts() {
        // Localize strings for JavaScript
        $i18n = [
            'lastModified' => __('Last Modified', 'wpswitchboard'),
            'featuredImage' => __('Featured Image', 'wpswitchboard'),
            'wordCount' => __('Word Count', 'wpswitchboard'),
            'slug' => __('Slug', 'wpswitchboard'),
            'id' => __('ID', 'wpswitchboard'),
            'newColumn' => __('New Column', 'wpswitchboard'),
            'customMeta' => __('Custom Meta', 'wpswitchboard'),
            'builtIn' => __('Built-in', 'wpswitchboard'),
            'sortable' => __('Sortable', 'wpswitchboard'),
            'delete' => __('Delete', 'wpswitchboard'),
            'label' => __('Label', 'wpswitchboard'),
            'metaKey' => __('Meta Key', 'wpswitchboard'),
            'width' => __('Width', 'wpswitchboard'),
            'cssClass' => __('CSS Class', 'wpswitchboard'),
            'makeSortable' => __('Make this column sortable', 'wpswitchboard'),
            'forceWidth' => __('Force width (override table layout)', 'wpswitchboard'),
            'columnExists' => __('This column already exists!', 'wpswitchboard'),
            'deleteConfirm' => __('Are you sure you want to delete this column?', 'wpswitchboard'),
            'resetConfirm' => __('Reset all columns to defaults? This will remove all custom configurations.', 'wpswitchboard'),
            'leaveEmptyBuiltIn' => __('Leave empty for built-in', 'wpswitchboard'),
            'egWidth' => __('e.g. 150px', 'wpswitchboard'),
            'saved' => __('Changes saved successfully!', 'wpswitchboard'),
        ];
        ?>
        <script>
        jQuery(document).ready(function($) {
            const i18n = <?php echo wp_json_encode($i18n); ?>;
            let columns = [];
            let currentPostType = 'post';
            let draggedElement = null;
            let saveTimeout = null;
            let availableMetaKeys = [];
            let dragListenersAttached = false;

            // Load available meta keys for the post type
            function loadMetaKeys(postType) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'get_custom_fields',
                        post_type: postType,
                        nonce: '<?php echo wp_create_nonce('switchboard_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success && response.data.fields) {
                            availableMetaKeys = response.data.fields;
                        } else {
                            availableMetaKeys = [];
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Failed to load meta keys:', status, error);
                        availableMetaKeys = [];
                    }
                });
            }

            // Load available taxonomies for the post type
            function loadTaxonomies(postType) {
                $('#scm-taxonomies-list').html('<p class="sb-module-loading"><?php echo esc_js(__('Loading taxonomies...', 'wpswitchboard')); ?></p>');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'get_post_type_taxonomies',
                        post_type: postType,
                        nonce: '<?php echo wp_create_nonce('switchboard_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success && response.data.taxonomies) {
                            renderTaxonomies(response.data.taxonomies);
                        } else {
                            $('#scm-taxonomies-list').html('<p class="sb-module-empty-text"><?php echo esc_js(__('No taxonomies found.', 'wpswitchboard')); ?></p>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Failed to load taxonomies:', status, error);
                        $('#scm-taxonomies-list').html('<p class="sb-module-empty-text"><?php echo esc_js(__('Failed to load taxonomies.', 'wpswitchboard')); ?></p>');
                    }
                });
            }

            // Render taxonomies list
            function renderTaxonomies(taxonomies) {
                if (!taxonomies || taxonomies.length === 0) {
                    $('#scm-taxonomies-list').html('<p class="sb-module-empty-text"><?php echo esc_js(__('No taxonomies found for this post type.', 'wpswitchboard')); ?></p>');
                    return;
                }

                let html = '<div class="sb-module-taxonomy-items">';
                taxonomies.forEach(function(tax) {
                    const isAlreadyAdded = columns.some(col => col.id === tax.column_id);
                    html += `
                        <button type="button" class="sb-module-taxonomy-item${isAlreadyAdded ? ' added' : ''}"
                                data-column-id="${tax.column_id}"
                                data-label="${tax.label}"
                                ${isAlreadyAdded ? 'disabled' : ''}>
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="16" height="16">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                            </svg>
                            <span>${tax.label}</span>
                            ${isAlreadyAdded ? '<span class="sb-module-taxonomy-added"><?php echo esc_js(__('Added', 'wpswitchboard')); ?></span>' : ''}
                        </button>
                    `;
                });
                html += '</div>';
                $('#scm-taxonomies-list').html(html);
            }

            // Handle taxonomy item click
            $(document).on('click', '.sb-module-taxonomy-item:not(.added):not([disabled])', function() {
                const columnId = $(this).data('column-id');
                const label = $(this).data('label');

                // Check if already exists
                if (columns.some(col => col.id === columnId)) {
                    showToast(i18n.columnExists, 'error');
                    return;
                }

                // Add new taxonomy column
                const newCol = {
                    id: columnId,
                    label: label, // Use taxonomy label as default, user can customize
                    enabled: true,
                    meta_key: '',
                    class: '',
                    width: 'auto',
                    force_width: false,
                    html_before: '',
                    html_after: '',
                    sortable: false
                };

                columns.push(newCol);
                renderColumns();
                saveColumns();

                // Mark as added
                $(this).addClass('added').attr('disabled', true);
                $(this).append('<span class="sb-module-taxonomy-added"><?php echo esc_js(__('Added', 'wpswitchboard')); ?></span>');
            });

            // Load columns for current post type
            function loadColumns(postType) {
                currentPostType = postType;
                loadMetaKeys(postType);

                $('#scm-columns-list').html('<div class="sb-module-loading"><div class="sb-module-spinner"></div><p>Loading columns...</p></div>');
                $('#scm-taxonomies-list').html('<p class="sb-module-loading"><?php echo esc_js(__('Loading taxonomies...', 'wpswitchboard')); ?></p>');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'get_post_type_columns',
                        post_type: postType,
                        nonce: '<?php echo wp_create_nonce('switchboard_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            const responseColumns = response.data.columns || {};
                            let columnsArray = Array.isArray(responseColumns) ? responseColumns : Object.values(responseColumns);

                            columns = columnsArray.map(col => ({
                                id: col.id || '',
                                label: col.label || col.id || '',
                                enabled: col.enabled !== undefined ? col.enabled : true,
                                meta_key: col.meta_key || '',
                                class: col.class || '',
                                width: col.width || '',
                                force_width: col.force_width || false,
                                html_before: col.html_before || '',
                                html_after: col.html_after || '',
                                sortable: col.sortable || false
                            }));

                            renderColumns();
                            // Load taxonomies AFTER columns are set so "Added" state is accurate
                            loadTaxonomies(postType);
                        } else {
                            // Handle error response
                            const errorMsg = response.data || 'Failed to load columns';
                            console.error('Error loading columns:', errorMsg);
                            showToast(errorMsg, 'error');
                            columns = [];
                            renderColumns();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX error loading columns:', status, error, xhr.responseText);
                        showToast('Error loading columns. Please refresh the page.', 'error');
                        $('#scm-columns-list').html('<div class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-title">Error Loading Columns</p><p class="sb-module-empty-desc">An error occurred while loading columns. Please refresh the page and try again.</p></div>');
                    }
                });
            }

            // Post type change - handle both select and button clicks
            $('#scm-post-type-select').on('change', function() {
                loadColumns($(this).val());
                updateActivePostType($(this).val());
            });

            // Post type button clicks
            $('.sb-module-post-type-item').on('click', function() {
                const postType = $(this).data('post-type');
                $('#scm-post-type-select').val(postType);
                loadColumns(postType);
                updateActivePostType(postType);
            });

            // Update active post type button
            function updateActivePostType(postType) {
                $('.sb-module-post-type-item').removeClass('active');
                $('.sb-module-post-type-item[data-post-type="' + postType + '"]').addClass('active');
            }

            // Initial load
            const initialPostType = $('#scm-post-type-select').val() || 'post';
            loadColumns(initialPostType);

            // Render columns
            function renderColumns() {
                const $list = $('#scm-columns-list');

                if (columns.length === 0) {
                    $list.html('<div class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-title">No columns configured</p><p class="sb-module-empty-desc">Click "Quick Add" or "Add Custom Column" to get started</p></div>');
                    return;
                }

                let html = '';
                columns.forEach((col, index) => {
                    const isOpen = false;
                    html += '<div class="sb-module-column-item" data-index="' + index + '" draggable="false">';
                    html += '<div class="sb-module-column-header">';
                    html += '<span class="sb-module-drag-handle" draggable="true" style="cursor: grab;">⋮⋮</span>';
                    html += '<svg class="' + (isOpen ? 'open' : '') + '" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>';
                    html += '<label class="sb-module-toggle"><input type="checkbox" class="col-enabled" data-index="' + index + '" ' + (col.enabled ? 'checked' : '') + '><span class="sb-module-toggle-slider"></span></label>';
                    html += '<div class="sb-module-column-info">';
                    html += '<div class="sb-module-column-name">' + escapeHtml(col.label || col.id) + '</div>';
                    html += '<div class="sb-module-column-id">' + escapeHtml(col.id) + '</div>';
                    html += '</div>';
                    html += '<div class="sb-module-column-meta">';
                    html += '<span class="sb-module-badge sb-module-badge-secondary' + (col.meta_key ? '' : '') + '">' + (col.meta_key ? i18n.customMeta : i18n.builtIn) + '</span>';
                    if (col.sortable) html += '<span class="sb-module-badge sb-module-badge-secondary">' + i18n.sortable + '</span>';
                    if (col.width) html += '<span class="sb-module-badge sb-module-badge-secondary">' + escapeHtml(col.width) + (col.force_width ? ' (forced)' : '') + '</span>';
                    html += '</div>';
                    html += '<div class="sb-module-column-actions">';

                    const isQuickAdd = ['modified', 'thumbnail', 'post_id', 'word_count', 'slug'].includes(col.id);
                    const isCustom = col.meta_key || col.id.startsWith('custom_');
                    const isTaxonomy = col.id.startsWith('taxonomy-');
                    if (isCustom || isQuickAdd || isTaxonomy) {
                        html += '<button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm" data-index="' + index + '">' + i18n.delete + '</button>';
                    }
                    html += '</div></div>';
                    html += '<div class="sb-module-column-advanced' + (isOpen ? ' open' : '') + '">';
                    html += '<div class="sb-module-advanced-grid">';
                    html += '<div class="sb-module-field"><label>' + i18n.label + '</label><input type="text" class="col-label" data-index="' + index + '" value="' + escapeHtml(col.label || '') + '"></div>';

                    // Meta Key field with dropdown - only show for non-taxonomy columns
                    const isTaxonomyColumn = col.id.startsWith('taxonomy-');
                    if (!isTaxonomyColumn) {
                        html += '<div class="sb-module-field"><label>' + i18n.metaKey + '</label>';
                        html += '<select class="col-meta-key" data-index="' + index + '" class="sb-module-select">';
                        html += '<option value="">' + i18n.leaveEmptyBuiltIn + '</option>';
                        availableMetaKeys.forEach(function(metaKey) {
                            const selected = col.meta_key === metaKey ? ' selected' : '';
                            html += '<option value="' + escapeHtml(metaKey) + '"' + selected + '>' + escapeHtml(metaKey) + '</option>';
                        });
                        html += '</select></div>';
                    }

                    html += '<div class="sb-module-field"><label>' + i18n.width + '</label><input type="text" class="col-width" data-index="' + index + '" value="' + escapeHtml(col.width || '') + '" placeholder="' + i18n.egWidth + '"></div>';
                    html += '<div class="sb-module-field"><label>' + i18n.cssClass + ' <small style="color: #64748b; font-weight: 400;">(no dot)</small></label><input type="text" class="col-class" data-index="' + index + '" value="' + escapeHtml(col.class || '') + '" placeholder="e.g. text-center font-bold"></div>';
                    html += '</div>';
                    html += '<div class="sb-module-checkbox-grid" style="grid-template-columns: repeat(2, 1fr); margin-top: 8px;">';
                    html += '<label class="sb-module-checkbox-item"><input type="checkbox" class="col-force-width" data-index="' + index + '" ' + (col.force_width ? 'checked' : '') + '><span>' + i18n.forceWidth + '</span></label>';
                    html += '<label class="sb-module-checkbox-item"><input type="checkbox" class="col-sortable" data-index="' + index + '" ' + (col.sortable ? 'checked' : '') + '><span>' + i18n.makeSortable + '</span></label>';
                    html += '</div>';
                    html += '</div></div>';
                });

                $list.html(html);
                attachEvents();
            }

            // Attach events
            function attachEvents() {
                $('.sb-module-column-header').off('click').on('click', function(e) {
                    if ($(e.target).closest('.sb-module-toggle, .sb-module-column-actions').length) return;
                    const $advanced = $(this).next('.sb-module-column-advanced');
                    const $chevron = $(this).find('svg');
                    $advanced.toggleClass('open');
                    $chevron.toggleClass('open');
                });

                $('.col-enabled').on('change', function() {
                    const index = $(this).data('index');
                    columns[index].enabled = $(this).is(':checked');
                    saveColumns();
                });

                $('.col-label, .col-width, .col-class').on('input', function() {
                    const index = $(this).data('index');
                    const field = $(this).attr('class').replace('col-', '').replace(/-/g, '_');
                    columns[index][field] = $(this).val();

                    if (field === 'label') {
                        $(this).closest('.sb-module-column-item').find('.sb-module-column-name').text($(this).val() || columns[index].id);
                    }

                    saveColumns();
                });

                $('.col-meta-key').on('change', function() {
                    const index = $(this).data('index');
                    columns[index].meta_key = $(this).val();
                    saveColumns();
                });

                $('.col-sortable').on('change', function() {
                    const index = $(this).data('index');
                    columns[index].sortable = $(this).is(':checked');
                    saveColumns();
                });

                $('.col-force-width').on('change', function() {
                    const index = $(this).data('index');
                    columns[index].force_width = $(this).is(':checked');
                    saveColumns();
                });

                // Drag and drop
                const columnsList = document.querySelector('#scm-columns-list');
                if (columnsList) {
                    const items = columnsList.querySelectorAll('.sb-module-column-item');
                    const handles = columnsList.querySelectorAll('.sb-module-drag-handle');

                    // Attach dragstart and dragend to handles only
                    handles.forEach((handle) => {
                        handle.removeEventListener('dragstart', handleDragStart);
                        handle.removeEventListener('dragend', handleDragEnd);

                        handle.addEventListener('dragstart', handleDragStart);
                        handle.addEventListener('dragend', handleDragEnd);
                    });

                    // Attach dragover, dragleave, and drop to items
                    items.forEach((item) => {
                        item.removeEventListener('dragover', handleDragOver);
                        item.removeEventListener('dragleave', handleDragLeave);
                        item.removeEventListener('drop', handleDrop);

                        item.addEventListener('dragover', handleDragOver);
                        item.addEventListener('dragleave', handleDragLeave);
                        item.addEventListener('drop', handleDrop);
                    });
                }

                // Delete button
                $('.sb-module-button-danger[data-index]').on('click', function(e) {
                    e.stopPropagation();
                    const index = $(this).data('index');
                    if (confirm(i18n.deleteConfirm)) {
                        columns.splice(index, 1);
                        renderColumns();
                        saveColumns();
                        // Refresh taxonomies to update "Added" state
                        loadTaxonomies(currentPostType);
                    }
                });
            }

            // Quick add buttons
            $('.sb-module-quick-add-btn').on('click', function() {
                const type = $(this).data('type');
                const quickAddConfigs = {
                    modified: {
                        id: 'modified',
                        label: i18n.lastModified,
                        enabled: true,
                        meta_key: '',
                        class: '',
                        width: '150px',
                        html_before: '',
                        html_after: '',
                        sortable: true
                    },
                    thumbnail: {
                        id: 'thumbnail',
                        label: i18n.featuredImage,
                        enabled: true,
                        meta_key: '',
                        class: '',
                        width: '80px',
                        html_before: '',
                        html_after: '',
                        sortable: false
                    },
                    id: {
                        id: 'post_id',
                        label: i18n.id,
                        enabled: true,
                        meta_key: '',
                        class: '',
                        width: '60px',
                        html_before: '',
                        html_after: '',
                        sortable: true
                    },
                    word_count: {
                        id: 'word_count',
                        label: i18n.wordCount,
                        enabled: true,
                        meta_key: '',
                        class: '',
                        width: '100px',
                        html_before: '',
                        html_after: '',
                        sortable: true
                    },
                    slug: {
                        id: 'slug',
                        label: i18n.slug,
                        enabled: true,
                        meta_key: '',
                        class: '',
                        width: '200px',
                        html_before: '',
                        html_after: '',
                        sortable: false
                    }
                };

                // Check if column already exists
                const existingCol = columns.find(c => c.id === quickAddConfigs[type].id);
                if (existingCol) {
                    // If it exists but is disabled, enable it instead
                    if (!existingCol.enabled) {
                        existingCol.enabled = true;
                        renderColumns();
                        saveColumns();
                        showToast('Column enabled', 'success');
                    } else {
                        showToast(i18n.columnExists, 'warning');
                    }
                    return;
                }

                // Add new column
                const newCol = {
                    ...quickAddConfigs[type],
                    order: columns.length
                };

                columns.push(newCol);
                renderColumns();
                saveColumns();
                showToast('Column added: ' + newCol.label, 'success');
            });

            // Add custom column
            $('#scm-add-custom-column').on('click', function() {
                const newCol = {
                    id: 'custom_' + Date.now(),
                    label: i18n.newColumn,
                    enabled: true,
                    meta_key: '',
                    class: '',
                    width: '',
                    html_before: '',
                    html_after: '',
                    sortable: false,
                    order: columns.length
                };

                columns.push(newCol);
                renderColumns();
                saveColumns();
                showToast('Custom column added', 'success');

                // Scroll to the new column
                setTimeout(function() {
                    const $lastColumn = $('.sb-module-column-item').last();
                    if ($lastColumn.length) {
                        $lastColumn[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                        // Open the advanced panel
                        $lastColumn.find('.sb-module-column-header').click();
                    }
                }, 100);
            });

            // Reset columns
            $('#scm-reset-columns').on('click', function() {
                if (confirm(i18n.resetConfirm)) {
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'save_column_config',
                            post_type: currentPostType,
                            columns: JSON.stringify([]),
                            nonce: '<?php echo wp_create_nonce('switchboard_nonce'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                loadColumns(currentPostType);
                                showToast(i18n.saved);
                            }
                        }
                    });
                }
            });

            // Drag handlers
            function handleDragStart(e) {
                // Stop event from bubbling
                e.stopPropagation();

                // Get the parent item using parentElement navigation for precision
                let item = this.parentElement; // Gets .sb-module-column-header
                if (item) {
                    item = item.parentElement; // Gets .sb-module-column-item
                }

                if (!item || !item.classList.contains('sb-module-column-item')) {
                    return false;
                }

                // Prevent multiple drag starts
                if (draggedElement) {
                    return false;
                }

                // Clear any existing dragging classes first
                document.querySelectorAll('.sb-module-column-item.dragging').forEach(el => {
                    el.classList.remove('dragging');
                });

                draggedElement = item;
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData('text/plain', item.dataset.index);

                // Create a clean clone for the drag image to avoid capturing underlying elements
                const dragImage = item.cloneNode(true);
                dragImage.style.position = 'absolute';
                dragImage.style.top = '-9999px';
                dragImage.style.left = '-9999px';
                dragImage.style.width = item.offsetWidth + 'px';
                dragImage.style.opacity = '0.8';
                dragImage.style.pointerEvents = 'none';
                document.body.appendChild(dragImage);

                // Set the cloned element as drag image
                e.dataTransfer.setDragImage(dragImage, 20, 20);

                // Remove the clone after a short delay
                setTimeout(() => {
                    if (dragImage && dragImage.parentNode) {
                        dragImage.parentNode.removeChild(dragImage);
                    }
                }, 0);

                // Add visual feedback class to the original item
                setTimeout(() => {
                    if (draggedElement === item) {
                        item.classList.add('dragging');
                    }
                }, 0);
            }

            function handleDragOver(e) {
                if (e.preventDefault) {
                    e.preventDefault();
                }

                e.dataTransfer.dropEffect = 'move';

                // Add drop zone visual feedback
                if (draggedElement && draggedElement !== this) {
                    // Remove previous indicators
                    document.querySelectorAll('.sb-module-column-item').forEach(item => {
                        item.classList.remove('drag-over');
                    });

                    // Add indicator to current target
                    this.classList.add('drag-over');
                }

                return false;
            }

            function handleDrop(e) {
                e.preventDefault();
                e.stopPropagation();

                // Remove all drag-over indicators
                document.querySelectorAll('.sb-module-column-item').forEach(item => {
                    item.classList.remove('drag-over');
                });

                if (draggedElement && draggedElement !== this) {
                    const draggedIndex = parseInt(draggedElement.dataset.index);
                    const targetIndex = parseInt(this.dataset.index);

                    // Reorder columns array
                    const temp = columns[draggedIndex];
                    columns.splice(draggedIndex, 1);
                    columns.splice(targetIndex, 0, temp);

                    // Use a flag to defer the render until after dragEnd
                    window.needsRerender = true;
                }

                return false;
            }

            function handleDragEnd(e) {
                e.stopPropagation();

                // Clean up ALL items (remove any stray classes)
                document.querySelectorAll('.sb-module-column-item').forEach(item => {
                    item.classList.remove('drag-over', 'dragging');
                });

                // Clear the dragged element reference
                draggedElement = null;

                // Now that drag is complete, re-render if needed
                if (window.needsRerender) {
                    window.needsRerender = false;
                    renderColumns();
                    saveColumns();
                }
            }

            // Add drag leave handler to remove hover state
            function handleDragLeave(e) {
                this.classList.remove('drag-over');
            }

            // Save columns function (can be called manually or auto-save)
            function saveColumns(manualSave = false) {
                if (!manualSave) {
                    // Auto-save with debounce
                    clearTimeout(saveTimeout);
                    saveTimeout = setTimeout(function() {
                        performSave(true); // true = auto-save
                    }, 1000);
                } else {
                    // Manual save - immediate
                    performSave(false); // false = manual save
                }
            }

            // Perform the actual save
            function performSave(isAutoSave = false) {
                // Validate columns before saving
                if (!Array.isArray(columns)) {
                    console.error('Invalid columns data structure');
                    if (!isAutoSave) {
                        showToast('Invalid data structure. Please refresh the page.', 'error');
                    }
                    return;
                }

                const $saveBtn = $('#scm-save-columns');
                const originalText = $saveBtn.html();

                // Update button state for manual saves
                if (!isAutoSave) {
                    $saveBtn.prop('disabled', true).html(
                        '<svg class="sb-module-spinner" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" stroke-width="4" opacity="0.25"/><path d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" fill="currentColor"/></svg> ' + 'Saving...'
                    );
                }

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'save_column_config',
                        post_type: currentPostType,
                        columns: JSON.stringify(columns),
                        nonce: '<?php echo wp_create_nonce('switchboard_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            // Show save indicator for both auto-save and manual save
                            $('#scm-save-indicator').addClass('show');
                            setTimeout(function() {
                                $('#scm-save-indicator').removeClass('show');
                            }, 2000);

                            if (!isAutoSave) {
                                // Only show toast for manual saves
                                showToast(i18n.saved, 'success');
                            }
                            // For auto-saves, the save indicator is enough feedback
                        } else {
                            // Show error message from server
                            const errorMsg = response.data || 'Failed to save configuration';
                            showToast(errorMsg, 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX error:', status, error, xhr.responseText);
                        showToast('Error saving configuration: ' + error, 'error');
                    },
                    complete: function() {
                        // Restore button state for manual saves
                        if (!isAutoSave) {
                            $saveBtn.prop('disabled', false).html(originalText);
                        }
                    }
                });
            }

            // Manual save button
            $('#scm-save-columns').on('click', function() {
                saveColumns(true);
            });

            // Show toast notification
            function showToast(message, type = 'success') {
                const $toast = $('#scm-toast');

                if (!$toast.length) {
                    console.error('Toast element not found');
                    return;
                }

                const $message = $toast.find('.sb-module-toast-message');
                const $icon = $toast.find('.sb-module-toast-icon');

                if (!$message.length || !$icon.length) {
                    console.error('Toast message or icon element not found');
                    return;
                }

                $message.text(message);

                // Remove all type classes
                $toast.removeClass('sb-module-toast-success sb-module-toast-error sb-module-toast-warning sb-module-toast-info sb-module-toast-auto-saved');

                // Update icon and styling based on type
                if (type === 'auto-saved') {
                    $icon.html('<path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z"/>');
                    $toast.addClass('sb-module-toast-auto-saved');
                } else if (type === 'error') {
                    $icon.html('<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/><path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z"/>');
                    $toast.addClass('sb-module-toast-error');
                } else if (type === 'warning') {
                    $icon.html('<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>');
                    $toast.addClass('sb-module-toast-warning');
                } else {
                    // Success icon (default)
                    $icon.html('<path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z"/>');
                    $toast.addClass('sb-module-toast-success');
                }

                // Show toast with animation
                $toast.addClass('show');

                // Auto-hide after delay
                const hideDelay = type === 'auto-saved' ? 2000 : 3000;
                setTimeout(function() {
                    $toast.removeClass('show');
                }, hideDelay);
            }

            // Escape HTML
            function escapeHtml(text) {
                if (text === null || text === undefined) return '';
                text = String(text);
                const map = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                };
                return text.replace(/[&<>"']/g, m => map[m]);
            }
        });
        </script>
        <?php
    }

    /**
     * Admin Columns Manager has no settings panel - uses dedicated page only
     * All management happens on dedicated page: admin.php?page=admin-columns-manager
     */

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_admin-columns-manager_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

// Create instance and make it globally accessible for settings renderer
global $SwitchboardAdminColumnsManager;
$SwitchboardAdminColumnsManager = new SwitchboardAdminColumnsManager();
Switchboard_Data_Registry::get_instance()->auto_register($SwitchboardAdminColumnsManager, __FILE__);
