import { registerWidget } from "../lib/utils";

class OEW_Media_Video extends elementorModules.frontend.handlers.Base {
    /**
     * Define default settings including selectors used within the widget.
     */
    getDefaultSettings() {
        return {
            selectors: {
                videoWrapper: '.oew-video-wrapper',
                videoThumbnail: '.oew-video-thumbnail',
                videoEmbed: '.oew-video-embed',
                playButton: '.oew-video-play-button',
                iframe: 'iframe',
            },
        };
    }

    /**
     * Cache the elements based on the defined selectors.
     */
    getDefaultElements() {
        const selectors = this.getSettings('selectors');

        return {
            videoWrappers: this.$element.find(selectors.videoWrapper),
            videoThumbnails: this.$element.find(selectors.videoThumbnail),
            videoEmbeds: this.$element.find(selectors.videoEmbed),
        };
    }

    /**
     * Initialize the handler by setting up event listeners.
     */
    onInit() {
        super.onInit();
        this.setupEventListeners();
    }

    /**
     * Set up event listeners for each video thumbnail within the widget instance.
     */
    setupEventListeners() {
        const widget = this;

        // Iterate over each video wrapper to bind events individually
        this.elements.videoWrappers.each(function() {
            const $wrapper = jQuery(this);
            const thumbnail = $wrapper.find(widget.getSettings('selectors').videoThumbnail);
            const embed = $wrapper.find(widget.getSettings('selectors').videoEmbed);
            const iframe = embed.find(widget.getSettings('selectors').iframe);

            // Attach click event to the thumbnail
            thumbnail.on('click', function() {
                // Hide the thumbnail
                thumbnail.hide();

                // Show the video embed
                embed.show();

                // Modify the iframe src to include autoplay=1 if not already present
                let src = iframe.attr('src');
                if (src && src.indexOf('autoplay=1') === -1) {
                    if (src.indexOf('?') === -1) {
                        src += '?autoplay=1';
                    } else {
                        src += '&autoplay=1';
                    }
                    iframe.attr('src', src);
                }
            });
        });
    }
}

// Register the widget with Elementor
registerWidget(OEW_Media_Video, "oew-media-video");
