<?php
/**
 * Plugin Name: FontSizePicker Unit Bug Replication
 * Description: Replicates WordPress Core Ticket #63922 - FontSizePicker incorrectly measures units for selecting elements
 * Version: 1.0.0
 * Author: Bug Replication
 * Requires at least: 6.0
 * Tested up to: 6.8
 * License: GPL v2 or later
 */

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

class FontSizePickerBugReplication {
    
    public function __construct() {
        add_action('init', array($this, 'register_block'));
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_block_assets'));
    }
    
    public function register_block() {
        register_block_type('fontsize-bug/test-block', array(
            'editor_script' => 'fontsize-bug-block',
            'attributes' => array(
                'titleFontSize' => array(
                    'type' => 'string',
                    'default' => '16'
                ),
                'titleFontUnit' => array(
                    'type' => 'string', 
                    'default' => 'px'
                ),
                'content' => array(
                    'type' => 'string',
                    'default' => 'Test text with FontSizePicker bug'
                )
            ),
            'render_callback' => array($this, 'render_block')
        ));
    }
    
    public function enqueue_block_assets() {
        wp_enqueue_script(
            'fontsize-bug-block',
            plugin_dir_url(__FILE__) . 'block.js',
            array('wp-blocks', 'wp-components', 'wp-element', 'wp-editor', 'wp-block-editor'),
            '1.0.0',
            true
        );
        
        // Inline the JavaScript since this is a single file plugin
        $this->inline_block_script();
    }
    
    private function inline_block_script() {
        $script = "
        (function() {
            const { registerBlockType } = wp.blocks;
            const { InspectorControls, RichText } = wp.blockEditor;
            const { PanelBody, FontSizePicker } = wp.components;
            const { Fragment, createElement: el } = wp.element;
            
            registerBlockType('fontsize-bug/test-block', {
                title: 'FontSize Bug Test',
                icon: 'text',
                category: 'text',
                attributes: {
                    titleFontSize: {
                        type: 'string',
                        default: '16'
                    },
                    titleFontUnit: {
                        type: 'string',
                        default: 'px'
                    },
                    content: {
                        type: 'string',
                        default: 'Test text with FontSizePicker bug'
                    }
                },
                
                edit: function(props) {
                    const { attributes, setAttributes } = props;
                    const { titleFontSize, titleFontUnit, content } = attributes;
                    
                    // Font sizes that demonstrate the bug
                    // Using numeric values that will be converted to rem internally
                    const fontSizes = [
                        {
                            name: 'Small',
                            size: 12,
                            slug: 'small'
                        },
                        {
                            name: 'Normal', 
                            size: 16,
                            slug: 'normal'
                        },
                        {
                            name: 'Medium',
                            size: 20,
                            slug: 'medium'
                        },
                        {
                            name: 'Large',
                            size: 24,
                            slug: 'large'
                        },
                        {
                            name: 'Big',
                            size: 32,
                            slug: 'big'
                        }
                    ];
                    
                    return el(Fragment, {},
                        el(InspectorControls, {},
                            el(PanelBody, { title: 'Typography Settings', initialOpen: true },
                                el('div', { style: { marginBottom: '20px' } },
                                    el('strong', {}, 'Font Size (Bug Demonstration)'),
                                    el('br'),
                                    el('small', {}, 'Switch between presets (S/M/L/XL) then to custom - notice unit inconsistency')
                                ),
                                el(FontSizePicker, {
                                    __next40pxDefaultSize: true,
                                    fontSizes: fontSizes,
                                    value: titleFontSize ? parseFloat(titleFontSize) : undefined,
                                    onChange: function(newSize) {
                                        console.log('FontSizePicker onChange:', newSize, typeof newSize);
                                        
                                        if (newSize === undefined) {
                                            setAttributes({
                                                titleFontSize: '16',
                                                titleFontUnit: 'px'
                                            });
                                            return;
                                        }
                                        
                                        // This is where the bug manifests:
                                        // We set unit as 'px' but the value might be in rem
                                        setAttributes({
                                            titleFontSize: String(newSize),
                                            titleFontUnit: 'px'  // Always setting as px but actual value conversion varies
                                        });
                                    },
                                    withSlider: true
                                }),
                                el('div', { style: { marginTop: '15px', padding: '10px', background: '#f0f0f0', borderRadius: '4px' } },
                                    el('strong', {}, 'Debug Info:'),
                                    el('br'),
                                    el('span', {}, 'Stored Font Size: ' + titleFontSize + ' ' + titleFontUnit),
                                    el('br'),
                                    el('span', {}, 'Actual Computed Style: Check inspector'),
                                    el('br'),
                                    el('small', { style: { color: '#d63638' } }, 
                                        'BUG: When switching from presets to custom, units may show as px but be calculated as rem'
                                    )
                                )
                            )
                        ),
                        el('div', { 
                            className: 'fontsize-bug-test-block',
                            style: { 
                                fontSize: titleFontSize + titleFontUnit,
                                border: '2px dashed #ccc',
                                padding: '20px',
                                margin: '10px 0'
                            }
                        },
                            el(RichText, {
                                tagName: 'p',
                                placeholder: 'Enter test text...',
                                value: content,
                                onChange: function(newContent) {
                                    setAttributes({ content: newContent });
                                },
                                style: {
                                    fontSize: 'inherit',
                                    margin: 0
                                }
                            }),
                            el('div', { 
                                style: { 
                                    fontSize: '12px', 
                                    color: '#666', 
                                    marginTop: '10px',
                                    fontFamily: 'monospace'
                                }
                            },
                                'Applied: font-size: ' + titleFontSize + titleFontUnit
                            )
                        )
                    );
                },
                
                save: function(props) {
                    const { attributes } = props;
                    const { titleFontSize, titleFontUnit, content } = attributes;
                    
                    return el('div', {
                        className: 'fontsize-bug-test-block',
                        style: { fontSize: titleFontSize + titleFontUnit }
                    }, content);
                }
            });
        })();
        ";
        
        wp_add_inline_script('fontsize-bug-block', $script);
    }
    
    public function render_block($attributes) {
        $font_size = isset($attributes['titleFontSize']) ? $attributes['titleFontSize'] : '16';
        $font_unit = isset($attributes['titleFontUnit']) ? $attributes['titleFontUnit'] : 'px';
        $content = isset($attributes['content']) ? $attributes['content'] : 'Test text';
        
        return sprintf(
            '<div class="fontsize-bug-test-block" style="font-size: %s%s; border: 1px solid #ddd; padding: 15px;">%s</div>',
            esc_attr($font_size),
            esc_attr($font_unit), 
            wp_kses_post($content)
        );
    }
}

// Initialize the plugin
new FontSizePickerBugReplication();

// Add some CSS for better visualization
add_action('wp_head', function() {
    echo '<style>
        .fontsize-bug-test-block {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }
    </style>';
});

// Add admin notice explaining the bug
add_action('admin_notices', function() {
    $screen = get_current_screen();
    if ($screen && ($screen->id === 'post' || $screen->id === 'page')) {
        echo '<div class="notice notice-info">
            <p><strong>FontSizePicker Bug Replication Active</strong></p>
            <p>This plugin replicates WordPress Core Ticket #63922. To see the bug:</p>
            <ol>
                <li>Add the "FontSize Bug Test" block</li>
                <li>In the sidebar, switch between font size presets (S/M/L/XL)</li>
                <li>Then switch to custom size input</li>
                <li>Notice the unit inconsistency - it shows "px" but may calculate as "rem"</li>
                <li>Check browser inspector to see actual computed font-size</li>
            </ol>
        </div>';
    }
});

?>