/**
 * VMPlayer Kebab Menu
 *
 * Shared dropdown menu attached to the kebab (3-dot) button on both
 * the main player and the pop-out. Contains Share, Switch Mount
 * (when the current station has multiple mounts configured),
 * Player Settings toggles, and About.
 *
 * The menu is created and destroyed on demand via VMPlayerKebab.render()
 * and VMPlayerKebab.close(), so the DOM stays clean when no menu is open.
 *
 * @package VMPlayer
 */

( function () {
    'use strict';

    var currentMenu    = null;
    var currentBackdrop = null;

    /**
     * Open a kebab menu. Options:
     *   anchor:          HTMLElement to position the menu near.
     *   strings:         Object of translatable labels.
     *   currentStation:  Station object with mounts, social, etc.
     *   currentIndex:    Zero-based index of the active station.
     *   settings:        { autoResume, enableVisualizer } current values.
     *   onSelectMount:   Callback( mountIndex ) when user picks a mount.
     *   onToggleSetting: Callback( key, value ) for toggles.
     *   onClose:         Callback when menu closes.
     *
     * @param {object} opts
     * @return {HTMLElement} The menu element.
     */
    function render( opts ) {
        close();

        var strings = opts.strings || {};
        var station = opts.currentStation || {};
        var settings = opts.settings || {};

        // Backdrop closes the menu when the user clicks outside it.
        var backdrop = document.createElement( 'div' );
        backdrop.className = 'vmplayer-kebab-backdrop';
        backdrop.addEventListener( 'click', function () { close(); } );
        document.body.appendChild( backdrop );

        var menu = document.createElement( 'div' );
        menu.className = 'vmplayer-kebab-menu';
        menu.setAttribute( 'role', 'menu' );

        // Section: Share
        menu.appendChild( buildShareSection( strings ) );

        // Section: Switch Mount (only when the station has multiple mounts).
        if ( Array.isArray( station.mounts ) && station.mounts.length > 1 ) {
            menu.appendChild( buildMountSection( strings, station.mounts, opts.onSelectMount ) );
        }

        // Section: Player Settings.
        menu.appendChild( buildSettingsSection( strings, settings, opts.onToggleSetting ) );

        // Section: About.
        menu.appendChild( buildAboutSection( strings, station ) );

        document.body.appendChild( menu );
        positionMenu( menu, opts.anchor );

        currentMenu = menu;
        currentBackdrop = backdrop;
        currentMenu._onClose = opts.onClose || null;

        // Close on Escape.
        window.addEventListener( 'keydown', onKeyDown );

        return menu;
    }

    function close() {
        if ( currentMenu ) {
            if ( 'function' === typeof currentMenu._onClose ) {
                currentMenu._onClose();
            }
            currentMenu.parentNode && currentMenu.parentNode.removeChild( currentMenu );
            currentMenu = null;
        }
        if ( currentBackdrop ) {
            currentBackdrop.parentNode && currentBackdrop.parentNode.removeChild( currentBackdrop );
            currentBackdrop = null;
        }
        window.removeEventListener( 'keydown', onKeyDown );
    }

    function onKeyDown( e ) {
        if ( 'Escape' === e.key ) { close(); }
    }

    /* ------------------------------------------------------------------
     * Section builders
     * --------------------------------------------------------------- */

    function buildShareSection( strings ) {
        var section = document.createElement( 'div' );
        section.className = 'vmplayer-kebab-menu__section';

        section.appendChild( heading( strings.share || 'Share' ) );

        var pageUrl = window.location.href;
        var pageTitle = document.title;

        section.appendChild( item( iconLink(), strings.copyLink || 'Copy link', function () {
            copyToClipboard( pageUrl );
            showToast( strings.linkCopied || 'Link copied!' );
        } ) );

        section.appendChild( item( iconFacebook(), strings.shareFB || 'Share on Facebook', function () {
            window.open(
                'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent( pageUrl ),
                '_blank',
                'noopener,noreferrer,width=600,height=500'
            );
            close();
        } ) );

        section.appendChild( item( iconX(), strings.shareTwitter || 'Share on X', function () {
            window.open(
                'https://twitter.com/intent/tweet?text=' + encodeURIComponent( pageTitle ) +
                '&url=' + encodeURIComponent( pageUrl ),
                '_blank',
                'noopener,noreferrer,width=600,height=500'
            );
            close();
        } ) );

        section.appendChild( item( iconEmail(), strings.shareEmail || 'Share via email', function () {
            window.location.href = 'mailto:?subject=' + encodeURIComponent( pageTitle ) +
                '&body=' + encodeURIComponent( pageUrl );
            close();
        } ) );

        return section;
    }

    function buildMountSection( strings, mounts, onSelect ) {
        var section = document.createElement( 'div' );
        section.className = 'vmplayer-kebab-menu__section';
        section.appendChild( heading( strings.switchMount || 'Switch Quality' ) );

        mounts.forEach( function ( mount, index ) {
            var label = ( mount.label || 'Stream' ) + ' (' + ( mount.bitrate || '?' ) + ' kbps ' + ( mount.format || 'mp3' ).toUpperCase() + ')';
            var el = item( iconMount(), label, function () {
                if ( 'function' === typeof onSelect ) { onSelect( index ); }
                close();
            } );
            section.appendChild( el );
        } );

        return section;
    }

    function buildSettingsSection( strings, settings, onToggle ) {
        var section = document.createElement( 'div' );
        section.className = 'vmplayer-kebab-menu__section';
        section.appendChild( heading( strings.settings || 'Player Settings' ) );

        var vizItem = toggleItem(
            iconViz(),
            strings.enableViz || 'Show visualizer',
            !! settings.enableVisualizer,
            function ( newValue ) {
                if ( 'function' === typeof onToggle ) { onToggle( 'enableVisualizer', newValue ); }
            }
        );
        section.appendChild( vizItem );

        var arItem = toggleItem(
            iconResume(),
            strings.enableAR || 'Auto-resume when pop-out closes',
            !! settings.autoResume,
            function ( newValue ) {
                if ( 'function' === typeof onToggle ) { onToggle( 'autoResume', newValue ); }
            }
        );
        section.appendChild( arItem );

        return section;
    }

    function buildAboutSection( strings, station ) {
        var section = document.createElement( 'div' );
        section.className = 'vmplayer-kebab-menu__section';
        section.appendChild( heading( strings.about || 'About' ) );

        var info = document.createElement( 'div' );
        info.className = 'vmplayer-kebab-menu__about';

        var stationLine = document.createElement( 'div' );
        stationLine.className = 'vmplayer-kebab-menu__about-station';
        stationLine.textContent = station.name || '';
        info.appendChild( stationLine );

        if ( station.tagline ) {
            var taglineLine = document.createElement( 'div' );
            taglineLine.className = 'vmplayer-kebab-menu__about-tagline';
            taglineLine.textContent = station.tagline;
            info.appendChild( taglineLine );
        }

        var poweredLine = document.createElement( 'div' );
        poweredLine.className = 'vmplayer-kebab-menu__about-powered';
        poweredLine.textContent = 'VMPlayer 1.1.5';
        info.appendChild( poweredLine );

        section.appendChild( info );
        return section;
    }

    /* ------------------------------------------------------------------
     * Element helpers
     * --------------------------------------------------------------- */

    function heading( text ) {
        var el = document.createElement( 'div' );
        el.className = 'vmplayer-kebab-menu__heading';
        el.textContent = text;
        return el;
    }

    function item( iconEl, labelText, onClick ) {
        var el = document.createElement( 'button' );
        el.type = 'button';
        el.className = 'vmplayer-kebab-menu__item';
        el.setAttribute( 'role', 'menuitem' );

        var iconWrap = document.createElement( 'span' );
        iconWrap.className = 'vmplayer-kebab-menu__item-icon';
        iconWrap.appendChild( iconEl );
        el.appendChild( iconWrap );

        var label = document.createElement( 'span' );
        label.className = 'vmplayer-kebab-menu__item-label';
        label.textContent = labelText;
        el.appendChild( label );

        if ( 'function' === typeof onClick ) {
            el.addEventListener( 'click', function () { onClick(); } );
        }
        return el;
    }

    function toggleItem( iconEl, labelText, initialState, onChange ) {
        var el = document.createElement( 'button' );
        el.type = 'button';
        el.className = 'vmplayer-kebab-menu__item';
        el.setAttribute( 'role', 'menuitemcheckbox' );
        el.setAttribute( 'aria-checked', initialState ? 'true' : 'false' );

        var iconWrap = document.createElement( 'span' );
        iconWrap.className = 'vmplayer-kebab-menu__item-icon';
        iconWrap.appendChild( iconEl );
        el.appendChild( iconWrap );

        var label = document.createElement( 'span' );
        label.className = 'vmplayer-kebab-menu__item-label';
        label.textContent = labelText;
        el.appendChild( label );

        var toggle = document.createElement( 'span' );
        toggle.className = 'vmplayer-kebab-menu__toggle';
        el.appendChild( toggle );

        if ( initialState ) { el.classList.add( 'is-toggled' ); }

        el.addEventListener( 'click', function () {
            var newState = ! el.classList.contains( 'is-toggled' );
            el.classList.toggle( 'is-toggled', newState );
            el.setAttribute( 'aria-checked', newState ? 'true' : 'false' );
            if ( 'function' === typeof onChange ) { onChange( newState ); }
        } );

        return el;
    }

    /* ------------------------------------------------------------------
     * Positioning
     * --------------------------------------------------------------- */

    function positionMenu( menu, anchor ) {
        if ( ! anchor ) {
            // Default to center of viewport.
            menu.style.top = '50%';
            menu.style.left = '50%';
            menu.style.transform = 'translate(-50%, -50%)';
            return;
        }

        var rect = anchor.getBoundingClientRect();
        var menuRect = menu.getBoundingClientRect();
        var vw = window.innerWidth;
        var vh = window.innerHeight;

        // Prefer placing menu above and to the left of the anchor.
        var top  = rect.top - menuRect.height - 8 + window.scrollY;
        var left = rect.right - menuRect.width + window.scrollX;

        // If the menu would go off the top, place it below the anchor.
        if ( rect.top - menuRect.height - 8 < 8 ) {
            top = rect.bottom + 8 + window.scrollY;
        }

        // Keep menu on-screen horizontally.
        if ( left < 8 + window.scrollX ) {
            left = 8 + window.scrollX;
        }
        if ( left + menuRect.width > vw + window.scrollX - 8 ) {
            left = vw + window.scrollX - menuRect.width - 8;
        }

        // Keep menu on-screen vertically.
        if ( top + menuRect.height > vh + window.scrollY - 8 ) {
            top = vh + window.scrollY - menuRect.height - 8;
        }
        if ( top < 8 + window.scrollY ) {
            top = 8 + window.scrollY;
        }

        menu.style.top = top + 'px';
        menu.style.left = left + 'px';
    }

    /* ------------------------------------------------------------------
     * Utility
     * --------------------------------------------------------------- */

    function copyToClipboard( text ) {
        if ( navigator.clipboard && navigator.clipboard.writeText ) {
            navigator.clipboard.writeText( text ).catch( function () {
                fallbackCopy( text );
            } );
        } else {
            fallbackCopy( text );
        }
    }

    function fallbackCopy( text ) {
        var ta = document.createElement( 'textarea' );
        ta.value = text;
        ta.setAttribute( 'readonly', '' );
        ta.style.position = 'absolute';
        ta.style.left = '-9999px';
        document.body.appendChild( ta );
        ta.select();
        try { document.execCommand( 'copy' ); } catch ( e ) {}
        document.body.removeChild( ta );
    }

    function showToast( message ) {
        if ( ! currentMenu ) { return; }
        var toast = document.createElement( 'div' );
        toast.className = 'vmplayer-kebab-menu__toast';
        toast.textContent = message;
        currentMenu.appendChild( toast );
        setTimeout( function () { toast.classList.add( 'is-visible' ); }, 10 );
        setTimeout( function () {
            toast.classList.remove( 'is-visible' );
            setTimeout( function () {
                if ( toast.parentNode ) { toast.parentNode.removeChild( toast ); }
            }, 300 );
        }, 1800 );
    }

    /* ------------------------------------------------------------------
     * Inline SVG icons
     * --------------------------------------------------------------- */

    function svg( pathD, viewBox ) {
        var s = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
        s.setAttribute( 'width', '18' );
        s.setAttribute( 'height', '18' );
        s.setAttribute( 'viewBox', viewBox || '0 0 24 24' );
        s.setAttribute( 'fill', 'none' );
        var p = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
        p.setAttribute( 'd', pathD );
        p.setAttribute( 'stroke', 'currentColor' );
        p.setAttribute( 'stroke-width', '2' );
        p.setAttribute( 'stroke-linecap', 'round' );
        p.setAttribute( 'stroke-linejoin', 'round' );
        s.appendChild( p );
        return s;
    }

    function iconLink() {
        return svg( 'M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71' );
    }
    function iconFacebook() {
        var s = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
        s.setAttribute( 'width', '18' );
        s.setAttribute( 'height', '18' );
        s.setAttribute( 'viewBox', '0 0 24 24' );
        s.setAttribute( 'fill', 'currentColor' );
        var p = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
        p.setAttribute( 'd', 'M22 12c0-5.5-4.5-10-10-10S2 6.5 2 12c0 5 3.7 9.1 8.4 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.3v7C18.3 21.1 22 17 22 12z' );
        s.appendChild( p );
        return s;
    }
    function iconX() {
        var s = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
        s.setAttribute( 'width', '18' );
        s.setAttribute( 'height', '18' );
        s.setAttribute( 'viewBox', '0 0 24 24' );
        s.setAttribute( 'fill', 'currentColor' );
        var p = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
        p.setAttribute( 'd', 'M18.9 1.5h3.6l-7.9 9 9.3 12.3h-7.3l-5.7-7.5-6.6 7.5H.8l8.5-9.7L.1 1.5h7.5l5.1 6.8 6.2-6.8zm-1.2 19.2h2L6.3 3.4H4.2l13.5 17.3z' );
        s.appendChild( p );
        return s;
    }
    function iconEmail() {
        return svg( 'M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2zM22 6l-10 7L2 6' );
    }
    function iconMount() {
        return svg( 'M12 3l3 6h6l-5 4 2 7-6-4-6 4 2-7-5-4h6z' );
    }
    function iconViz() {
        return svg( 'M4 20V10m6 10V4m6 16v-8' );
    }
    function iconResume() {
        return svg( 'M21 12a9 9 0 11-9-9M21 3v6h-6' );
    }

    /* Expose */

    window.VMPlayerKebab = {
        render: render,
        close: close
    };

} )();
