/**
 * AIEO Newsletter Signup — block editor registration with full per-instance
 * controls + a live preview. Pairs with the server-side render in
 * class-aieo-dmm-newsletter-signup.php; the block is self-contained (its own
 * attributes drive the front-end render), while the admin page under Storefront
 * Display → Discoverability drives the [aieo_newsletter_signup] shortcode.
 *
 * Attribute defaults come from PHP via wp_localize_script (window.aieoNewsletterCfg).
 */

(function (wp) {
    if (!wp || !wp.blocks || !wp.blockEditor || !wp.components || !wp.element) { return; }

    var el       = wp.element.createElement;
    var Fragment = wp.element.Fragment;
    var __       = (wp.i18n && wp.i18n.__) ? wp.i18n.__ : function (s) { return s; };

    var InspectorControls = wp.blockEditor.InspectorControls;
    var useBlockProps     = wp.blockEditor.useBlockProps;
    var MediaUpload       = wp.blockEditor.MediaUpload;
    var MediaUploadCheck  = wp.blockEditor.MediaUploadCheck;

    var PanelBody       = wp.components.PanelBody;
    var TextControl     = wp.components.TextControl;
    var TextareaControl = wp.components.TextareaControl;
    var ToggleControl   = wp.components.ToggleControl;
    var SelectControl   = wp.components.SelectControl;
    var Button          = wp.components.Button;

    var cfg      = (typeof window !== 'undefined' && window.aieoNewsletterCfg) || { defaults: {} };
    var defaults = cfg.defaults || {};

    var BOOL_KEYS = ['collect_name', 'glass_mobile', 'sso_enabled'];
    var NUM_KEYS  = ['logo_id', 'bg_desktop_image_id', 'bg_mobile_image_id', 'gravity_form_id'];
    function coerce(k, v) {
        if (BOOL_KEYS.indexOf(k) >= 0) { return (v === true || v === 1 || v === '1'); }
        if (NUM_KEYS.indexOf(k) >= 0)  { return parseInt(v, 10) || 0; }
        return (v === null || v === undefined) ? '' : v;
    }

    // Build block attributes from the PHP defaults (single source of truth).
    var attributes = { align: { type: 'string' } };
    Object.keys(defaults).forEach(function (k) {
        if (k === 'enabled') { return; }
        var t = (BOOL_KEYS.indexOf(k) >= 0) ? 'boolean' : (NUM_KEYS.indexOf(k) >= 0 ? 'number' : 'string');
        attributes[k] = { type: t, default: coerce(k, defaults[k]) };
    });

    function imageControl(label, idKey, urlKey, a, set) {
        return el('div', { style: { marginBottom: '14px' } },
            el('p', { style: { margin: '0 0 4px', fontSize: '11px', fontWeight: 600, textTransform: 'uppercase', color: '#757575' } }, label),
            el(MediaUploadCheck, null,
                el(MediaUpload, {
                    onSelect: function (m) { var o = {}; o[idKey] = m.id; o[urlKey] = m.url; set(o); },
                    allowedTypes: ['image'],
                    value: a[idKey],
                    render: function (open) { return el(Button, { variant: 'secondary', onClick: open.open }, a[idKey] ? __('Change', 'ai-eshop-optimizer') : __('Choose image', 'ai-eshop-optimizer')); }
                })
            ),
            a[idKey] ? el(Button, { variant: 'link', isDestructive: true, style: { marginLeft: '8px' }, onClick: function () { var o = {}; o[idKey] = 0; o[urlKey] = ''; set(o); } }, __('Remove', 'ai-eshop-optimizer')) : null,
            a[urlKey] ? el('img', { src: a[urlKey], style: { display: 'block', maxHeight: '48px', marginTop: '6px', borderRadius: '4px' } }) : null
        );
    }

    wp.blocks.registerBlockType('aieo/newsletter-signup', {
        title:       __('AIEO Newsletter Signup', 'ai-eshop-optimizer'),
        category:    'theme',
        icon:        'email',
        description: __('Theme-independent newsletter signup banner — fully configurable here in the block.', 'ai-eshop-optimizer'),
        keywords:    ['newsletter', 'signup', 'email', 'subscribe', 'aieo'],
        supports:    { align: ['wide', 'full'], html: false, spacing: { margin: true, padding: true }, typography: { fontSize: true, lineHeight: true }, color: { background: true, text: true } },
        attributes:  attributes,

        edit: function (props) {
            var a = props.attributes, set = props.setAttributes;
            var blockProps = useBlockProps({ className: 'aieo-newsletter-signup-editor' });

            var providerOptions = [
                { value: 'newsletter', label: __('Newsletter provider (configured under Newsletter/Push)', 'ai-eshop-optimizer') },
                { value: 'gravity',    label: __('Gravity Form (embed by ID)', 'ai-eshop-optimizer') },
                { value: 'none',       label: __('Collect only (fires the hook)', 'ai-eshop-optimizer') }
            ];

            var inspector = el(InspectorControls, null,
                el(PanelBody, { title: __('Content', 'ai-eshop-optimizer'), initialOpen: true },
                    el(TextControl,     { label: __('Heading', 'ai-eshop-optimizer'), value: a.heading || '', onChange: function (v) { set({ heading: v }); } }),
                    el(TextareaControl, { label: __('Intro text', 'ai-eshop-optimizer'), value: a.intro || '', onChange: function (v) { set({ intro: v }); } }),
                    el(TextControl,     { label: __('Button text', 'ai-eshop-optimizer'), value: a.button_text || '', onChange: function (v) { set({ button_text: v }); } }),
                    el(TextControl,     { label: __('Email placeholder', 'ai-eshop-optimizer'), value: a.placeholder || '', onChange: function (v) { set({ placeholder: v }); } }),
                    el(TextControl,     { label: __('Success message', 'ai-eshop-optimizer'), value: a.success_msg || '', onChange: function (v) { set({ success_msg: v }); } }),
                    el(ToggleControl,   { label: __('Collect name too', 'ai-eshop-optimizer'), checked: !!a.collect_name, onChange: function (v) { set({ collect_name: !!v }); } }),
                    imageControl(__('Company logo', 'ai-eshop-optimizer'), 'logo_id', 'logo_url', a, set)
                ),
                el(PanelBody, { title: __('Appearance', 'ai-eshop-optimizer'), initialOpen: false },
                    el(TextControl, { label: __('Background colour — desktop (hex)', 'ai-eshop-optimizer'), value: a.bg_desktop_color || '', onChange: function (v) { set({ bg_desktop_color: v }); } }),
                    imageControl(__('Background image — desktop', 'ai-eshop-optimizer'), 'bg_desktop_image_id', 'bg_desktop_url', a, set),
                    el(TextControl, { label: __('Background colour — mobile (hex)', 'ai-eshop-optimizer'), value: a.bg_mobile_color || '', onChange: function (v) { set({ bg_mobile_color: v }); } }),
                    imageControl(__('Background image — mobile', 'ai-eshop-optimizer'), 'bg_mobile_image_id', 'bg_mobile_url', a, set),
                    el(ToggleControl, { label: __('Glass effect (mobile)', 'ai-eshop-optimizer'), checked: !!a.glass_mobile, onChange: function (v) { set({ glass_mobile: !!v }); } }),
                    el(TextControl, { label: __('Text colour (hex)', 'ai-eshop-optimizer'), value: a.text_color || '', onChange: function (v) { set({ text_color: v }); } }),
                    el(TextControl, { label: __('Accent / button colour (hex)', 'ai-eshop-optimizer'), value: a.accent_color || '', onChange: function (v) { set({ accent_color: v }); } })
                ),
                el(PanelBody, { title: __('Integration', 'ai-eshop-optimizer'), initialOpen: false },
                    el(SelectControl, { label: __('Submit to', 'ai-eshop-optimizer'), value: a.provider_mode || 'newsletter', options: providerOptions, onChange: function (v) { set({ provider_mode: v }); } }),
                    (a.provider_mode === 'gravity') ? el(TextControl, { label: __('Gravity Form ID', 'ai-eshop-optimizer'), type: 'number', value: String(a.gravity_form_id || 0), onChange: function (v) { set({ gravity_form_id: parseInt(v, 10) || 0 }); } }) : null,
                    el(ToggleControl, { label: __('SSO auto-registration buttons', 'ai-eshop-optimizer'), checked: !!a.sso_enabled, onChange: function (v) { set({ sso_enabled: !!v }); } })
                )
            );

            var previewStyle = {
                background: a.bg_desktop_color || '#111111',
                color: a.text_color || '#ffffff',
                padding: '36px 22px', borderRadius: '8px', textAlign: 'center',
                backgroundSize: 'cover', backgroundPosition: 'center',
                backgroundImage: a.bg_desktop_url ? ('linear-gradient(rgba(0,0,0,.35),rgba(0,0,0,.35)),url(' + a.bg_desktop_url + ')') : 'none'
            };
            var formRow = (a.provider_mode === 'gravity')
                ? el('em', { style: { opacity: .85 } }, '[ Gravity Form #' + (a.gravity_form_id || 0) + ' ]')
                : el('div', { style: { display: 'flex', gap: '8px', justifyContent: 'center', flexWrap: 'wrap' } },
                    a.collect_name ? el('input', { type: 'text', placeholder: __('Name', 'ai-eshop-optimizer'), disabled: true, style: { padding: '11px 14px', borderRadius: '999px', border: 0 } }) : null,
                    el('input', { type: 'email', placeholder: a.placeholder || '', disabled: true, style: { padding: '11px 14px', borderRadius: '999px', border: 0, minWidth: '180px' } }),
                    el('button', { type: 'button', disabled: true, style: { padding: '11px 24px', borderRadius: '999px', border: 0, background: a.accent_color || '#c82d52', color: '#fff', fontWeight: 700 } }, a.button_text || '')
                );
            var preview = el('div', { style: previewStyle },
                a.logo_url ? el('img', { src: a.logo_url, style: { maxHeight: '46px', margin: '0 auto 12px', display: 'block' } }) : null,
                a.heading ? el('h3', { style: { margin: '0 0 6px', color: 'inherit' } }, a.heading) : null,
                a.intro ? el('p', { style: { margin: '0 0 16px', opacity: .92, color: 'inherit' } }, a.intro) : null,
                formRow,
                a.sso_enabled ? el('p', { style: { marginTop: '14px', fontSize: '12px', opacity: .85, color: 'inherit' } }, __('+ Google / Facebook sign-up buttons', 'ai-eshop-optimizer')) : null
            );

            return el(Fragment, null, inspector, el('div', blockProps, preview));
        },

        save: function () { return null; }
    });
})(window.wp);
