/**
 * WordPress Block Editor customizations for PinnerPress
 * Adds Pinterest-specific options to image blocks
 */
(function(wp) {
    /**
     * Debug logging function that only logs when debug is enabled
     * @param {...any} args - Arguments to log
     */
    function pinnerpressDebugLog() {
        // Check for debug parameter in URL since this is in the admin
        var urlParams = new URLSearchParams(window.location.search);
        var debugEnabled = urlParams.get('pinnerpressdebug') === '1';
        
        if (debugEnabled) {
            console.log.apply(console, arguments);
        }
    }
    
    /**
     * Track analytics event for block editor interactions
     * @param {string} eventType - The type of event to track
     * @param {object} eventData - Additional data for the event
     */
    function pinnerpressTrackBlockEditorEvent(eventType, eventData) {
        // Check if analytics is enabled and we have the necessary data
        if (typeof pinnerpressVars === 'undefined' || !pinnerpressVars.analyticsNonce) {
            return;
        }

        // Prepare data for AJAX request
        var data = {
            action: 'pinnerpress_track_event',
            nonce: pinnerpressVars.analyticsNonce,
            event_type: 'block_editor_button_click',
            event_data: {
                block_editor_action: eventType,
                ...eventData
            },
            post_id: wp.data.select('core/editor').getCurrentPostId()
        };

        // Send AJAX request
        jQuery.post(pinnerpressVars.ajaxurl, data, function(response) {
            if (response.success) {
                pinnerpressDebugLog('PinnerPress Analytics: Block editor event tracked successfully', eventType, eventData);
            } else {
                pinnerpressDebugLog('PinnerPress Analytics: Failed to track block editor event', response);
            }
        }).fail(function() {
            pinnerpressDebugLog('PinnerPress Analytics: Block editor AJAX request failed');
        });
    }
    
    // Debug information - log to confirm script is loading
    pinnerpressDebugLog('PinnerPress block editor script loaded');
    
    const { __ } = wp.i18n;
    const { createHigherOrderComponent } = wp.compose;
    const { Fragment } = wp.element;
    const { InspectorControls } = wp.blockEditor;
    const { PanelBody, TextControl, TextareaControl, ToggleControl } = wp.components;
    const { addFilter } = wp.hooks;
    
    /**
     * Add Pinterest attributes to the image block
     */
    const addPinterestAttributes = (settings, name) => {
        // Only add attributes to image block
        if (name !== 'core/image') {
            return settings;
        }
        
        // Add custom attributes
        settings.attributes = {
            ...settings.attributes,
            pinterestTitle: {
                type: 'string',
                default: '',
            },
            pinterestText: {
                type: 'string',
                default: '',
            },
            pinterestRepinId: {
                type: 'string',
                default: '',
            },
            pinterestDisablePinning: {
                type: 'boolean',
                default: false,
            }
        };
        
        return settings;
    };
    
    /**
     * Add Pinterest controls to the image block sidebar
     */
    const withPinterestControls = createHigherOrderComponent((BlockEdit) => {
        return (props) => {
            // Only add controls to image block
            if (props.name !== 'core/image') {
                return wp.element.createElement(BlockEdit, props);
            }
            
            const {
                attributes: {
                    pinterestTitle,
                    pinterestText,
                    pinterestRepinId,
                    pinterestDisablePinning
                },
                setAttributes
            } = props;
            
            return wp.element.createElement(
                Fragment,
                null,
                wp.element.createElement(BlockEdit, props),
                wp.element.createElement(
                    InspectorControls,
                    null,
                    wp.element.createElement(
                        PanelBody,
                        {
                            title: __('PinnerPress', 'pinnerpress'),
                            initialOpen: true, // Open by default for better visibility
                            className: 'pinnerpress-image-settings'
                        },
                        wp.element.createElement(TextControl, {
                            label: __('Pinterest Title', 'pinnerpress'),
                            value: pinterestTitle || '',
                            onChange: (value) => {
                                setAttributes({ pinterestTitle: value });
                                // Track analytics event
                                pinnerpressTrackBlockEditorEvent('pinterest_title_changed', { value: value });
                            },
                            help: __('100 characters remaining.', 'pinnerpress')
                        }),
                        wp.element.createElement(TextareaControl, {
                            label: __('Pinterest Text', 'pinnerpress'),
                            value: pinterestText || '',
                            onChange: (value) => {
                                setAttributes({ pinterestText: value });
                                // Track analytics event
                                pinnerpressTrackBlockEditorEvent('pinterest_description_changed', { value: value });
                            },
                            help: __('500 characters remaining.', 'pinnerpress')
                        }),
                        wp.element.createElement(TextControl, {
                            label: __('Pinterest Repin ID', 'pinnerpress'),
                            value: pinterestRepinId || '',
                            onChange: (value) => {
                                setAttributes({ pinterestRepinId: value });
                                // Track analytics event
                                pinnerpressTrackBlockEditorEvent('pinterest_repin_id_changed', { value: value });
                            }
                        }),
                        wp.element.createElement(ToggleControl, {
                            label: __('Disable Pinning', 'pinnerpress'),
                            checked: !!pinterestDisablePinning,
                            onChange: (value) => {
                                setAttributes({ pinterestDisablePinning: value });
                                // Track analytics event
                                pinnerpressTrackBlockEditorEvent('pinterest_disable_pinning_toggled', { disabled: value });
                            }
                        })
                    )
                )
            );
        };
    }, 'withPinterestControls');
    
    /**
     * Save Pinterest attributes as HTML attributes on the image element
     */
    const savePinterestAttributes = (extraProps, blockType, attributes) => {
        // Only add attributes to image block
        if (blockType.name !== 'core/image') {
            return extraProps;
        }
        
        const {
            pinterestTitle,
            pinterestText,
            pinterestRepinId,
            pinterestDisablePinning
        } = attributes;
        
        // Add custom attributes to the saved element
        if (pinterestTitle) {
            extraProps['data-pin-title'] = pinterestTitle;
        }
        
        if (pinterestText) {
            extraProps['data-pin-description'] = pinterestText;
        }
        
        if (pinterestRepinId) {
            extraProps['data-pin-id'] = pinterestRepinId;
        }
        
        if (pinterestDisablePinning) {
            extraProps['data-pin-nopin'] = 'true';
        }
        
        return extraProps;
    };
    
    // Register the filters
    addFilter(
        'blocks.registerBlockType',
        'pinnerpress/pinterest-attributes',
        addPinterestAttributes
    );
    pinnerpressDebugLog('PinnerPress: Registered attribute filter');
    
    addFilter(
        'editor.BlockEdit',
        'pinnerpress/pinterest-controls',
        withPinterestControls
    );
    pinnerpressDebugLog('PinnerPress: Registered control filter');
    
    addFilter(
        'blocks.getSaveContent.extraProps',
        'pinnerpress/save-pinterest-attributes',
        savePinterestAttributes
    );
    pinnerpressDebugLog('PinnerPress: Registered save filter');
    
})(window.wp); 