/**
 * audace/production — editor preview + inspector.
 */
(function (wp) {
    'use strict';
    var el       = wp.element.createElement;
    var Fragment = wp.element.Fragment;
    var __       = (wp.i18n && wp.i18n.__) ? wp.i18n.__ : function (s) { return s; };
    var useBlockProps     = wp.blockEditor.useBlockProps;
    var InspectorControls = wp.blockEditor.InspectorControls;
    var PanelBody         = wp.components.PanelBody;
    var TextControl       = wp.components.TextControl;
    var ToggleControl     = wp.components.ToggleControl;
    var RangeControl      = wp.components.RangeControl;
    var SelectControl     = wp.components.SelectControl;
    var __NumberControl   = wp.components.__experimentalNumberControl || wp.components.NumberControl;

    // theme.json spacing scale (operator *, increment 1.5, mediumStep 1.5rem):
    // slug 20 ≈ 0.44rem  /  30 ≈ 0.67rem  /  40 = 1rem  /  50 = 1.5rem  /
    // 60 ≈ 2.25rem  /  70 ≈ 3.4rem  /  80 ≈ 5rem.
    var SPACING_OPTIONS = [
        { label: '— Aucune —',    value: '0'  },
        { label: '20 (≈0.44rem)', value: '20' },
        { label: '30 (≈0.67rem)', value: '30' },
        { label: '40 (1rem)',     value: '40' },
        { label: '50 (1.5rem)',   value: '50' },
        { label: '60 (≈2.25rem)', value: '60' },
        { label: '70 (≈3.4rem)',  value: '70' },
        { label: '80 (≈5rem)',    value: '80' }
    ];
    function spacingVar(n) {
        var v = parseInt(n, 10) || 0;
        return v ? 'var(--wp--preset--spacing--' + v + ')' : '0';
    }
    var useSelect         = wp.data.useSelect;

    var themeUri = (window.AudaceBlocks && window.AudaceBlocks.themeUri) || '';

    wp.blocks.registerBlockType('audace/productions-showcase', {
        edit: function (props) {
            var a = props.attributes;

            var posts = useSelect(function (select) {
                return select('core').getEntityRecords('postType', 'production', {
                    per_page: -1,
                    orderby: 'menu_order',
                    order:   'asc',
                    _embed:  true,
                    status:  ['publish', 'private', 'draft']
                }) || [];
            }, []);

            var blockProps = useBlockProps({
                className: 'audace-production is-style-slide',
                style: {
                    '--audace-prod-left':        a.leftColFr + 'fr',
                    '--audace-prod-right':       a.rightColFr + 'fr',
                    '--audace-prod-left-pad-x':  spacingVar(a.leftColPadX),
                    '--audace-prod-left-pad-y':  spacingVar(a.leftColPadY),
                    '--audace-prod-right-pad-x': spacingVar(a.rightColPadX),
                    '--audace-prod-right-pad-y': spacingVar(a.rightColPadY)
                }
            });

            var first = posts[0] || null;
            var thumbUrl = '';
            if (first && first._embedded && first._embedded['wp:featuredmedia'] && first._embedded['wp:featuredmedia'][0]) {
                var m = first._embedded['wp:featuredmedia'][0];
                thumbUrl = (m.media_details && m.media_details.sizes && (m.media_details.sizes.large || m.media_details.sizes.medium_large || m.media_details.sizes.medium) || {}).source_url || m.source_url || '';
            }
            var title = (first && first.title && (first.title.rendered || first.title)) || __('(aucune production)', 'audace');
            var contentHtml = (first && first.content && (first.content.rendered || first.content)) || '';

            var inspector = el(InspectorControls, null,
                el(PanelBody, { title: __('Contenu', 'audace'), initialOpen: true },
                    el(TextControl, {
                        label: __('Titre interne', 'audace'),
                        value: a.heading,
                        onChange: function (v) { props.setAttributes({ heading: v }); }
                    }),
                    el(TextControl, {
                        label: __('Libellé du téléchargement', 'audace'),
                        value: a.downloadLabel,
                        onChange: function (v) { props.setAttributes({ downloadLabel: v }); }
                    }),
                    __NumberControl ? el(__NumberControl, {
                        label: __('Nombre max (0 = toutes)', 'audace'),
                        value: a.maxItems,
                        min: 0,
                        onChange: function (v) { props.setAttributes({ maxItems: parseInt(v, 10) || 0 }); }
                    }) : null
                ),
                el(PanelBody, { title: __('Colonnes', 'audace'), initialOpen: false },
                    el(RangeControl, {
                        label: __('Largeur colonne gauche (fr)', 'audace'),
                        value: a.leftColFr, min: 0, max: 10, step: 0.1,
                        onChange: function (v) { props.setAttributes({ leftColFr: typeof v === 'number' ? v : 1 }); }
                    }),
                    el(RangeControl, {
                        label: __('Largeur colonne droite (fr)', 'audace'),
                        value: a.rightColFr, min: 0, max: 10, step: 0.1,
                        onChange: function (v) { props.setAttributes({ rightColFr: typeof v === 'number' ? v : 1 }); }
                    }),
                    el(SelectControl, {
                        label: __('Gauche — marge latérale', 'audace'),
                        value: String(a.leftColPadX),
                        options: SPACING_OPTIONS,
                        onChange: function (v) { props.setAttributes({ leftColPadX: parseInt(v, 10) || 0 }); }
                    }),
                    el(SelectControl, {
                        label: __('Gauche — marge verticale', 'audace'),
                        value: String(a.leftColPadY),
                        options: SPACING_OPTIONS,
                        onChange: function (v) { props.setAttributes({ leftColPadY: parseInt(v, 10) || 0 }); }
                    }),
                    el(SelectControl, {
                        label: __('Droite — marge latérale', 'audace'),
                        value: String(a.rightColPadX),
                        options: SPACING_OPTIONS,
                        onChange: function (v) { props.setAttributes({ rightColPadX: parseInt(v, 10) || 0 }); }
                    }),
                    el(SelectControl, {
                        label: __('Droite — marge verticale', 'audace'),
                        value: String(a.rightColPadY),
                        options: SPACING_OPTIONS,
                        onChange: function (v) { props.setAttributes({ rightColPadY: parseInt(v, 10) || 0 }); }
                    })
                ),
                el(PanelBody, { title: __('Navigation', 'audace'), initialOpen: false },
                    el(ToggleControl, {
                        label: __('Flèches en boucle', 'audace'),
                        checked: !!a.loopArrows,
                        onChange: function (v) { props.setAttributes({ loopArrows: !!v }); }
                    })
                )
            );

            return el(Fragment, null,
                inspector,
                el('section', blockProps,
                    el('div', { className: 'audace-production__stage' },
                        el('article', { className: 'audace-production__slide is-active' },
                            el('div', { className: 'audace-production__media' },
                                thumbUrl
                                    ? el('figure', { className: 'audace-production__figure' },
                                        el('img', { src: thumbUrl, alt: '', className: 'audace-production__img' })
                                    )
                                    : el('div', { className: 'audace-production__figure audace-production__figure--empty' })
                            ),
                            el('div', { className: 'audace-production__body' },
                                el('h2', { className: 'audace-production__title' }, title),
                                contentHtml
                                    ? el('div', { className: 'audace-production__content', dangerouslySetInnerHTML: { __html: contentHtml } })
                                    : null
                            ),
                            el('div', { className: 'audace-production__footer' },
                                el('a', { className: 'audace-production__download', href: '#', onClick: function (e) { e.preventDefault(); } },
                                    el('span', { className: 'audace-production__download-label' }, a.downloadLabel || 'télécharger'),
                                    el('img', { src: themeUri + '/assets/images/audace-fleche-telechargement.svg', alt: '' })
                                ),
                                el('nav', { className: 'audace-production__arrows' },
                                    el('button', { type: 'button', className: 'audace-production__arrow audace-production__arrow--prev', disabled: true },
                                        el('img', { src: themeUri + '/assets/images/audace-fleche-gauche.svg', alt: '' })
                                    ),
                                    el('button', { type: 'button', className: 'audace-production__arrow audace-production__arrow--next', disabled: true },
                                        el('img', { src: themeUri + '/assets/images/audace-fleche-droite.svg', alt: '' })
                                    )
                                )
                            )
                        )
                    )
                )
            );
        },
        save: function () { return null; }
    });
})(window.wp);
