/**
 * audace/expertise-showcase — 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 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 __NumberControl     = wp.components.__experimentalNumberControl || wp.components.NumberControl;
    var __UnitControl       = wp.components.__experimentalUnitControl   || wp.components.UnitControl;
    var useSelect           = wp.data.useSelect;

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

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

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

            var blockProps = useBlockProps({
                className: 'audace-expertise-showcase is-style-slide',
                style: {
                    '--audace-expertise-left': a.leftColumnWidth,
                    '--audace-expertise-gap':  a.columnGap,
                    '--audace-expertise-panel-padding': a.panelPadding,
                    '--audace-expertise-panel-gap': a.panelGap,
                    '--audace-exp-left':        a.leftColFr + 'fr',
                    '--audace-exp-right':       a.rightColFr + 'fr',
                    '--audace-exp-left-pad-x':  spacingVar(a.leftColPadX),
                    '--audace-exp-left-pad-y':  spacingVar(a.leftColPadY),
                    '--audace-exp-right-pad-x': spacingVar(a.rightColPadX),
                    '--audace-exp-right-pad-y': spacingVar(a.rightColPadY)
                }
            });

            var tabList = el('ul', { className: 'audace-expertise-tabs' },
                (posts.length ? posts : [{ id: 0, title: { rendered: __('(aucune expertise)', 'audace') } }]).map(function (p, i) {
                    return el('li', { key: p.id || i },
                        el('button', {
                            type: 'button',
                            className: 'audace-expertise-tab' + (i === 0 ? ' is-active' : ''),
                            disabled: true
                        }, (p.title && (p.title.rendered || p.title)) || __('(sans titre)', 'audace'))
                    );
                })
            );

            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 inspector = el(InspectorControls, null,
                el(PanelBody, { title: __('Contenu', 'audace'), initialOpen: true },
                    el(TextControl, {
                        label: __('Titre', 'audace'),
                        value: a.heading,
                        onChange: function (v) { props.setAttributes({ heading: v }); }
                    }),
                    el(TextControl, {
                        label: __('Suffixe du compteur', 'audace'),
                        value: a.countSuffix,
                        onChange: function (v) { props.setAttributes({ countSuffix: v }); }
                    }),
                    __NumberControl ? el(__NumberControl, {
                        label: __('Nombre max (0 = tous)', 'audace'),
                        value: a.maxItems,
                        min: 0,
                        onChange: function (v) { props.setAttributes({ maxItems: parseInt(v, 10) || 0 }); }
                    }) : null
                ),
                el(PanelBody, { title: __('Mise en page', 'audace'), initialOpen: false },
                    __UnitControl ? el(__UnitControl, {
                        label: __('Largeur colonne gauche', 'audace'),
                        value: a.leftColumnWidth,
                        units: [{value:'%',label:'%'},{value:'px',label:'px'},{value:'rem',label:'rem'}],
                        onChange: function (v) { props.setAttributes({ leftColumnWidth: v || '40%' }); }
                    }) : el(TextControl, {
                        label: __('Largeur colonne gauche', 'audace'),
                        value: a.leftColumnWidth,
                        onChange: function (v) { props.setAttributes({ leftColumnWidth: v }); }
                    }),
                    __UnitControl ? el(__UnitControl, {
                        label: __('Gouttière entre colonnes', 'audace'),
                        value: a.columnGap,
                        units: [{value:'px',label:'px'},{value:'rem',label:'rem'},{value:'em',label:'em'},{value:'%',label:'%'}],
                        onChange: function (v) { props.setAttributes({ columnGap: v || '2rem' }); }
                    }) : el(TextControl, {
                        label: __('Gouttière entre colonnes', 'audace'),
                        value: a.columnGap,
                        onChange: function (v) { props.setAttributes({ columnGap: v }); }
                    }),
                    __UnitControl ? el(__UnitControl, {
                        label: __('Marge interne du panneau', 'audace'),
                        value: a.panelPadding,
                        units: [{value:'px',label:'px'},{value:'rem',label:'rem'},{value:'em',label:'em'},{value:'%',label:'%'}],
                        onChange: function (v) { props.setAttributes({ panelPadding: v || '0px' }); }
                    }) : null,
                    __UnitControl ? el(__UnitControl, {
                        label: __('Espacement image / texte', 'audace'),
                        value: a.panelGap,
                        units: [{value:'px',label:'px'},{value:'rem',label:'rem'},{value:'em',label:'em'},{value:'%',label:'%'}],
                        onChange: function (v) { props.setAttributes({ panelGap: v || '1.5rem' }); }
                    }) : 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'),
                        help:  __('Après le dernier, revient au premier.', 'audace'),
                        checked: !!a.loopArrows,
                        onChange: function (v) { props.setAttributes({ loopArrows: !!v }); }
                    })
                )
            );

            return el(Fragment, null,
                inspector,
                el('section', blockProps,
                    el('div', { className: 'audace-expertise-showcase__left' },
                        el('h2', { className: 'audace-expertise-showcase__heading' }, a.heading),
                        el('p', { className: 'audace-expertise-showcase__count' },
                            el('span', { className: 'audace-expertise-showcase__count-n' }, String(posts.length)),
                            ' ',
                            el('span', { className: 'audace-expertise-showcase__count-label' }, a.countSuffix)
                        ),
                        tabList
                    ),
                    el('div', { className: 'audace-expertise-showcase__right' },
                        el('div', { className: 'audace-expertise-stage' },
                            el('article', { className: 'audace-expertise-panel is-active' },
                                thumbUrl
                                    ? el('figure', { className: 'audace-expertise-panel__figure' },
                                        el('img', { src: thumbUrl, alt: '' })
                                    )
                                    : null,
                                el('div', { className: 'audace-expertise-panel__content' },
                                    first
                                        ? el('p', null, __('Aperçu : contenu du premier post affiché côté front.', 'audace'))
                                        : el('p', null, __('Créez des posts « Expertise » pour les afficher ici.', 'audace'))
                                )
                            )
                        ),
                        el('nav', { className: 'audace-expertise-arrows' },
                            el('button', { type: 'button', className: 'audace-expertise-arrow audace-expertise-arrow--prev', disabled: true },
                                el('img', { src: themeUri + '/assets/images/audace-fleche-gauche.svg', alt: '' })
                            ),
                            el('button', { type: 'button', className: 'audace-expertise-arrow audace-expertise-arrow--next', disabled: true },
                                el('img', { src: themeUri + '/assets/images/audace-fleche-droite.svg', alt: '' })
                            )
                        )
                    )
                )
            );
        },
        save: function () { return null; }
    });
})(window.wp);
