<?php
/**
 * Name: Social Share Buttons
 * Description: Add social media share buttons for Facebook, Twitter, LinkedIn, and other platforms with Web Share API support for mobile native sharing experience
 * Category: Content
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Increase Content Reach",
 *     "description": "Make it easy for visitors to share your content on social media platforms, expanding your audience organically."
 *   },
 *   {
 *     "title": "Lightweight Solution",
 *     "description": "Add social sharing without heavy third-party scripts that slow down your site or track your users."
 *   }
 * ]
 * Added: 2025-07-08
 * Tags: social, share, buttons, facebook, x, twitter, linkedin, web-share
 * WhereToFind: {
 *   "location": "Frontend (Posts with Shortcode)",
 *   "url": "/",
 *   "instructions": "Add [social_share] shortcode to display share buttons",
 *   "newTab": true
 * }
 */

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

class SwitchboardSocialShareButtons {
    
    public function __construct() {
        add_filter('the_content', [$this, 'add_share_buttons']);
        add_shortcode('social_share', [$this, 'share_buttons_shortcode']);
        add_action('wp_footer', [$this, 'add_web_share_script']);
        
        // Register with data registry
        $this->register_with_data_registry();
    }
    
    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_social-share-buttons_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    private function get_settings() {
        return get_option('switchboard_social-share-buttons_settings', []);
    }
    
    public function add_share_buttons($content) {
        if (!is_singular()) {
            return $content;
        }
        
        $settings = $this->get_settings();
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : 'yes';
        
        if ($auto_display !== 'yes') {
            return $content;
        }
        
        $post_types = isset($settings['post_types']) ? array_map('trim', explode(',', $settings['post_types'])) : ['post'];
        $position = isset($settings['position']) ? $settings['position'] : 'after';
        
        if (!in_array(get_post_type(), $post_types)) {
            return $content;
        }
        
        $buttons = $this->generate_share_buttons();
        
        if ($position === 'before') {
            return $buttons . $content;
        } elseif ($position === 'both') {
            return $buttons . $content . $buttons;
        }
        
        return $content . $buttons;
    }
    
    public function share_buttons_shortcode($atts) {
        $atts = shortcode_atts([
            'platforms' => null
        ], $atts);
        
        return $this->generate_share_buttons($atts['platforms']);
    }
    
    private function generate_share_buttons($custom_platforms = null) {
        global $post;

        if (!$post) {
            return '';
        }

        $settings = $this->get_settings();
        $web_share_enabled = isset($settings['web_share_api']) ? $settings['web_share_api'] : 'yes';

        $platforms_setting = $custom_platforms ? $custom_platforms : (isset($settings['platforms']) ? $settings['platforms'] : 'facebook,x,linkedin,email');
        $enabled_platforms = array_map('trim', explode(',', $platforms_setting));

        $post_url = get_permalink();
        $post_title = get_the_title();
        $post_url_encoded = urlencode($post_url);
        $post_title_encoded = urlencode($post_title);
        
        $all_platforms = [
            'facebook' => [
                'url' => 'https://www.facebook.com/sharer/sharer.php?u=' . $post_url_encoded,
                'label' => 'Facebook',
                'color' => '#1877f2',
                'icon' => '<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>'
            ],
            'x' => [
                'url' => 'https://x.com/intent/tweet?url=' . $post_url_encoded . '&text=' . $post_title_encoded,
                'label' => 'X',
                'color' => '#000000',
                'icon' => '<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>'
            ],
            'linkedin' => [
                'url' => 'https://www.linkedin.com/shareArticle?mini=true&url=' . $post_url_encoded . '&title=' . $post_title_encoded,
                'label' => 'LinkedIn',
                'color' => '#0077b5',
                'icon' => '<path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>'
            ],
            'whatsapp' => [
                'url' => 'https://wa.me/?text=' . $post_title_encoded . '%20' . $post_url_encoded,
                'label' => 'WhatsApp',
                'color' => '#25d366',
                'icon' => '<path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>'
            ],
            'reddit' => [
                'url' => 'https://reddit.com/submit?url=' . $post_url_encoded . '&title=' . $post_title_encoded,
                'label' => 'Reddit',
                'color' => '#ff4500',
                'icon' => '<path d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z"/>'
            ],
            'email' => [
                'url' => 'mailto:?subject=' . $post_title_encoded . '&body=' . $post_url_encoded,
                'label' => 'Email',
                'color' => '#666',
                'icon' => '<path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/>'
            ]
        ];
        
        ob_start();
        ?>
        <style>
        .switchboard-share-override * {
            box-sizing: border-box !important;
        }
        .switchboard-share-override .sb-link-override,
        .switchboard-share-override .sb-btn-override {
            display: inline-flex !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
            float: none !important;
            clear: none !important;
            width: auto !important;
            height: auto !important;
            max-width: none !important;
            min-width: 0 !important;
        }
        .switchboard-share-override .sb-link-override:hover {
            opacity: 0.85 !important;
        }
        </style>
        <div class="switchboard-social-share switchboard-share-override" style="margin: 30px 0 !important; padding: 20px !important; background: #f8f9fa !important; border-radius: 8px !important; border: 1px solid #e9ecef !important; clear: both !important;">
            <h4 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #111827;"><?php esc_html_e('Share this:', 'wpswitchboard'); ?></h4>
            <div class="sb-share-btns-wrapper" style="display: flex; gap: 8px; flex-wrap: wrap;">
                <?php if ($web_share_enabled === 'yes'): ?>
                <button class="switchboard-web-share-btn sb-btn-override"
                        data-url="<?php echo esc_attr($post_url); ?>"
                        data-title="<?php echo esc_attr($post_title); ?>"
                        style="display: none !important; align-items: center !important; gap: 8px !important; padding: 10px 16px !important; background: #2271b1 !important; color: white !important; border: none !important; border-radius: 4px !important; font-size: 14px !important; font-weight: 500 !important; cursor: pointer !important; margin: 0 !important; line-height: normal !important; text-decoration: none !important;">
                    <svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24" style="flex-shrink: 0 !important;">
                        <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
                    </svg>
                    <?php esc_html_e('Share', 'wpswitchboard'); ?>
                </button>
                <?php endif; ?>
                
                <?php
                foreach ($enabled_platforms as $platform):
                    if (!isset($all_platforms[$platform])) {
                        continue;
                    }
                    $p = $all_platforms[$platform];
                ?>
                <a href="javascript:void(0);"
                   data-share-url="<?php echo esc_url($p['url']); ?>"
                   target="_blank"
                   rel="noopener noreferrer"
                   class="switchboard-share-link sb-link-override sb-platform-<?php echo esc_attr($platform); ?>"
                   data-platform="<?php echo esc_attr($platform); ?>"
                   data-color="<?php echo esc_attr($p['color']); ?>"
                   style="display: inline-flex !important; align-items: center !important; gap: 8px !important; padding: 10px 16px !important; background: <?php echo esc_attr($p['color']); ?> !important; color: white !important; text-decoration: none !important; border-radius: 4px !important; font-size: 14px !important; font-weight: 500 !important; transition: opacity 0.2s !important; margin: 0 !important; line-height: normal !important; border: none !important; opacity: 1 !important; visibility: visible !important; position: relative !important; cursor: pointer !important;">
                    <svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24" style="flex-shrink: 0 !important; display: inline-block !important;">
                        <?php echo wp_kses($p['icon'], array('path' => array('d' => true))); ?>
                    </svg>
                    <span style="display: inline-block;"><?php echo esc_html($p['label']); ?></span>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
    
    public function add_web_share_script() {
        if (!is_singular()) {
            return;
        }
        ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const shareBtn = document.querySelector('.switchboard-web-share-btn');

            if (shareBtn && navigator.share) {
                shareBtn.style.display = 'inline-flex';

                shareBtn.addEventListener('click', async function() {
                    try {
                        await navigator.share({
                            title: this.dataset.title,
                            url: this.dataset.url
                        });
                    } catch (err) {
                        if (err.name !== 'AbortError') {
                            console.error('Share failed:', err);
                        }
                    }
                });
            }

            // Handle share button clicks (bypass ad blocker detection)
            document.querySelectorAll('.switchboard-share-link').forEach(link => {
                // Click handler to open share URL
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const shareUrl = this.dataset.shareUrl;
                    if (shareUrl) {
                        window.open(shareUrl, '_blank', 'noopener,noreferrer,width=600,height=400');
                    }
                });

                // Hover effect
                link.addEventListener('mouseenter', function() {
                    this.style.opacity = '0.85';
                });
                link.addEventListener('mouseleave', function() {
                    this.style.opacity = '1';
                });
            });
        });
        </script>
        <?php
    }
    
    public function render_settings($settings = []) {
        $platforms = isset($settings['platforms']) ? $settings['platforms'] : 'facebook,x,linkedin,whatsapp,reddit,email';
        $post_types = isset($settings['post_types']) ? $settings['post_types'] : 'post';
        $position = isset($settings['position']) ? $settings['position'] : 'after';
        $web_share_api = isset($settings['web_share_api']) ? $settings['web_share_api'] : 'yes';
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : 'yes';

        // Convert comma-separated strings to arrays
        $selected_platforms = array_map('trim', explode(',', $platforms));
        $selected_post_types = array_map('trim', explode(',', $post_types));

        // Available platforms
        $available_platforms = [
            'facebook' => 'Facebook',
            'x' => 'X (Twitter)',
            'linkedin' => 'LinkedIn',
            'whatsapp' => 'WhatsApp',
            'reddit' => 'Reddit',
            'email' => 'Email'
        ];

        // Get all public post types
        $all_post_types = get_post_types(['public' => true], 'objects');
        $exclude_types = ['attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation'];
        $all_post_types = array_diff_key($all_post_types, array_flip($exclude_types));
        ?>
        <input type="hidden" name="module" value="social-share-buttons">

        <input type="hidden" name="setting_platforms" id="setting_platforms" value="<?php echo esc_attr($platforms); ?>">

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Select Platforms', 'wpswitchboard'); ?></label>
            <div class="switchboard-tag-selector" data-input-id="setting_platforms">
                <div class="switchboard-selected-tags" id="selected-platforms">
                    <?php foreach ($selected_platforms as $platform_slug):
                        if (isset($available_platforms[$platform_slug])): ?>
                            <span class="switchboard-tag" data-value="<?php echo esc_attr($platform_slug); ?>">
                                <?php echo esc_html($available_platforms[$platform_slug]); ?>
                                <span class="remove-tag">×</span>
                            </span>
                        <?php endif;
                    endforeach; ?>
                </div>
                <div class="switchboard-available-tags">
                    <?php foreach ($available_platforms as $platform_slug => $platform_name):
                        $is_selected = in_array($platform_slug, $selected_platforms) ? 'selected' : ''; ?>
                        <span class="switchboard-tag-option <?php echo esc_attr($is_selected); ?>" data-value="<?php echo esc_attr($platform_slug); ?>">
                            <?php echo esc_html($platform_name); ?>
                        </span>
                    <?php endforeach; ?>
                </div>
            </div>
            <p class="sb-sp-description"><?php esc_html_e('Click to select social media platforms to display', 'wpswitchboard'); ?></p>
        </div>

        <input type="hidden" name="setting_post_types" id="setting_post_types" value="<?php echo esc_attr($post_types); ?>">

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Select Post Types', 'wpswitchboard'); ?></label>
            <div class="switchboard-tag-selector" data-input-id="setting_post_types">
                <div class="switchboard-selected-tags" id="selected-post-types">
                    <?php foreach ($selected_post_types as $pt_slug):
                        if (isset($all_post_types[$pt_slug])): ?>
                            <span class="switchboard-tag" data-value="<?php echo esc_attr($pt_slug); ?>">
                                <?php echo esc_html($all_post_types[$pt_slug]->label); ?>
                                <span class="remove-tag">×</span>
                            </span>
                        <?php endif;
                    endforeach; ?>
                </div>
                <div class="switchboard-available-tags">
                    <?php foreach ($all_post_types as $pt_slug => $pt_obj):
                        $is_selected = in_array($pt_slug, $selected_post_types) ? 'selected' : ''; ?>
                        <span class="switchboard-tag-option <?php echo esc_attr($is_selected); ?>" data-value="<?php echo esc_attr($pt_slug); ?>">
                            <?php echo esc_html($pt_obj->label); ?>
                        </span>
                    <?php endforeach; ?>
                </div>
            </div>
            <p class="sb-sp-description"><?php esc_html_e('Choose where to display share buttons', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_position" class="sb-sp-label"><?php esc_html_e('Button Position', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Where to display the share buttons in your content', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_position" id="setting_position" class="sb-sp-select">
                <option value="before" <?php selected($position, 'before'); ?>><?php esc_html_e('Before Content', 'wpswitchboard'); ?></option>
                <option value="after" <?php selected($position, 'after'); ?>><?php esc_html_e('After Content (Recommended)', 'wpswitchboard'); ?></option>
                <option value="both" <?php selected($position, 'both'); ?>><?php esc_html_e('Both Before & After', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Auto Display', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_auto_display" value="yes" <?php checked($auto_display, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php echo wp_kses_post(__('Automatically add share buttons to content. When disabled, use shortcode <code>[social_share]</code> to display buttons manually.', 'wpswitchboard')); ?></p>
            </div>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Web Share API', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_web_share_api" value="yes" <?php checked($web_share_api, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Shows a "Share" button that uses the device\'s native share menu (iOS, Android, etc.)', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('How to Display Share Buttons', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Automatic:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Enable "Auto Display" above and buttons will appear automatically on selected post types.', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item">
                    <strong><?php esc_html_e('Basic shortcode:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value='[social_share]' onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 180px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                </li>
                <li class="sb-sp-list-item">
                    <strong><?php esc_html_e('Custom platforms:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value='[social_share platforms="facebook,x,linkedin"]' onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 380px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                </li>
                <li class="sb-sp-list-item">
                    <strong><?php esc_html_e('In PHP template:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value="<?php echo esc_attr('<?php echo do_shortcode(\'[social_share]\'); ?>'); ?>" onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 380px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                </li>
            </ul>
        </div>

        <script>
        function copyShortcode(input) {
            input.select();
            input.setSelectionRange(0, 99999);
            
            try {
                navigator.clipboard.writeText(input.value).then(function() {
                    showCopiedMessage(input);
                }).catch(function() {
                    document.execCommand('copy');
                    showCopiedMessage(input);
                });
            } catch (err) {
                document.execCommand('copy');
                showCopiedMessage(input);
            }
        }
        
        function showCopiedMessage(input) {
            var message = input.parentElement.querySelector('.sb-module-shortcode-copied');
            if (message) {
                message.classList.add('show');
                setTimeout(function() {
                    message.classList.remove('show');
                }, 2000);
            }
        }
        
        jQuery(document).ready(function($) {
            // Update hidden fields on page load to sync with selected tags
            function updatePlatformsField() {
                var values = [];
                $("#selected-platforms .switchboard-tag").each(function() {
                    values.push($(this).data("value"));
                });
                $("#setting_platforms").val(values.join(","));
            }

            function updatePostTypesField() {
                var values = [];
                $("#selected-post-types .switchboard-tag").each(function() {
                    values.push($(this).data("value"));
                });
                $("#setting_post_types").val(values.join(","));
            }

            // Initialize on page load
            updatePlatformsField();
            updatePostTypesField();

            // Handle platform tag selection
            $("#selected-platforms").parent().find(".switchboard-tag-option").on("click", function() {
                var value = $(this).data("value");
                var text = $(this).text();

                if ($(this).hasClass("selected")) {
                    $(this).removeClass("selected");
                    $("#selected-platforms .switchboard-tag[data-value=\"" + value + "\"]").remove();
                } else {
                    $(this).addClass("selected");
                    $("#selected-platforms").append("<span class=\"switchboard-tag\" data-value=\"" + value + "\">" + text + " <span class=\"remove-tag\">×</span></span>");
                }

                updatePlatformsField();
            });

            $(document).on("click", "#selected-platforms .remove-tag", function() {
                var value = $(this).parent().data("value");
                $(this).parent().remove();
                $("#selected-platforms").parent().find(".switchboard-tag-option[data-value=\"" + value + "\"]").removeClass("selected");
                updatePlatformsField();
            });

            // Handle post type tag selection
            $("#selected-post-types").parent().find(".switchboard-tag-option").on("click", function() {
                var value = $(this).data("value");
                var text = $(this).text();

                if ($(this).hasClass("selected")) {
                    $(this).removeClass("selected");
                    $("#selected-post-types .switchboard-tag[data-value=\"" + value + "\"]").remove();
                } else {
                    $(this).addClass("selected");
                    $("#selected-post-types").append("<span class=\"switchboard-tag\" data-value=\"" + value + "\">" + text + " <span class=\"remove-tag\">×</span></span>");
                }

                updatePostTypesField();
            });

            $(document).on("click", "#selected-post-types .remove-tag", function() {
                var value = $(this).parent().data("value");
                $(this).parent().remove();
                $("#selected-post-types").parent().find(".switchboard-tag-option[data-value=\"" + value + "\"]").removeClass("selected");
                updatePostTypesField();
            });
        });
        </script>
        <?php
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardSocialShareButtons();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
