import RadioPlayerInit from './player';
import {openPopup, openStickyPlayer} from "./includes/functions";
import metadataHandler from "./includes/metadata-handler";

const {isPro, settings} = radioPlayer;

;(function ($) {

    const app = {

        init: function () {

            window.RadioPlayerInit = RadioPlayerInit;
            RadioPlayerInit();

            $(window).on('elementor/frontend/init', function () {
                window.elementorFrontend.hooks.addAction('frontend/element_ready/radio_player.default', RadioPlayerInit);
            });

        },

        ready: function () {

            metadataHandler.init();

            if (isPro) {
                // Handle popup triggers
                app.handlePopupTriggers();

                // Handle sticky triggers
                app.handleStickyTriggers();

                // Handle sticky draggable
                app.handleStickyDraggable();
            }

        },

        handlePopupTriggers: () => {
            const {popupTriggers = []} = settings;

            if (popupTriggers.length) {
                const selectors = popupTriggers.map((trigger) => trigger.selector);
                const playerIds = popupTriggers.map((trigger) => parseInt(trigger.player));

                selectors.forEach((selector, index) => {

                    if (!selector) return;

                    $(document).on('click', selector, function (e) {
                        e.preventDefault();
                        openPopup(playerIds[index]);
                    });
                });
            }
        },

        handleStickyTriggers: () => {
            const players = window.radioPlayer?.players;
            const {stickyTriggers = []} = settings;

            if (stickyTriggers.length) {
                const selectors = stickyTriggers.map((trigger) => trigger.selector);
                const playerIds = stickyTriggers.map((trigger) => parseInt(trigger.player));

                selectors.forEach((selector, index) => {
                    const player = players.find(player => player.id === playerIds[index]);
                    let data = player?.config;

                    if (!selector || !data) return;

                    $(document).on('click', selector, function (e) {
                        e.preventDefault();

                        // open sticky player
                        openStickyPlayer(data);
                    });
                });
            }
        },

        handleStickyDraggable: () => {

            const {draggableFloating = true} = settings;

            if (!isPro || !draggableFloating) return;

            const element = document.querySelector('.radio-player.floating.draggable');
            if (!element) return;

            // Restore saved position
            const saved = localStorage.getItem('radio_player_sticky_position');
            if (saved) {
                const pos = JSON.parse(saved);
                element.style.position = 'fixed';
                element.style.top = pos.top + 'px';
                element.style.left = pos.left + 'px';
            }

            let isDragging = false, offsetX = 0, offsetY = 0;

            const startDrag = (clientX, clientY) => {
                isDragging = true;
                const rect = element.getBoundingClientRect();
                offsetX = clientX - rect.left;
                offsetY = clientY - rect.top;
            };

            const moveDrag = (clientX, clientY) => {
                if (!isDragging) return;
                const left = clientX - offsetX;
                const top = clientY - offsetY;
                element.style.position = 'fixed';
                element.style.left = left + 'px';
                element.style.top = top + 'px';
                localStorage.setItem('radio_player_sticky_position', JSON.stringify({top, left}));
            };

            const endDrag = () => isDragging = false;

            // Mouse events
            element.addEventListener('mousedown', e => {
                startDrag(e.clientX, e.clientY);
            });

            document.addEventListener('mousemove', e => {
                moveDrag(e.clientX, e.clientY);
            });

            document.addEventListener('mouseup', () => endDrag());

            // Touch events
            element.addEventListener('touchstart', e => {
                if (!e.touches || !e.touches[0]) return;
                const t = e.touches[0];
                startDrag(t.clientX, t.clientY);
                // prevent touch scrolling while dragging
                e.preventDefault();
            }, {passive: false});

            document.addEventListener('touchmove', e => {
                if (!e.touches || !e.touches[0]) return;
                const t = e.touches[0];
                moveDrag(t.clientX, t.clientY);
                e.preventDefault();
            }, {passive: false});

            document.addEventListener('touchend', () => endDrag());

        },

    }

    app.init();
    $(document).ready(app.ready);

})(jQuery);
