<?php
/**
 * Settings Page Template
 *
 * Custom HTML template for social media settings page.
 * Features circular social media buttons with dynamic link inputs.
 */

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

// Platform data — single source of truth via canvon_fb_get_platform_data() in frontend-display.php
$canvon_fb_icons = canvon_fb_get_platform_data();

// Get saved values for all platforms
$canvon_fb_platforms = array('phone', 'whatsapp', 'line', 'wechat', 'kakao', 'discord', 'email', 'tiktok', 'twitter', 'linkedin', 'threads', 'facebook', 'instagram', 'youtube');
$canvon_fb_saved_values = array();
$canvon_fb_selected_platforms_str = get_option('canvon_fb_selected_platforms', '');
$canvon_fb_selected_platforms = !empty($canvon_fb_selected_platforms_str) ? explode(',', $canvon_fb_selected_platforms_str) : array();

$canvon_fb_show_premium_activated_banner =
    (bool) get_transient( 'canvon_fb_premium_activated_banner' ) ||
    (bool) get_option( 'canvon_fb_show_premium_activated_banner', false );

$canvon_fb_is_banner_dismissed = (bool) get_option( 'canvon_fb_premium_banner_dismissed', false );

$canvon_fb_is_test_banner = (
    current_user_can( 'manage_options' ) &&
    isset( $_GET['canvon_fb_test_banner'], $_GET['_canvon_fb_test_banner_nonce'] ) &&
    '1' === sanitize_text_field( wp_unslash( $_GET['canvon_fb_test_banner'] ) ) &&
    wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_canvon_fb_test_banner_nonce'] ) ), 'canvon_fb_test_banner' )
);

if ( $canvon_fb_is_test_banner ) {
    $canvon_fb_show_premium_activated_banner = true;
    $canvon_fb_is_banner_dismissed = false;
}

$canvon_fb_show_premium_activated_banner = $canvon_fb_show_premium_activated_banner && ! $canvon_fb_is_banner_dismissed;

$canvon_fb_dismiss_banner_url = wp_nonce_url(
    add_query_arg(
        array(
            'page'                       => 'canvon-floating-buttons',
            'canvon_fb_dismiss_premium_banner' => '1',
        ),
        admin_url( 'admin.php' )
    ),
    'canvon_fb_dismiss_premium_banner',
    '_canvon_fb_banner_nonce'
);

foreach ($canvon_fb_platforms as $canvon_fb_platform) {
    $canvon_fb_saved_values[$canvon_fb_platform] = get_option( 'canvon_fb_' . $canvon_fb_platform . '_url', '' );
}

// Load widget icon SVGs from files
$canvon_fb_icons_dir = CANVON_FB_PLUGIN_DIR . 'assets/images/';
$canvon_fb_widget_icons = array(
    'info'    => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-1.svg' ),
    'chat'    => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-2.svg' ),
    'message' => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-3.svg' ),
    'contact' => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-4.svg' ),
);
?>


<div class="wrap">
    <div class="canvon-fb-settings-wrapper">
        <div class="canvon-fb-left-column">
            <div class="canvon-fb-settings-panel">
                <div class="canvon-fb-settings-panel-header">
                    <h1>Buttons</h1>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=canvon-floating-buttons-appearance' ) ); ?>" class="canvon-fb-secondary-link-button canvon-fb-appearance-link-button">
                        Customize Appearance &rarr;
                    </a>
                </div>
            <form method="post" action="options.php">
                <?php settings_fields( 'canvon_fb_settings_group' ); ?>

                <!-- Hidden input to track selected platforms -->
                <input type="hidden" name="canvon_fb_selected_platforms" id="canvon-fb-selected-platforms" value="<?php echo esc_attr($canvon_fb_selected_platforms_str); ?>">

                <div class="canvon-fb-social-section">
                    <p>Add and manage your floating buttons.</p>

                <?php
                // Group platforms by category
                $canvon_fb_categories = array(
                    'Chat / Messaging' => array('whatsapp', 'line', 'wechat', 'kakao', 'discord'),
                    'Social / Community' => array('tiktok', 'twitter', 'linkedin', 'threads', 'facebook', 'instagram', 'youtube'),
                    'Personal Contact' => array('phone', 'email')
                );

                foreach ($canvon_fb_categories as $canvon_fb_category_name => $canvon_fb_platforms_in_category):
                ?>
                    <h3 style="margin-top: 20px; margin-bottom: 10px; font-size: 14px; color: #0D99FF; font-weight: 600;"><?php echo esc_html( $canvon_fb_category_name ); ?></h3>
                    <div class="canvon-fb-social-grid">
                        <?php
                        foreach ($canvon_fb_platforms_in_category as $canvon_fb_platform) {
                            if (!isset($canvon_fb_icons[$canvon_fb_platform])) continue;
                            $canvon_fb_data = $canvon_fb_icons[$canvon_fb_platform];
                            $canvon_fb_is_active = in_array($canvon_fb_platform, $canvon_fb_selected_platforms) ? 'active' : '';
                            echo '<div class="canvon-fb-social-item">';
                            echo '<button type="button" class="canvon-fb-social-button canvon-fb-' . esc_attr( $canvon_fb_platform ) . ' ' . esc_attr( $canvon_fb_is_active ) . '" data-platform="' . esc_attr( $canvon_fb_platform ) . '">';
                            echo wp_kses( $canvon_fb_data['svg'], canvon_fb_get_icon_kses_allowed_html() );
                            echo '</button>';
                            echo '<label>' . esc_html( $canvon_fb_data['name'] ) . '</label>';
                            echo '</div>';
                        }
                        ?>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="canvon-fb-channels-section">
                <h2>Edit Button</h2>

                <?php if ( $canvon_fb_show_premium_activated_banner ) : ?>
                    <div class="canvon-fb-premium-activated-banner">
                        <a href="<?php echo esc_url( $canvon_fb_dismiss_banner_url ); ?>" class="canvon-fb-premium-activated-banner-dismiss" aria-label="Dismiss">&times;</a>
                        Premium plan was successfully activated.
                    </div>
                <?php endif; ?>

                <div id="canvon-fb-channels-list">
                    <?php
                    $canvon_fb_has_channels = false;
                    // Show channels for selected platforms (even if URL is empty)
                    foreach ($canvon_fb_selected_platforms as $canvon_fb_platform) {
                        if (isset($canvon_fb_icons[$canvon_fb_platform])) {
                            $canvon_fb_has_channels = true;
                            $canvon_fb_platform_data = $canvon_fb_icons[$canvon_fb_platform];
                            $canvon_fb_url = isset($canvon_fb_saved_values[$canvon_fb_platform]) ? $canvon_fb_saved_values[$canvon_fb_platform] : '';
                            $canvon_fb_input_config = function_exists( 'canvon_fb_get_platform_input_config' ) ? canvon_fb_get_platform_input_config( $canvon_fb_platform ) : array(
                                'input_type'  => $canvon_fb_platform === 'email' ? 'email' : 'text',
                                'placeholder' => $canvon_fb_platform === 'email' ? 'your@email.com' : 'Enter URL',
                            );
                            $canvon_fb_input_type = $canvon_fb_input_config['input_type'];
                            $canvon_fb_placeholder = $canvon_fb_input_config['placeholder'];
                            $canvon_fb_help_text = isset( $canvon_fb_input_config['help'] ) ? $canvon_fb_input_config['help'] : '';

                            echo '<div class="canvon-fb-channel-row" data-platform="' . esc_attr( $canvon_fb_platform ) . '">';
                            echo '<div class="canvon-fb-drag-handle"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M40 352l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40zm192 0l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40zM40 320c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0zM232 192l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40zM40 160c-22.1 0-40-17.9-40-40L0 72C0 49.9 17.9 32 40 32l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0zM232 32l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40z"/></svg></div>';
                            echo '<div class="canvon-fb-channel-icon canvon-fb-' . esc_attr( $canvon_fb_platform ) . '">';
                            echo wp_kses( $canvon_fb_platform_data['svg'], canvon_fb_get_icon_kses_allowed_html() );
                            echo '</div>';
                            echo '<div class="canvon-fb-channel-content">';
                            echo '<span class="canvon-fb-channel-label">' . esc_html( $canvon_fb_platform_data['name'] ) . '</span>';
                            echo '<input type="' . esc_attr( $canvon_fb_input_type ) . '" name="canvon_fb_' . esc_attr( $canvon_fb_platform ) . '_url" value="' . esc_attr($canvon_fb_url) . '" placeholder="' . esc_attr( $canvon_fb_placeholder ) . '">';
                            if ( ! empty( $canvon_fb_help_text ) && 'wechat' === $canvon_fb_platform ) {
                                echo '<small class="canvon-fb-channel-help">' . esc_html( $canvon_fb_help_text ) . '</small>';
                            }
                            if ( 'wechat' === $canvon_fb_platform ) {
                                $canvon_fb_wechat_qr_url = get_option( 'canvon_fb_wechat_qr_code_url', '' );
                                $canvon_fb_wechat_qr_id  = absint( get_option( 'canvon_fb_wechat_qr_code_id', 0 ) );
                                echo '<div class="canvon-fb-wechat-qr-control">';
                                echo '<img class="canvon-fb-wechat-qr-preview" src="' . esc_url( $canvon_fb_wechat_qr_url ) . '" alt="" style="' . ( empty( $canvon_fb_wechat_qr_url ) ? 'display:none;' : '' ) . '">';
                                echo '<div class="canvon-fb-wechat-qr-actions">';
                                echo '<button type="button" class="canvon-fb-wechat-qr-button">Upload QR code</button>';
                                echo '<button type="button" class="canvon-fb-wechat-qr-remove" style="' . ( empty( $canvon_fb_wechat_qr_url ) ? 'display:none;' : '' ) . '">Remove</button>';
                                echo '</div>';
                                echo '<input type="hidden" name="canvon_fb_wechat_qr_code_id" class="canvon-fb-wechat-qr-id" value="' . esc_attr( $canvon_fb_wechat_qr_id ) . '">';
                                echo '<input type="hidden" name="canvon_fb_wechat_qr_code_url" class="canvon-fb-wechat-qr-url" value="' . esc_attr( $canvon_fb_wechat_qr_url ) . '">';
                                echo '</div>';
                            }
                            $canvon_fb_show_on_val = function_exists( 'canvon_fb_sanitize_show_on_value' ) ? canvon_fb_sanitize_show_on_value( get_option('canvon_fb_' . $canvon_fb_platform . '_show_on', 'both') ) : get_option('canvon_fb_' . $canvon_fb_platform . '_show_on', 'both');
                            $canvon_fb_d_cls = ($canvon_fb_show_on_val === 'both' || $canvon_fb_show_on_val === 'desktop') ? ' canvon-fb-show-on-active' : '';
                            $canvon_fb_m_cls = ($canvon_fb_show_on_val === 'both' || $canvon_fb_show_on_val === 'mobile')  ? ' canvon-fb-show-on-active' : '';
                            $canvon_fb_laptop_svg = '<svg width="22" height="22" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M63.4026 56.8235C64.0654 56.8243 64.7028 57.0769 65.1847 57.5297C65.6667 57.9826 65.9567 58.6015 65.9955 59.2601C66.0344 59.9186 65.8191 60.5671 65.3937 61.073C64.9683 61.5789 64.365 61.904 63.7068 61.9819L63.4026 62H16.5974C15.9346 61.9993 15.2972 61.7467 14.8153 61.2938C14.3333 60.8409 14.0433 60.222 14.0045 59.5635C13.9656 58.9049 14.1809 58.2564 14.6063 57.7506C15.0317 57.2447 15.6351 56.9196 16.2932 56.8416L16.5974 56.8235H63.4026ZM58.202 18C59.5141 17.9996 60.7778 18.4928 61.7398 19.3808C62.7019 20.2688 63.2912 21.486 63.3896 22.7882L63.4026 23.1765V49.0588C63.403 50.3648 62.9075 51.6226 62.0153 52.5802C61.1232 53.5378 59.9004 54.1244 58.5921 54.2224L58.202 54.2353H21.798C20.4859 54.2357 19.2222 53.7425 18.2602 52.8545C17.2981 51.9665 16.7088 50.7493 16.6104 49.4471L16.5974 49.0588V23.1765C16.597 21.8705 17.0925 20.6127 17.9847 19.6551C18.8768 18.6975 20.0996 18.1109 21.4079 18.0129L21.798 18H58.202ZM58.202 23.1765H21.798V49.0588H58.202V23.1765Z" fill="currentColor"/></svg>';
                            $canvon_fb_phone_svg  = '<svg width="22" height="22" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M51.5 12H29.5C28.0413 12 26.6424 12.5795 25.6109 13.6109C24.5795 14.6424 24 16.0413 24 17.5V61.5C24 62.9587 24.5795 64.3576 25.6109 65.3891C26.6424 66.4205 28.0413 67 29.5 67H51.5C52.9587 67 54.3576 66.4205 55.3891 65.3891C56.4205 64.3576 57 62.9587 57 61.5V17.5C57 16.0413 56.4205 14.6424 55.3891 13.6109C54.3576 12.5795 52.9587 12 51.5 12ZM43.25 64.25H37.75V61.5H43.25V64.25ZM51.5 58.75H29.5V20.25H51.5V58.75Z" fill="currentColor"/></svg>';
                            echo '<div class="canvon-fb-show-on-control">';
                            echo '<span class="canvon-fb-show-on-label">Show on</span>';
                            echo '<input type="hidden" name="canvon_fb_' . esc_attr( $canvon_fb_platform ) . '_show_on" class="canvon-fb-show-on-value" value="' . esc_attr($canvon_fb_show_on_val) . '">';
                            echo '<button type="button" class="canvon-fb-show-on-btn' . esc_attr( $canvon_fb_d_cls ) . '" data-device="desktop" title="Desktop">' . wp_kses( $canvon_fb_laptop_svg, canvon_fb_get_icon_kses_allowed_html() ) . '</button>';
                            echo '<button type="button" class="canvon-fb-show-on-btn' . esc_attr( $canvon_fb_m_cls ) . '" data-device="mobile" title="Mobile">' . wp_kses( $canvon_fb_phone_svg, canvon_fb_get_icon_kses_allowed_html() ) . '</button>';
                            echo '</div>';
                            echo '</div>';
                            echo '<button type="button" class="canvon-fb-channel-remove"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#0D99FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></button>';
                            echo '</div>';
                        }
                    }

                    if (!$canvon_fb_has_channels) {
                        echo '<div class="canvon-fb-empty-state"><p>👆 Click on a social media button above to get started!</p></div>';
                    }
                    ?>
                </div>
            </div>

            <div class="canvon-fb-save-section" style="padding: 20px 30px; margin-top: 0;">
                <?php submit_button('Save Changes', 'primary', 'submit', false); ?>
            </div>
        </form>
            </div><!-- /.canvon-fb-settings-panel -->
        </div><!-- /.canvon-fb-left-column -->

        <div class="canvon-fb-right-column">
            <?php require_once plugin_dir_path( __FILE__ ) . 'preview-section.php'; ?>
        </div>
    </div><!-- /.canvon-fb-settings-wrapper -->
</div><!-- /.wrap -->

<?php
ob_start();
?>
// Defined in global scope so preview-section.php can access it across document.ready closures
var appearanceSettings = {
    position: '<?php echo esc_js(get_option('canvon_fb_button_position', 'right')); ?>',
    size: '<?php echo esc_js(get_option('canvon_fb_button_size', 'M')); ?>',
    shape: '<?php echo esc_js(get_option('canvon_fb_button_shape', 'round')); ?>',
    color: '<?php echo esc_js(get_option('canvon_fb_button_color', '#0D99FF')); ?>',
    widgetIcon: '<?php echo esc_js(get_option('canvon_fb_widget_icon', 'info')); ?>',
    widgetText: '<?php echo esc_js(get_option('canvon_fb_widget_icon_text', '')); ?>',
    widgetTextShow: <?php echo get_option('canvon_fb_widget_icon_text_show', false) ? 'true' : 'false'; ?>
    <?php do_action( 'canvon_fb_settings_appearance_settings_js' ); ?>
};

jQuery(document).ready(function($) {
    function relocateFreemiusLicenseNotice() {
        var $canvon_fb_settingsWrapper = $('.canvon-fb-settings-wrapper').first();
        var $canvon_fb_notices = $('.canvon-fb-settings-wrapper .fs-notice');

        if ($canvon_fb_notices.length && $canvon_fb_settingsWrapper.length) {
            $canvon_fb_notices.addClass('canvon-fb-license-notice-row').insertBefore($canvon_fb_settingsWrapper);
        }
    }

    relocateFreemiusLicenseNotice();
    setTimeout(relocateFreemiusLicenseNotice, 250);
    setTimeout(relocateFreemiusLicenseNotice, 1000);

    var settingsWrapper = document.querySelector('.canvon-fb-settings-wrapper');
    if (settingsWrapper && window.MutationObserver) {
        var freemiusNoticeObserver = new MutationObserver(relocateFreemiusLicenseNotice);
        freemiusNoticeObserver.observe(settingsWrapper, {
            childList: true,
            subtree: true
        });
    }

    // Widget icon SVGs
    var widgetIcons = <?php echo wp_json_encode( $canvon_fb_widget_icons ); ?>;

    // Platform data for JavaScript — built dynamically from canvon_fb_get_platform_data()
    <?php
    $canvon_fb_js_platforms = array();
    foreach ( $canvon_fb_icons as $canvon_fb_platform_key => $canvon_fb_platform_data ) {
        $canvon_fb_input_config = function_exists( 'canvon_fb_get_platform_input_config' ) ? canvon_fb_get_platform_input_config( $canvon_fb_platform_key ) : array(
            'input_type'  => $canvon_fb_platform_key === 'email' ? 'email' : 'text',
            'placeholder' => $canvon_fb_platform_key === 'email' ? 'your@email.com' : 'Enter URL',
        );
        $canvon_fb_js_platforms[ $canvon_fb_platform_key ] = array(
            'label'      => $canvon_fb_platform_data['name'],
            'placeholder'=> $canvon_fb_input_config['placeholder'],
            'inputName'  => 'canvon_fb_' . $canvon_fb_platform_key . '_url',
            'inputType'  => $canvon_fb_input_config['input_type'],
            'help'       => isset( $canvon_fb_input_config['help'] ) ? $canvon_fb_input_config['help'] : '',
            'colorClass' => $canvon_fb_platform_data['color_class'],
            'svg'        => $canvon_fb_platform_data['svg'],
        );
    }
    ?>
    var platforms = <?php echo wp_json_encode( $canvon_fb_js_platforms ); ?>;

    // Handle social button click
    $('.canvon-fb-social-button').on('click', function(e) {
        e.preventDefault();
        var platform = $(this).data('platform');
        var $canvon_fb_channelsList = $('#canvon-fb-channels-list');

        // Remove empty state if exists
        $canvon_fb_channelsList.find('.canvon-fb-empty-state').remove();

        // Check if platform already exists
        var $canvon_fb_existingRow = $canvon_fb_channelsList.find('[data-platform="' + platform + '"]');
        if ($canvon_fb_existingRow.length > 0) {
            // Jump to the existing row (no animation)
            var offset = $canvon_fb_existingRow.offset().top - 100;
            window.scrollTo(0, offset);
            // Highlight briefly
            $canvon_fb_existingRow.css('background-color', '#fff3cd');
            setTimeout(function() {
                $canvon_fb_existingRow.css('background-color', '');
            }, 1000);
            return false;
        }

        // Add active class to button
        $(this).addClass('active');

        // Add channel row
        var platformData = platforms[platform];
        var row = $('<div class="canvon-fb-channel-row" data-platform="' + platform + '"></div>');

        var dragHandle = $('<div class="canvon-fb-drag-handle"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M40 352l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40zm192 0l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40zM40 320c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0zM232 192l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40zM40 160c-22.1 0-40-17.9-40-40L0 72C0 49.9 17.9 32 40 32l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0zM232 32l48 0c22.1 0 40 17.9 40 40l0 48c0 22.1-17.9 40-40 40l-48 0c-22.1 0-40-17.9-40-40l0-48c0-22.1 17.9-40 40-40z"/></svg></div>');

        var icon = $('<div class="canvon-fb-channel-icon ' + platformData.colorClass + '"></div>');
        icon.html(platformData.svg);

        var content = $('<div class="canvon-fb-channel-content"></div>');
        content.append('<span class="canvon-fb-channel-label">' + platformData.label + '</span>');
        content.append('<input type="' + platformData.inputType + '" name="' + platformData.inputName + '" placeholder="' + platformData.placeholder + '">');
        if (platform === 'wechat' && platformData.help) {
            content.append('<small class="canvon-fb-channel-help">' + platformData.help + '</small>');
            content.append('<div class="canvon-fb-wechat-qr-control">'
                + '<img class="canvon-fb-wechat-qr-preview" src="" alt="" style="display:none;">'
                + '<div class="canvon-fb-wechat-qr-actions">'
                + '<button type="button" class="canvon-fb-wechat-qr-button">Upload QR code</button>'
                + '<button type="button" class="canvon-fb-wechat-qr-remove" style="display:none;">Remove</button>'
                + '</div>'
                + '<input type="hidden" name="canvon_fb_wechat_qr_code_id" class="canvon-fb-wechat-qr-id" value="">'
                + '<input type="hidden" name="canvon_fb_wechat_qr_code_url" class="canvon-fb-wechat-qr-url" value="">'
                + '</div>');
        }
        content.append('<div class="canvon-fb-show-on-control">'
            + '<span class="canvon-fb-show-on-label">Show on</span>'
            + '<input type="hidden" name="canvon_fb_' + platform + '_show_on" class="canvon-fb-show-on-value" value="both">'
            + '<button type="button" class="canvon-fb-show-on-btn canvon-fb-show-on-active" data-device="desktop" title="Desktop"><svg width="22" height="22" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M63.4026 56.8235C64.0654 56.8243 64.7028 57.0769 65.1847 57.5297C65.6667 57.9826 65.9567 58.6015 65.9955 59.2601C66.0344 59.9186 65.8191 60.5671 65.3937 61.073C64.9683 61.5789 64.365 61.904 63.7068 61.9819L63.4026 62H16.5974C15.9346 61.9993 15.2972 61.7467 14.8153 61.2938C14.3333 60.8409 14.0433 60.222 14.0045 59.5635C13.9656 58.9049 14.1809 58.2564 14.6063 57.7506C15.0317 57.2447 15.6351 56.9196 16.2932 56.8416L16.5974 56.8235H63.4026ZM58.202 18C59.5141 17.9996 60.7778 18.4928 61.7398 19.3808C62.7019 20.2688 63.2912 21.486 63.3896 22.7882L63.4026 23.1765V49.0588C63.403 50.3648 62.9075 51.6226 62.0153 52.5802C61.1232 53.5378 59.9004 54.1244 58.5921 54.2224L58.202 54.2353H21.798C20.4859 54.2357 19.2222 53.7425 18.2602 52.8545C17.2981 51.9665 16.7088 50.7493 16.6104 49.4471L16.5974 49.0588V23.1765C16.597 21.8705 17.0925 20.6127 17.9847 19.6551C18.8768 18.6975 20.0996 18.1109 21.4079 18.0129L21.798 18H58.202ZM58.202 23.1765H21.798V49.0588H58.202V23.1765Z" fill="currentColor"/></svg></button>'
            + '<button type="button" class="canvon-fb-show-on-btn canvon-fb-show-on-active" data-device="mobile" title="Mobile"><svg width="22" height="22" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M51.5 12H29.5C28.0413 12 26.6424 12.5795 25.6109 13.6109C24.5795 14.6424 24 16.0413 24 17.5V61.5C24 62.9587 24.5795 64.3576 25.6109 65.3891C26.6424 66.4205 28.0413 67 29.5 67H51.5C52.9587 67 54.3576 66.4205 55.3891 65.3891C56.4205 64.3576 57 62.9587 57 61.5V17.5C57 16.0413 56.4205 14.6424 55.3891 13.6109C54.3576 12.5795 52.9587 12 51.5 12ZM43.25 64.25H37.75V61.5H43.25V64.25ZM51.5 58.75H29.5V20.25H51.5V58.75Z" fill="currentColor"/></svg></button>'
            + '</div>');

        var removeBtn = $('<button type="button" class="canvon-fb-channel-remove"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#0D99FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></button>');

        row.append(dragHandle, icon, content, removeBtn);

        // Add to top of list
        $canvon_fb_channelsList.prepend(row);

        // Jump to the newly added row (no animation)
        setTimeout(function() {
            var offset = row.offset().top - 100;
            window.scrollTo(0, offset);
        }, 100);

        content.find('input').focus();

        // Update selected platforms hidden field
        updateSelectedPlatforms();

        // Update preview
        updatePreview();

        return false;
    });

    // Handle Show On device toggle buttons (premium)
    $(document).on('click', '.canvon-fb-show-on-btn', function() {
        var $canvon_fb_btn     = $(this);
        var $canvon_fb_control = $canvon_fb_btn.closest('.canvon-fb-show-on-control');
        var $canvon_fb_input   = $canvon_fb_control.find('.canvon-fb-show-on-value');
        $canvon_fb_btn.toggleClass('canvon-fb-show-on-active');
        var dActive = $canvon_fb_control.find('[data-device="desktop"]').hasClass('canvon-fb-show-on-active');
        var mActive = $canvon_fb_control.find('[data-device="mobile"]').hasClass('canvon-fb-show-on-active');
        $canvon_fb_input.val(dActive && mActive ? 'both' : dActive ? 'desktop' : mActive ? 'mobile' : 'none');
    });


    var mcpWechatQrFrame;

    $(document).on('click', '.canvon-fb-wechat-qr-button', function(e) {
        e.preventDefault();

        var $canvon_fb_control = $(this).closest('.canvon-fb-wechat-qr-control');

        if (mcpWechatQrFrame) {
            mcpWechatQrFrame.off('select');
        }

        mcpWechatQrFrame = wp.media({
            title: 'Select WeChat QR code',
            button: { text: 'Use this QR code' },
            library: { type: 'image' },
            multiple: false
        });

        mcpWechatQrFrame.on('select', function() {
            var attachment = mcpWechatQrFrame.state().get('selection').first().toJSON();
            var url = attachment.url || '';
            $canvon_fb_control.find('.canvon-fb-wechat-qr-id').val(attachment.id || '');
            $canvon_fb_control.find('.canvon-fb-wechat-qr-url').val(url);
            $canvon_fb_control.find('.canvon-fb-wechat-qr-preview').attr('src', url).toggle(!!url);
            $canvon_fb_control.find('.canvon-fb-wechat-qr-remove').toggle(!!url);
            updatePreview();
        });

        mcpWechatQrFrame.open();
    });

    $(document).on('click', '.canvon-fb-wechat-qr-remove', function(e) {
        e.preventDefault();

        var $canvon_fb_control = $(this).closest('.canvon-fb-wechat-qr-control');
        $canvon_fb_control.find('.canvon-fb-wechat-qr-id').val('');
        $canvon_fb_control.find('.canvon-fb-wechat-qr-url').val('');
        $canvon_fb_control.find('.canvon-fb-wechat-qr-preview').attr('src', '').hide();
        $(this).hide();
        updatePreview();
    });

    // Handle remove button
    $(document).on('click', '.canvon-fb-channel-remove', function() {
        var $canvon_fb_row = $(this).closest('.canvon-fb-channel-row');
        var platform = $canvon_fb_row.data('platform');

        // Remove active class from button
        $('.canvon-fb-social-button[data-platform="' + platform + '"]').removeClass('active');

        // Remove row
        $canvon_fb_row.remove();

        // If no channels at all, show empty state
        if ($('#canvon-fb-channels-list .canvon-fb-channel-row').length === 0) {
            $('#canvon-fb-channels-list').html('<div class="canvon-fb-empty-state"><p>👆 Click on a social media button above to get started!</p></div>');
        }

        // Update selected platforms hidden field
        updateSelectedPlatforms();

        // Update preview
        updatePreview();
    });

    // Function to update the selected platforms hidden input
    function updateSelectedPlatforms() {
        var platforms = [];
        $('#canvon-fb-channels-list .canvon-fb-channel-row').each(function() {
            platforms.push($(this).data('platform'));
        });
        $('#canvon-fb-selected-platforms').val(platforms.join(','));
    }

    // Function to update preview
    function updatePreview() {
        var $canvon_fb_previewIcons = $('#canvon-fb-preview-icons');
        var $canvon_fb_placeholder = $('#canvon-fb-preview-placeholder');

        // Clear preview
        $canvon_fb_previewIcons.empty();
        $canvon_fb_previewIcons.removeClass('expanded');

        // Apply appearance settings to preview container
        $canvon_fb_previewIcons.attr('data-position', appearanceSettings.position);
        $canvon_fb_previewIcons.attr('data-size', appearanceSettings.size);
        $canvon_fb_previewIcons.attr('data-shape', appearanceSettings.shape);
        $canvon_fb_previewIcons.attr('data-color', appearanceSettings.color);

        // Apply scaled offsets only when custom mode is enabled
        var $canvon_fb_content = $canvon_fb_previewIcons.closest('.canvon-fb-browser-content');
        if ( appearanceSettings.offsetEnabled ) {
            var scaleV = $canvon_fb_content.innerHeight() / 900;
            var scaleH = $canvon_fb_content.innerWidth()  / 1440;
            $canvon_fb_previewIcons.css('bottom', Math.round(appearanceSettings.vOffset * scaleV) + 'px');
            if (appearanceSettings.position === 'left') {
                $canvon_fb_previewIcons.css({ 'left': Math.round(appearanceSettings.hOffset * scaleH) + 'px', 'right': '' });
            } else {
                $canvon_fb_previewIcons.css({ 'right': Math.round(appearanceSettings.hOffset * scaleH) + 'px', 'left': '' });
            }
        } else {
            $canvon_fb_previewIcons.css({ 'bottom': '', 'left': '', 'right': '' });
        }

        // Get all active channels
        var $canvon_fb_channels = $('#canvon-fb-channels-list .canvon-fb-channel-row');

        if ($canvon_fb_channels.length === 0) {
            $canvon_fb_placeholder.show();
        } else {
            $canvon_fb_placeholder.hide();

            if ($canvon_fb_channels.length === 1) {
                // Show single icon
                var platform = $canvon_fb_channels.first().data('platform');
                var platformData = platforms[platform];

                if (platformData && platformData.svg) {
                    var previewIcon = $('<div class="canvon-fb-preview-icon ' + platformData.colorClass + '"></div>');
                    previewIcon.html(platformData.svg);
                    $canvon_fb_previewIcons.append(previewIcon);
                }
            } else {
                // Show widget icon for 2+ channels with saved custom color and optional text
                var widgetIconHtml = (appearanceSettings.widgetIcon === 'custom' && appearanceSettings.customIconUrl)
                    ? '<img src="' + appearanceSettings.customIconUrl + '" style="width:50%;height:50%;object-fit:contain;mix-blend-mode:multiply;" />'
                    : (widgetIcons[appearanceSettings.widgetIcon] || widgetIcons['info']);
                if (appearanceSettings.widgetTextShow && appearanceSettings.widgetText) {
                    var wrapper = $('<div class="canvon-fb-widget-with-text"></div>');
                    var infoIcon = $('<div class="canvon-fb-preview-info-icon"></div>');
                    infoIcon.css('background-color', appearanceSettings.color);
                    infoIcon.html(widgetIconHtml);
                    infoIcon.attr('data-collapsed', 'true');
                    var textDiv = $('<div class="canvon-fb-widget-text"></div>').text(appearanceSettings.widgetText);
                    wrapper.append(infoIcon).append(textDiv);
                    $canvon_fb_previewIcons.append(wrapper);
                } else {
                    var infoIcon = $('<div class="canvon-fb-preview-info-icon"></div>');
                    infoIcon.css('background-color', appearanceSettings.color);
                    infoIcon.html(widgetIconHtml);
                    infoIcon.attr('data-collapsed', 'true');
                    $canvon_fb_previewIcons.append(infoIcon);
                }
            }
        }

        // Apply custom size after icons are in the DOM
        applyPreviewCustomSize($canvon_fb_previewIcons);
        applyPreviewCustomRadius($canvon_fb_previewIcons);
    }

    function applyPreviewCustomSize($canvon_fb_container) {
        if ( appearanceSettings.sizeEnabled && appearanceSettings.customSize > 0 ) {
            var px    = appearanceSettings.customSize;
            var svgPx = Math.round(px * 0.5);
            $canvon_fb_container.find('.canvon-fb-preview-icon, .canvon-fb-preview-info-icon, .canvon-fb-preview-close').css({ 'width': px + 'px', 'height': px + 'px' });
            $canvon_fb_container.find('.canvon-fb-preview-icon svg, .canvon-fb-preview-info-icon svg').css({ 'width': svgPx + 'px', 'height': svgPx + 'px' });
        } else {
            $canvon_fb_container.find('.canvon-fb-preview-icon, .canvon-fb-preview-info-icon, .canvon-fb-preview-close').css({ 'width': '', 'height': '' });
            $canvon_fb_container.find('.canvon-fb-preview-icon svg, .canvon-fb-preview-info-icon svg').css({ 'width': '', 'height': '' });
        }
    }

    function applyPreviewCustomRadius($canvon_fb_container) {
        if ( appearanceSettings.radiusEnabled ) {
            $canvon_fb_container.find('.canvon-fb-preview-icon, .canvon-fb-preview-info-icon, .canvon-fb-preview-close').css({ 'border-radius': appearanceSettings.customRadius + 'px' });
        } else {
            $canvon_fb_container.find('.canvon-fb-preview-icon, .canvon-fb-preview-info-icon, .canvon-fb-preview-close').css({ 'border-radius': '' });
        }
    }

    // Handle info icon click to expand/collapse
    $(document).on('click', '.canvon-fb-preview-info-icon', function() {
        var $canvon_fb_previewIcons = $('#canvon-fb-preview-icons');
        var isCollapsed = $(this).attr('data-collapsed') === 'true';

        if (isCollapsed) {
            // Expand - show all icons
            $canvon_fb_previewIcons.empty();
            $canvon_fb_previewIcons.addClass('expanded');

            var $canvon_fb_channels = $('#canvon-fb-channels-list .canvon-fb-channel-row');
            $canvon_fb_channels.each(function() {
                var platform = $(this).data('platform');
                var platformData = platforms[platform];

                if (platformData && platformData.svg) {
                    var previewIcon = $('<div class="canvon-fb-preview-icon ' + platformData.colorClass + '"></div>');
                    previewIcon.html(platformData.svg);
                    $canvon_fb_previewIcons.append(previewIcon);
                }
            });

            // Add close button at the bottom with custom color
            var closeBtn = $('<div class="canvon-fb-preview-close"></div>');
            closeBtn.css('background-color', appearanceSettings.color);
            closeBtn.html('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>');
            $canvon_fb_previewIcons.append(closeBtn);

            applyPreviewCustomSize($canvon_fb_previewIcons);
            applyPreviewCustomRadius($canvon_fb_previewIcons);
        }
    });

    // Handle close button click to collapse
    $(document).on('click', '.canvon-fb-preview-close', function() {
        updatePreview();
    });

    // Initialize sortable for drag and drop
    function initSortable() {
        if (typeof $.fn.sortable !== 'undefined') {
            $('#canvon-fb-channels-list').sortable({
                handle: '.canvon-fb-drag-handle',
                cursor: 'grabbing',
                opacity: 0.8,
                placeholder: 'canvon-fb-channel-placeholder',
                update: function(event, ui) {
                    // Update selected platforms order
                    updateSelectedPlatforms();
                    // Update preview when order changes
                    updatePreview();
                }
            });
        } else {
            console.error('jQuery UI Sortable not loaded');
        }
    }

    initSortable();

    // Initialize preview on page load
    updatePreview();
});

<?php
wp_add_inline_script( 'canvon-fb-admin-script', ob_get_clean() );
?>
