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

    var el = wp.element.createElement;
    var registerBlockType = wp.blocks.registerBlockType;
    var InspectorControls = wp.blockEditor.InspectorControls;
    var PanelBody = wp.components.PanelBody;
    var SelectControl = wp.components.SelectControl;
    var TextControl = wp.components.TextControl;
    var ToggleControl = wp.components.ToggleControl;

    registerBlockType('chess-podium/tournament', {
        apiVersion: 3,
        title: (window.chessPodiumBlockData && window.chessPodiumBlockData.labelBlockTitle) || 'Chess Podium Tournament',
        icon: 'awards',
        category: 'widgets',
        attributes: {
            tournamentId: { type: 'integer', default: 0 },
            round: { type: 'integer', default: 0 }
        },
        edit: function (props) {
            var attrs = props.attributes || {};
            var data = window.chessPodiumBlockData || {};
            var options = [{ label: data.labelCurrent || 'Current/latest tournament', value: 0 }];
            var selectedName = data.labelCurrent || 'Current/latest tournament';
            (data.tournaments || []).forEach(function (t) {
                options.push({ label: (t.name || ('Tournament #' + t.id)) + ' (#' + t.id + ')', value: parseInt(t.id, 10) || 0 });
                if ((parseInt(t.id, 10) || 0) === (attrs.tournamentId || 0)) {
                    selectedName = t.name || ('Tournament #' + t.id);
                }
            });
            var shortcode = '[chess_podium_tournament' + ((attrs.tournamentId || 0) > 0 ? (' id="' + (attrs.tournamentId || 0) + '"') : '') + ((attrs.round || 0) > 0 ? (' round="' + (attrs.round || 0) + '"') : '') + ']';
            return el(
                'div',
                { className: 'cp-gutenberg-block', style: { border: '1px solid #dcdcde', borderRadius: '8px', padding: '12px', background: '#fff' } },
                el(InspectorControls, {},
                    el(PanelBody, { title: data.labelPanelTitle || 'Chess Podium', initialOpen: true },
                        el(SelectControl, {
                            label: data.labelTournament || 'Tournament',
                            value: attrs.tournamentId || 0,
                            options: options,
                            onChange: function (v) {
                                props.setAttributes({ tournamentId: parseInt(v, 10) || 0 });
                            }
                        }),
                        el(TextControl, {
                            label: data.labelRound || 'Round (optional)',
                            type: 'number',
                            min: 0,
                            value: attrs.round || 0,
                            onChange: function (v) {
                                props.setAttributes({ round: parseInt(v, 10) || 0 });
                            }
                        })
                    )
                ),
                el('strong', {}, data.labelBlockTitle || 'Chess Podium Tournament'),
                el(
                    'p',
                    { style: { marginBottom: '6px' } },
                    (data.labelTournamentPrefix || 'Tournament') + ': ' + selectedName + (attrs.round ? (' | ' + (data.labelRoundShort || 'Round') + ': ' + attrs.round) : (' | ' + (data.labelAllRounds || 'All rounds')))
                ),
                el('code', {}, shortcode)
            );
        },
        save: function () {
            return null;
        }
    });

    var archiveData = (window.chessPodiumBlockData && window.chessPodiumBlockData.archiveBlock) || {};
    registerBlockType('chess-podium/tournament-archive-card', {
        apiVersion: 3,
        title: archiveData.labelBlockTitle || 'Chess Podium Tournament Archive Card',
        icon: 'calendar',
        category: 'widgets',
        description: archiveData.labelPreviewHint || 'Standings preview card for a past tournament.',
        attributes: {
            tournamentId: { type: 'integer', default: 0 },
            maxRows: { type: 'integer', default: 10 },
            showImage: { type: 'boolean', default: true },
            linkMode: { type: 'string', default: 'auto' }
        },
        edit: function (props) {
            var attrs = props.attributes || {};
            var options = [{ label: archiveData.labelSelect || 'Select a tournament', value: 0 }];
            var selectedName = archiveData.labelNone || 'Choose a tournament in the block settings.';
            (archiveData.tournaments || []).forEach(function (t) {
                var id = parseInt(t.id, 10) || 0;
                options.push({ label: t.label || t.name || ('Tournament #' + id), value: id });
                if (id === (attrs.tournamentId || 0)) {
                    selectedName = t.name || t.label || ('Tournament #' + id);
                }
            });
            var linkOptions = [
                { label: archiveData.linkAuto || 'Auto', value: 'auto' },
                { label: archiveData.linkLive || 'Live page', value: 'live' },
                { label: archiveData.linkArchive || 'Published archive', value: 'archive' }
            ];
            var shortcode = '[chess_podium_tournament_archive id="' + (attrs.tournamentId || 0) + '" rows="' + (attrs.maxRows || 10) + '"' +
                (attrs.showImage === false ? ' show_image="0"' : '') +
                (attrs.linkMode && attrs.linkMode !== 'auto' ? (' link="' + attrs.linkMode + '"') : '') + ']';
            return el(
                'div',
                { className: 'cp-gutenberg-block cp-gutenberg-archive-block', style: { border: '1px solid #dcdcde', borderRadius: '8px', padding: '12px', background: '#f8fafc' } },
                el(InspectorControls, {},
                    el(PanelBody, { title: archiveData.labelPanelTitle || 'Archive card', initialOpen: true },
                        el(SelectControl, {
                            label: archiveData.labelTournament || 'Tournament',
                            value: attrs.tournamentId || 0,
                            options: options,
                            onChange: function (v) {
                                props.setAttributes({ tournamentId: parseInt(v, 10) || 0 });
                            }
                        }),
                        el(TextControl, {
                            label: archiveData.labelMaxRows || 'Players in standings preview',
                            type: 'number',
                            min: 3,
                            max: 25,
                            value: attrs.maxRows || 10,
                            onChange: function (v) {
                                var n = parseInt(v, 10) || 10;
                                props.setAttributes({ maxRows: Math.max(3, Math.min(25, n)) });
                            }
                        }),
                        el(ToggleControl, {
                            label: archiveData.labelShowImage || 'Show cover image',
                            checked: attrs.showImage !== false,
                            onChange: function (v) {
                                props.setAttributes({ showImage: !!v });
                            }
                        }),
                        el(SelectControl, {
                            label: archiveData.labelLinkMode || 'Link target',
                            value: attrs.linkMode || 'auto',
                            options: linkOptions,
                            onChange: function (v) {
                                props.setAttributes({ linkMode: v || 'auto' });
                            }
                        })
                    )
                ),
                el('strong', {}, archiveData.labelBlockTitle || 'Chess Podium Tournament Archive Card'),
                el('p', { style: { marginBottom: '6px', color: '#50575e' } }, archiveData.labelPreviewHint || ''),
                el('p', { style: { marginBottom: '6px' } }, selectedName),
                el('code', {}, shortcode)
            );
        },
        save: function () {
            return null;
        }
    });
})(window.wp);
