/**
 * Product Display Gutenberg Blocks
 * Complete integration with showcase functionality
 */

const { registerBlockType } = wp.blocks;
const { __ } = wp.i18n;
const { InspectorControls, BlockControls, AlignmentToolbar } = wp.blockEditor;
const {
    PanelBody,
    SelectControl,
    ToggleControl,
    RangeControl,
    TextControl,
    Button,
    Placeholder,
    Notice,
    Disabled
} = wp.components;
const { Fragment, useState, useEffect } = wp.element;

// Check if pro is active (passed from PHP)
const isProActive = window.proddispGutenberg && window.proddispGutenberg.isProActive;

/**
 * Pro Lock Component for Gutenberg
 */
function ProLock({ featureName, description }) {
    const showUpgradeModal = () => {
        if (typeof window.proddispUpgradeModal !== "undefined") {
            window.proddispUpgradeModal.show();
        } else {
            // Fallback - open upgrade page
            window.open(window.proddispGutenberg?.upgradeUrl || '#', '_blank');
        }
    };

    return wp.element.createElement('div', {
        style: {
            background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
            padding: '20px',
            borderRadius: '8px',
            textAlign: 'center',
            border: '2px dashed #dee2e6',
            position: 'relative',
            overflow: 'hidden'
        }
    },
        wp.element.createElement('div', {
            style: {
                background: '#6c757d',
                color: 'white',
                width: '48px',
                height: '48px',
                borderRadius: '50%',
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: '12px',
                fontSize: '20px'
            }
        }, '🔒'),
        wp.element.createElement('h3', {
            style: {
                margin: '0 0 12px 0',
                color: '#495057',
                fontSize: '18px',
                fontWeight: '600'
            }
        }, `${featureName} (Pro Feature)`),
        wp.element.createElement('p', {
            style: {
                color: '#6c757d',
                margin: '0 0 20px 0',
                fontSize: '14px',
                lineHeight: '1.5'
            }
        }, description),
        wp.element.createElement(Button, {
            isPrimary: true,
            onClick: showUpgradeModal,
            style: {
                background: 'linear-gradient(135deg, #007cba 0%, #005a87 100%)',
                borderColor: '#007cba'
            }
        }, '🚀 ' + __('Upgrade to Pro', 'product-display'))
    );
}

/**
 * Enhanced Icon Selector Component
 */
function IconSelector(props) {
    const { label, value, onChange, context } = props;

    const getIconOptions = () => {
        const contextIcons = {
            'addtocart': [
                { value: 'fas fa-shopping-cart', label: 'Shopping Cart' },
                { value: 'fas fa-shopping-bag', label: 'Shopping Bag' },
                { value: 'fas fa-cart-plus', label: 'Add to Cart' },
                { value: 'fas fa-cart-arrow-down', label: 'Cart Download' },
                { value: 'fas fa-shopping-basket', label: 'Shopping Basket' }
            ],
            'wishlist': [
                { value: 'fas fa-heart', label: 'Heart' },
                { value: 'far fa-heart', label: 'Heart Outline' },
                { value: 'fas fa-bookmark', label: 'Bookmark' },
                { value: 'far fa-bookmark', label: 'Bookmark Outline' },
                { value: 'fas fa-star', label: 'Star' },
                { value: 'far fa-star', label: 'Star Outline' }
            ],
            'compare': [
                { value: 'fas fa-balance-scale', label: 'Balance Scale' },
                { value: 'fas fa-balance-scale-left', label: 'Balance Scale Left' },
                { value: 'fas fa-balance-scale-right', label: 'Balance Scale Right' },
                { value: 'fas fa-chart-bar', label: 'Chart Bar' },
                { value: 'fas fa-exchange-alt', label: 'Exchange' },
                { value: 'fas fa-random', label: 'Random' }
            ],
            'quickview': [
                { value: 'fas fa-eye', label: 'Eye' },
                { value: 'far fa-eye', label: 'Eye Outline' },
                { value: 'fas fa-search', label: 'Search' },
                { value: 'fas fa-search-plus', label: 'Search Plus' },
                { value: 'fas fa-expand', label: 'Expand' },
                { value: 'fas fa-external-link-alt', label: 'External Link' }
            ]
        };

        const commonIcons = [
            { value: 'fas fa-plus', label: 'Plus' },
            { value: 'fas fa-minus', label: 'Minus' },
            { value: 'fas fa-times', label: 'Times' },
            { value: 'fas fa-check', label: 'Check' },
            { value: 'fas fa-arrow-right', label: 'Arrow Right' },
            { value: 'fas fa-arrow-left', label: 'Arrow Left' },
            { value: 'fas fa-share', label: 'Share' },
            { value: 'fas fa-user', label: 'User' },
            { value: 'fas fa-cog', label: 'Settings' },
            { value: 'fas fa-info', label: 'Info' }
        ];

        const options = [{ value: '', label: __('Select Icon', 'product-display') }];

        if (context && contextIcons[context]) {
            options.push(...contextIcons[context]);
        }

        options.push(...commonIcons);
        return options;
    };

    return wp.element.createElement('div', {
        className: 'proddisp-icon-selector',
        style: { marginBottom: '16px' }
    },
        wp.element.createElement('label', {
            className: 'components-base-control__label',
            style: { marginBottom: '8px', display: 'block', fontWeight: '600' }
        }, label),
        wp.element.createElement('div', {
            style: { display: 'flex', alignItems: 'center', gap: '12px' }
        },
            wp.element.createElement(SelectControl, {
                value: value || '',
                options: getIconOptions(),
                onChange: onChange,
                style: { flex: 1 },
                __next40pxDefaultSize: true,
                __nextHasNoMarginBottom: true
            }),
            value && wp.element.createElement('div', {
                style: {
                    padding: '8px 12px',
                    background: '#f0f6fc',
                    border: '1px solid #2271b1',
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    minWidth: '40px'
                }
            },
                wp.element.createElement('i', {
                    className: value,
                    style: { fontSize: '16px', color: '#2271b1' }
                })
            )
        )
    );
}

/**
 * Product Showcase Block
 */
registerBlockType('product-display/showcase', {
    title: __('Product Showcase', 'product-display'),
    description: __('Display products using a saved Product Display showcase with customizable settings.', 'product-display'),
    icon: 'products',
    category: 'product-display',
    keywords: [
        __('product', 'product-display'),
        __('showcase', 'product-display'),
        __('woocommerce', 'product-display'),
        __('shop', 'product-display'),
        __('display', 'product-display')
    ],
    supports: {
        align: ['left', 'center', 'right', 'wide', 'full'],
        html: false
    },
    attributes: {
        showcaseId: {
            type: 'string',
            default: ''
        },
        overrideLimit: {
            type: 'boolean',
            default: false
        },
        limit: {
            type: 'number',
            default: 4
        },
        overrideColumns: {
            type: 'boolean',
            default: false
        },
        columns: {
            type: 'number',
            default: 4
        },
        overrideOrderBy: {
            type: 'boolean',
            default: false
        },
        orderBy: {
            type: 'string',
            default: 'date'
        },
        order: {
            type: 'string',
            default: 'DESC'
        },
        overrideIcons: {
            type: 'boolean',
            default: false
        },
        addtocartIcon: {
            type: 'string',
            default: 'fas fa-shopping-cart'
        },
        wishlistIcon: {
            type: 'string',
            default: 'fas fa-heart'
        },
        compareIcon: {
            type: 'string',
            default: 'fas fa-balance-scale'
        },
        quickviewIcon: {
            type: 'string',
            default: 'fas fa-eye'
        },
        customCssClass: {
            type: 'string',
            default: ''
        },
        alignment: {
            type: 'string',
            default: 'none'
        }
    },

    edit: function (props) {
        const { attributes, setAttributes } = props;
        const {
            showcaseId,
            overrideLimit,
            limit,
            overrideColumns,
            columns,
            overrideOrderBy,
            orderBy,
            order,
            overrideIcons,
            addtocartIcon,
            wishlistIcon,
            compareIcon,
            quickviewIcon,
            customCssClass,
            alignment
        } = attributes;

        // Get showcases from localized data
        const showcases = (typeof proddispGutenberg !== 'undefined' && proddispGutenberg.showcases) ? proddispGutenberg.showcases : [];
        const showcaseOptions = [
            { value: '', label: __('Select a Product Showcase', 'product-display') }
        ].concat(showcases);

        const selectedShowcase = showcases.find(s => s.value === showcaseId);

        return wp.element.createElement(Fragment, null,
            // Block Controls
            wp.element.createElement(BlockControls, null,
                wp.element.createElement(AlignmentToolbar, {
                    value: alignment,
                    onChange: (newAlignment) => setAttributes({ alignment: newAlignment })
                })
            ),

            // Inspector Controls
            wp.element.createElement(InspectorControls, null,
                // Showcase Selection
                wp.element.createElement(PanelBody, {
                    title: __('Showcase Settings', 'product-display'),
                    initialOpen: true
                },
                    wp.element.createElement(SelectControl, {
                        label: __('Select Showcase', 'product-display'),
                        value: showcaseId,
                        options: showcaseOptions,
                        onChange: (value) => setAttributes({ showcaseId: value }),
                        help: __('Choose a saved showcase configuration to display', 'product-display'),
                        __next40pxDefaultSize: true,
                        __nextHasNoMarginBottom: true
                    }),

                    showcaseId && selectedShowcase && wp.element.createElement('div', {
                        className: 'showcase-info',
                        style: {
                            background: '#e8f5e8',
                            padding: '16px',
                            borderRadius: '6px',
                            margin: '16px 0',
                            fontSize: '13px',
                            border: '1px solid #46b450'
                        }
                    },
                        wp.element.createElement('h4', {
                            style: {
                                margin: '0 0 12px 0',
                                color: '#155724',
                                fontSize: '14px',
                                fontWeight: '600'
                            }
                        }, __('Showcase Information', 'product-display')),
                        wp.element.createElement('div', {
                            style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }
                        },
                            wp.element.createElement('p', { style: { margin: '0' } },
                                wp.element.createElement('strong', null, __('Layout:', 'product-display') + ' '),
                                selectedShowcase.layout || 'N/A'
                            ),
                            wp.element.createElement('p', { style: { margin: '0' } },
                                wp.element.createElement('strong', null, __('Mode:', 'product-display') + ' '),
                                selectedShowcase.mode || 'N/A'
                            ),
                            wp.element.createElement('p', { style: { margin: '0' } },
                                wp.element.createElement('strong', null, __('Columns:', 'product-display') + ' '),
                                selectedShowcase.columns || 'N/A'
                            ),
                            wp.element.createElement('p', { style: { margin: '0' } },
                                wp.element.createElement('strong', null, __('Limit:', 'product-display') + ' '),
                                selectedShowcase.limit || 'N/A'
                            )
                        )
                    ),

                    showcases.length === 0 && wp.element.createElement(Notice, {
                        status: 'warning',
                        isDismissible: false
                    },
                        wp.element.createElement('p', null, __('No showcases found. Create one first in Product Display settings.', 'product-display')),
                        typeof proddispGutenberg !== 'undefined' && proddispGutenberg.adminUrl && wp.element.createElement(Button, {
                            isSecondary: true,
                            href: proddispGutenberg.adminUrl,
                            target: '_blank',
                            style: { marginTop: '8px' }
                        }, __('Create Showcase', 'product-display'))
                    )
                ),

                // Override Settings (Pro Feature)
                showcaseId && wp.element.createElement(PanelBody, {
                    title: __('Override Settings', 'product-display') + (!isProActive ? ' (Pro)' : ''),
                    initialOpen: false
                },
                    !isProActive ? 
                        wp.element.createElement(ProLock, {
                            featureName: __('Override Settings', 'product-display'),
                            description: __('Override showcase settings like product limit, columns, and ordering for this block instance.', 'product-display')
                        }) :
                        wp.element.createElement('p', {
                            style: {
                                background: '#e3f2fd',
                                padding: '12px',
                                borderRadius: '4px',
                                borderLeft: '4px solid #2196f3',
                                fontSize: '13px',
                                margin: '0 0 16px 0'
                            }
                        }, __('Override specific showcase settings for this block instance only.', 'product-display')),

                    isProActive && wp.element.createElement(ToggleControl, {
                        label: __('Override Product Limit', 'product-display'),
                        checked: overrideLimit,
                        onChange: (value) => setAttributes({ overrideLimit: value }),
                        help: __('Change the number of products displayed', 'product-display')
                    }),

                    isProActive && overrideLimit && wp.element.createElement(RangeControl, {
                        label: __('Product Limit', 'product-display'),
                        value: limit,
                        onChange: (value) => setAttributes({ limit: value }),
                        min: 1,
                        max: 50,
                        help: __('Number of products to display', 'product-display')
                    }),

                    isProActive && wp.element.createElement(ToggleControl, {
                        label: __('Override Columns', 'product-display'),
                        checked: overrideColumns,
                        onChange: (value) => setAttributes({ overrideColumns: value }),
                        help: __('Change the number of columns in the layout', 'product-display')
                    }),

                    isProActive && overrideColumns && wp.element.createElement(RangeControl, {
                        label: __('Columns', 'product-display'),
                        value: columns,
                        onChange: (value) => setAttributes({ columns: value }),
                        min: 1,
                        max: 6,
                        help: __('Number of columns to display products in', 'product-display')
                    }),

                    isProActive && wp.element.createElement(ToggleControl, {
                        label: __('Override Order By', 'product-display'),
                        checked: overrideOrderBy,
                        onChange: (value) => setAttributes({ overrideOrderBy: value }),
                        help: __('Change how products are sorted', 'product-display')
                    }),

                    isProActive && overrideOrderBy && wp.element.createElement(Fragment, null,
                        wp.element.createElement(SelectControl, {
                            label: __('Order By', 'product-display'),   
                            value: orderBy,
                            options: [
                                { value: 'date', label: __('Date', 'product-display') },
                                { value: 'title', label: __('Title', 'product-display') },
                                { value: 'price', label: __('Price', 'product-display') }
                            ],
                        }),
                            // Settings Summary
                            wp.element.createElement('div', {
                                style: {
                                    background: 'rgba(255,255,255,0.8)',
                                    padding: '12px',
                                    borderRadius: '6px',
                                    border: '1px solid #dee2e6',
                                    fontSize: '12px',
                                    color: '#6c757d'
                                }
                            },
                                wp.element.createElement('div', {
                                    style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: '8px' }
                                },
                                    wp.element.createElement('span', null,
                                        wp.element.createElement('strong', null, __('Products:', 'product-display') + ' '),
                                        overrideLimit ? limit : (selectedShowcase && selectedShowcase.limit ? parseInt(selectedShowcase.limit) : 4)
                                    ),
                                    wp.element.createElement('span', null,
                                        wp.element.createElement('strong', null, __('Order:', 'product-display') + ' '),
                                        overrideOrderBy ? orderBy : 'Default'
                                    ),
                                    overrideIcons && wp.element.createElement('span', null,
                                        wp.element.createElement('strong', null, __('Icons:', 'product-display') + ' '),
                                        'Custom'
                                    ),
                                    customCssClass && wp.element.createElement('span', null,
                                        wp.element.createElement('strong', null, __('CSS:', 'product-display') + ' '),
                                        customCssClass
                                    )
                                )
                            )
                        )
                    )
            )
        );
    },

    save: function () {
        // Server-side rendering
        return null;
    }
});

console.log('Product Display: Gutenberg showcase block registered successfully');