// Copyright Hassine RIANI (https://upvimeo.com)
// 2025. All Rights Reserved.
// This file is licensed under the GPLv2 License.
// License text available at https://opensource.org/licenses/gpl-2.0.php

wp.blocks.registerBlockType('upvimeo/wp-vimeo-video', {
    title: UPVIMEO_GTB.words.block_name,
    icon: wp.element.createElement('svg', { width: 24, height: 24, viewBox: '0 0 24 24' }, wp.element.createElement('path', { d: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z' })),
    keywords: ['vimeo', 'upload', 'video', 'upvimeo'],
    category: 'media',
    attributes: {
        title: { type: 'string' },
        description: { type: 'string' },
        files: { type: 'array' },
        upvimeo_id: { type: 'string' },
        method: { type: 'string' },
        size_type: { type: 'string' }, // fixed or responsive
        height: { type: 'string' },
        width: { type: 'string' },
        autoplay: { type: 'string' },
        loop: { type: 'string' },
        current_message: { type: 'string' },
        current_message_type: { type: 'string' },
        search_phrase: { type: 'string' },
        search_results: { type: 'array' },
        privacy: { type: 'string' }
    },
    edit: function (props) {

        // State update helpers
        function updateTitle(event) { props.setAttributes({ title: event.target.value }) }
        function updateDescription(event) { props.setAttributes({ description: event.target.value }) }
        function updateViewPrivacy(event) { props.setAttributes({ privacy: event.target.value }); }
        function updateSearchPhrase(event) { props.setAttributes({ search_phrase: event.target.value }) }
        function updateFile(event) { props.setAttributes({ files: event.target.files }) }

        function updateCurrentVimeoId(event) {
            var is_search = Array.isArray(props.attributes.search_results) && props.attributes.search_results.length > 0;
            if (parseInt(event.target.value) > 0) {
                var method = is_search ? 'search' : 'existing';
                props.setAttributes({ upvimeo_id: event.target.value, method: method });
            }
        }

        function setMethod(methodValue) {
            if (methodValue === 'upload') {
                props.setAttributes({ method: methodValue, upvimeo_id: undefined, search_phrase: '', search_results: [] });
            } else if (methodValue === 'existing') {
                props.setAttributes({ method: methodValue, search_phrase: '', search_results: [] });
            } else {
                props.setAttributes({ method: methodValue });
            }
        }

        // Validation & Upload Logic
        function submitVideo(event) {
            event.preventDefault();
            var target = event.target;
            var submitButton = event.target.querySelector('.submitUpload');
            var videoFile = (props.attributes.files instanceof FileList && props.attributes.files.length > 0) ? props.attributes.files[0] : null;

            if (!WPVimeoVideos.Uploader.validateVideo(videoFile)) {
                swal.fire(UPVIMEO_GTB.words.sorry, UPVIMEO_GTB.phrases.upload_invalid_file, 'error');
                return false;
            }

            // Init upload
            var privacy = UPVIMEO_GTB.upload_form_options.enable_privacy_option && props.attributes.privacy ? props.attributes.privacy : UPVIMEO_GTB.default_privacy;

            var uploader = new WPVimeoVideos.Uploader(UPVIMEO_GTB.nonce, videoFile, {
                'title': props.attributes.title,
                'description': props.attributes.description,
                'privacy': privacy,
                'wp': {
                    'notify_endpoint': UPVIMEO_GTB.ajax_url + '?action=UPVIMEO_store_upload&_wpnonce=' + UPVIMEO_GTB.nonce,
                },
                'beforeStart': function () {
                    submitButton.disabled = true;
                    submitButton.innerHTML = UPVIMEO_GTB.words.uploading3d;
                    startLoading(target);
                    updateProgressBar(target, 0.25);
                },
                'onProgress': function (bytesUploaded, bytesTotal) {
                    var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
                    updateProgressBar(target, percentage);
                },
                'onSuccess': function (response, currentUpload) {
                    var video_uri = currentUpload.uri;
                    var video_uri_parts = video_uri.split('/');
                    var video_id = video_uri_parts[video_uri_parts.length - 1];
                    UPVIMEO_GTB.uploads.push({ title: props.attributes.title, ID: null, upvimeo_id: video_id });
                    props.setAttributes({
                        'upvimeo_id': video_id,
                        'current_message_type': 'success',
                        'current_message': UPVIMEO_GTB.phrases.upload_success,
                        'method': 'existing',
                    });
                    submitButton.disabled = false;
                    submitButton.innerHTML = UPVIMEO_GTB.words.upload;
                },
                'onError': function (error) {
                    handleUploadError(error, target, submitButton);
                },
                'onVideoCreateError': function (error) {
                    var parsedError = JSON.parse(error);
                    var message = parsedError.hasOwnProperty('invalid_parameters') ? parsedError['invalid_parameters'][0]['developer_message'] : parsedError['developer_message'];
                    handleUploadError(message, target, submitButton);
                },
                'onWPNotifyError': function (error) {
                    var parsedError = JSON.parse(error);
                    var message = parsedError.hasOwnProperty('data') ? parsedError.data : 'Error notifying WordPress about the file upload.';
                    handleUploadError(message, target, submitButton);
                }
            });
            uploader.start();
            return true;
        }

        function handleUploadError(message, target, submitButton) {
            props.setAttributes({ 'current_message_type': 'error', 'current_message': message });
            stopLoading(target, true);
            submitButton.disabled = false;
            submitButton.innerHTML = UPVIMEO_GTB.words.upload;
            alert(message);
        }

        function searchAccount(event) {
            var search_phrase = props.attributes.search_phrase;
            if (search_phrase !== '') {
                var vimeoProfile = new WPVimeoVideos.Profile(UPVIMEO_GTB.nonce);
                vimeoProfile.search({
                    'page': 1, 'per_page': 100, 'query': search_phrase, 'sort': 'date', 'direction': 'desc',
                    'onSuccess': function (response) {
                        var search_results = [];
                        for (var i in response.data) {
                            search_results.push({ title: response.data[i].name, uri: response.data[i].uri });
                        }
                        props.setAttributes({ 'search_results': search_results, 'upvimeo_id': '' });
                    },
                    'onError': function (response) {
                        swal.fire(UPVIMEO_GTB.words.sorry, UPVIMEO_GTB.phrases.invalid_search_phrase, 'error');
                    }
                });
            } else {
                swal.fire(UPVIMEO_GTB.words.sorry, UPVIMEO_GTB.phrases.invalid_search_phrase, 'error');
            }
        }

        // Helper: Progress Bar & Loader
        function updateProgressBar(form, progress) {
            form.querySelector('.upvimeo-progress-bar').style.display = 'block';
            form.querySelector('.upvimeo-progress-bar-inner').style.width = progress + '%';
            form.querySelector('.upvimeo-progress-bar-value').innerHTML = progress + '%';
        }

        function startLoading(form) { form.querySelector('.upvimeo-loader').style.display = 'inline-block'; }

        function stopLoading(form, hide_progressbar) {
            form.querySelector('.upvimeo-loader').style.display = 'none';
            if (hide_progressbar) { form.querySelector('.upvimeo-progress-bar').style.display = 'none'; }
        }

        // Helper: Dropdown Generation
        function getUploadsDropdown(current_vimeo_id, uploads, message) {
            var uploads_options = [];
            uploads_options.push(wp.element.createElement("option", { value: -1, key: 'standard' }, message));

            var current_found = false;
            for (var i in uploads) {
                if (current_vimeo_id == uploads[i].upvimeo_id) current_found = true;
                uploads_options.push(wp.element.createElement("option", { value: uploads[i].upvimeo_id, key: uploads[i].upvimeo_id }, uploads[i].title));
            }

            if (current_vimeo_id && !current_found) {
                uploads_options.push(wp.element.createElement("option", { value: current_vimeo_id, key: current_vimeo_id }, '#' + current_vimeo_id + ' ' + UPVIMEO_GTB.phrases.existing_not_visible_current_user));
            }
            return uploads_options;
        }

        function getIDFromURI(uri) { var parts = uri.split('/'); return parts[parts.length - 1]; }


        // ---------------- RENDER ---------------- //

        var upvimeo_video_id = props.attributes.upvimeo_id;
        var uploads = UPVIMEO_GTB.uploads;
        var is_search = Array.isArray(props.attributes.search_results) && props.attributes.search_results.length > 0;
        var is_already_selected = upvimeo_video_id && upvimeo_video_id.toString().trim() !== '';

        var hash = '';
        var display_id = upvimeo_video_id;
        if (upvimeo_video_id && upvimeo_video_id.toString().indexOf('/') !== -1) {
            var parts = upvimeo_video_id.toString().split('/');
            display_id = parts[0];
            hash = '?h=' + parts[1];
        } else if (upvimeo_video_id && upvimeo_video_id.toString().indexOf(':') !== -1) {
            var parts = upvimeo_video_id.toString().split(':');
            display_id = parts[0];
            hash = '?h=' + parts[1];
        }

        var iframe_src = is_already_selected ? 'https://player.vimeo.com/video/' + display_id + hash : false;

        // 1. Header
        var header = wp.element.createElement('div', { className: 'upvimeo-block-header' },
            wp.element.createElement('h4', {},
                wp.element.createElement('svg', { className: 'upvimeo-header-icon', viewBox: '0 0 24 24' }, wp.element.createElement('path', { d: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z' })),
                UPVIMEO_GTB.phrases.block_title
            )
        );

        // 2. Method Selector (Tabs)
        var methodOptions = [
            { id: 'upload', label: UPVIMEO_GTB.methods.upload, icon: 'cloud-upload' },
            { id: 'existing', label: UPVIMEO_GTB.methods.local, icon: 'admin-media' }
        ];
        if (UPVIMEO_GTB.enable_vimeo_search) {
            methodOptions.push({ id: 'search', label: UPVIMEO_GTB.methods.search, icon: 'search' });
        }

        var methodSelector = wp.element.createElement('div', { className: 'upvimeo-method-selector' },
            methodOptions.map(function (opt) {
                return wp.element.createElement('div', {
                    key: opt.id,
                    className: 'upvimeo-method-option ' + (props.attributes.method === opt.id ? 'active' : ''),
                    onClick: function () { setMethod(opt.id); }
                },
                    // Note: Use Dashicons or simple text/emoji if no icon lib available. Using Dashicon class.
                    wp.element.createElement('span', { className: 'dashicons dashicons-' + opt.icon + ' upvimeo-method-icon' }),
                    opt.label
                );
            })
        );

        // 3. Form Content
        var formContent = [];

        // --- METHOD: UPLOAD ---
        if (props.attributes.method === 'upload') {
            formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', key: 'grp-title' },
                wp.element.createElement('label', {}, UPVIMEO_GTB.words.title),
                wp.element.createElement('input', {
                    type: 'text',
                    className: 'upvimeo-input-control',
                    placeholder: UPVIMEO_GTB.words.title,
                    onChange: updateTitle
                })
            ));

            formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', key: 'grp-desc' },
                wp.element.createElement('label', {}, UPVIMEO_GTB.words.desc),
                wp.element.createElement('textarea', {
                    className: 'upvimeo-input-control',
                    placeholder: UPVIMEO_GTB.words.desc,
                    onChange: updateDescription
                })
            ));

            if (UPVIMEO_GTB.upload_form_options.enable_privacy_option) {
                var privacy_options_elements = [];
                var privacy_default = 'anybody';
                for (var key in UPVIMEO_GTB.upload_form_options.privacy_view) {
                    var p_name = UPVIMEO_GTB.upload_form_options.privacy_view[key].name;
                    var p_avail = UPVIMEO_GTB.upload_form_options.privacy_view[key].available;
                    privacy_default = UPVIMEO_GTB.upload_form_options.privacy_view[key].default ? key : privacy_default;
                    privacy_options_elements.push(wp.element.createElement("option", { value: key, key: key, disabled: !p_avail }, p_name));
                }
                if (props.attributes.privacy) privacy_default = props.attributes.privacy;

                formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', key: 'grp-privacy' },
                    wp.element.createElement('label', {}, 'Privacy'),
                    wp.element.createElement('select', {
                        className: 'upvimeo-input-control',
                        onChange: updateViewPrivacy,
                        value: privacy_default
                    }, privacy_options_elements)
                ));
            }

            formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', key: 'grp-file' },
                wp.element.createElement('label', {}, UPVIMEO_GTB.words.file),
                wp.element.createElement('input', {
                    type: 'file',
                    className: 'upvimeo-input-control',
                    onChange: updateFile
                })
            ));

            // Progress Bar
            formContent.push(wp.element.createElement('div', { className: 'upvimeo-progress-bar', style: { display: 'none' }, key: 'progress' },
                wp.element.createElement('div', { className: 'upvimeo-progress-bar-inner', style: { width: '0%' } }),
                wp.element.createElement('div', { className: 'upvimeo-progress-bar-value' }, '0%')
            ));

            // Loader & Submit
            formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', style: { marginTop: '10px' }, key: 'grp-submit' },
                wp.element.createElement('div', { className: 'upvimeo-loader', style: { display: 'none' } }),
                wp.element.createElement('button', {
                    type: 'submit',
                    className: 'upvimeo-button submitUpload',
                }, UPVIMEO_GTB.words.upload)
            ));

            // --- METHOD: EXISTING ---
        } else if (props.attributes.method === 'existing') {
            var existing_dropdown = getUploadsDropdown(upvimeo_video_id, uploads, 'Select existing video');
            var existing_val = props.attributes.upvimeo_id || '';

            formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', key: 'grp-existing' },
                wp.element.createElement('label', {}, 'Choose from Library'),
                wp.element.createElement('select', {
                    className: 'upvimeo-input-control',
                    onChange: updateCurrentVimeoId,
                    value: existing_val
                }, existing_dropdown)
            ));

            // --- METHOD: SEARCH ---
        } else if (props.attributes.method === 'search') {
            formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', key: 'grp-search' },
                wp.element.createElement('label', {}, 'Search Vimeo'),
                wp.element.createElement('div', { className: 'upvimeo-search-controls' },
                    wp.element.createElement('input', {
                        type: 'text',
                        className: 'upvimeo-input-control upvimeo-search-field',
                        placeholder: UPVIMEO_GTB.phrases.enter_phrase,
                        value: props.attributes.search_phrase,
                        onChange: updateSearchPhrase
                    }),
                    wp.element.createElement('button', {
                        type: 'button',
                        className: 'upvimeo-button submitSearch',
                        onClick: searchAccount
                    }, UPVIMEO_GTB.words.search)
                )
            ));

            if (is_search) {
                var search_dropdown_opts = [];
                for (var i in props.attributes.search_results) {
                    search_dropdown_opts.push({
                        'title': props.attributes.search_results[i].title,
                        'upvimeo_id': getIDFromURI(props.attributes.search_results[i].uri),
                    });
                }
                var search_dropdown = getUploadsDropdown(upvimeo_video_id, search_dropdown_opts, UPVIMEO_GTB.phrases.select_video);

                formContent.push(wp.element.createElement('div', { className: 'upvimeo-form-group', style: { marginTop: '15px' }, key: 'grp-search-results' },
                    wp.element.createElement('label', {}, 'Search Results'),
                    wp.element.createElement('select', {
                        className: 'upvimeo-input-control',
                        onChange: updateCurrentVimeoId
                    }, search_dropdown)
                ));
            }
        }

        // 4. Embed Preview
        if (is_already_selected && iframe_src) {
            formContent.push(wp.element.createElement('div', { className: 'upvimeo-embed-container', key: 'embed' },
                wp.element.createElement('iframe', { src: iframe_src, frameBorder: '0', allowFullScreen: true })
            ));
        }

        // Final Render
        return wp.element.createElement('div', { className: 'upvimeo-block-container' },
            header,
            methodSelector,
            wp.element.createElement('form', { className: 'upvimeo-vimeo-upload-form', onSubmit: submitVideo }, formContent)
        );
    },
    save: function (props) {
        var element;
        if (props.attributes.upvimeo_id && props.attributes.upvimeo_id.toString().trim() !== '') {
            var upvimeo_video_id = props.attributes.upvimeo_id;
            var video_width = props.attributes.width;
            var video_height = props.attributes.height;
            var size_type = props.attributes.size_type;
            if (!size_type) {
                size_type = 'responsive';
            }
            if (isNaN(video_width) || size_type === 'responsive') {
                video_width = 'auto';
            }
            if (isNaN(video_height) || size_type === 'responsive') {
                video_height = 'auto';
            }

            element = wp.element.createElement('div', {
                'className': 'upvimeo-embed-wrapper',
            }, '[upvimeo_video id="' + upvimeo_video_id + '" type="' + size_type + '" width="' + video_width + '" height="' + video_height + '" eparam1="-1" eparam2="-1" eparam3="-1"]');

        } else {
            element = wp.element.createElement(
                "div",
                { className: 'upvimeo-vimeo upvimeo-viemo-missing' },
                'No video uploaded.'
            );
        }
        return element;
    },
});
