/**
 * Admin Login Guard & Branding — Admin Settings JS
 *
 * Handles all interactive behaviour on the plugin settings page:
 * media uploads/removals, slug preview, clipboard copy, colour pickers,
 * tab switching, background-type toggling, custom-login toggling,
 * DataTables initialisation, and telemetry card selection.
 *
 * @requires jQuery
 * @requires wp.media
 * @requires jQuery.wpColorPicker
 * @requires jQuery.DataTable
 */
jQuery(document).ready(function ($) {

    /* ------------------------------------------------------------------ */
    /*  Media Upload                                                      */
    /* ------------------------------------------------------------------ */

    /** @type {?wp.media.view.MediaFrame} Reusable WP media frame instance. */
    let admiloguMedia;

    /** @type {?jQuery} The hidden input that will receive the selected URL. */
    let activeInput;

    /**
     * Open the WordPress media library and write the selected
     * attachment URL into the target hidden input field.
     *
     * The button must carry two data-attributes:
     *   - data-target : CSS selector of the hidden input (e.g. "#adminlgb_logo_url")
     *   - data-type   : (optional) MIME type filter, defaults to "image"
     */
    $('.adminlgb_media-upload').on('click', function (e) {
        e.preventDefault();
        const button = $(this);
        activeInput = $(button.data('target'));

        // If the media frame already exists, reopen it.
        if (admiloguMedia) {
            admiloguMedia.open();
            return;
        }

        const mediaType = button.data('type') || 'image';

        admiloguMedia = wp.media({
            title: admiloguWplc.uploadTitle,
            button: { text: admiloguWplc.uploadButton },
            multiple: false,
            library: { type: mediaType }
        });

        /**
         * Handle media selection — update the hidden input value,
         * show the preview container, and reveal the "Remove" button.
         */
        admiloguMedia.on('select', function () {
            let attachment = admiloguMedia.state().get('selection').first().toJSON();
            if (activeInput) {
                activeInput.val(attachment.url);

                // Update preview and show remove button
                const parent = activeInput.closest('.adminlgb-media-group');
                const removeBtn = parent.find('.adminlgb_media-remove');

                if (activeInput.attr('id') === 'adminlgb_logo_url') {
                    const previewContainer = $('#adminlgb_logo_preview_container');
                    if (previewContainer.length) {
                        previewContainer.find('img').attr('src', attachment.url);
                        previewContainer.removeClass('hidden');
                    }
                } else if (activeInput.attr('id') === 'adminlgb_bg_image') {
                    const previewContainer = $('#adminlgb_bg_image_preview_container');
                    if (previewContainer.length) {
                        previewContainer.find('img').attr('src', attachment.url);
                        previewContainer.removeClass('hidden');
                    }
                } else if (activeInput.attr('id') === 'adminlgb_bg_video') {
                    const previewContainer = $('#adminlgb_bg_video_preview_container');
                    if (previewContainer.length) {
                        previewContainer.find('video').attr('src', attachment.url);
                        previewContainer.removeClass('hidden');
                    }
                }

                removeBtn.removeClass('hidden');
            }
        });

        admiloguMedia.open();
    });

    /* ------------------------------------------------------------------ */
    /*  Media Remove                                                      */
    /* ------------------------------------------------------------------ */

    /**
     * Clear the hidden input, hide the preview container, and hide
     * the "Remove" button for a previously selected media item.
     */
    $('.adminlgb_media-remove').on('click', function (e) {
        e.preventDefault();
        const button = $(this);
        const target = $(button.data('target'));
        const parent = button.closest('.adminlgb-media-group');
        const container = parent.find('[class*="-preview-wrapper"]');

        target.val('');
        container.addClass('hidden');
        button.addClass('hidden');
    });

    /* ------------------------------------------------------------------ */
    /*  Slug Preview                                                      */
    /* ------------------------------------------------------------------ */

    /** Update the slug preview text as the user types. */
    $('#adminlgb_login_slug').on('input', function () {
        $('#adminlgb_slug_preview').text($(this).val());
    });

    /* ------------------------------------------------------------------ */
    /*  Copy Login URL                                                    */
    /* ------------------------------------------------------------------ */

    /**
     * Copy the full custom login URL to the clipboard.
     * Uses the modern Clipboard API with a fallback for older browsers.
     */
    $('#adminlgb_copy_login_url').on('click', function () {
        var slug = $('#adminlgb_login_slug').val();
        var url = admiloguWplc.siteUrl + '/' + slug;
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(function () {
                alert('Login URL copied to clipboard');
            }, function (err) {
                console.error('Could not copy text: ', err);
            });
        } else {
            // Fallback for older browsers
            var $temp = $('<input>');
            $('body').append($temp);
            $temp.val(url).select();
            document.execCommand('copy');
            $temp.remove();
            alert('Login URL copied to clipboard');
        }
    });

    /* ------------------------------------------------------------------ */
    /*  Color Pickers                                                     */
    /* ------------------------------------------------------------------ */

    /** Initialise WordPress colour-picker widgets on all matching inputs. */
    $('.adminlgb_color-picker').wpColorPicker();

    /* ------------------------------------------------------------------ */
    /*  Tab Switching                                                     */
    /* ------------------------------------------------------------------ */

    /**
     * Switch between settings tabs.
     * Updates the URL hash so the browser can restore the active tab
     * on page reload.
     */
    $('.nav-tab').on('click', function (e) {
        e.preventDefault();

        // Remove active class from all tabs and add to clicked tab
        $('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        // Hide all tab content and show target content
        $('.adminlgb_tab-content').hide();
        var target = $(this).data('tab');
        $('#tab-' + target).show();

        // Update URL hash without jumping
        var hash = $(this).attr('href');
        if (history.pushState) {
            history.pushState(null, null, hash);
        } else {
            hash = hash.replace(/^#/, '');
            location.hash = hash;
        }
    });

    // Restore active tab from URL hash on page load
    var currentHash = window.location.hash;
    if (currentHash) {
        var tabId = currentHash.replace('#', '');
        var $targetTab = $('.nav-tab[data-tab="' + tabId + '"]');
        if ($targetTab.length) {
            $targetTab.trigger('click');
        }
    }

    /* ------------------------------------------------------------------ */
    /*  Background Type Toggle                                            */
    /* ------------------------------------------------------------------ */

    /**
     * Show/hide the background setting rows (image, video, colour)
     * based on the currently selected background-type radio button.
     */
    function toggleBgType() {
        var selectedInfo = $('input[name="admilogu_bg_type"]:checked').val();
        if (selectedInfo === 'image') {
            $('#adminlgb_row-bg-image').show();
            $('#adminlgb_row-bg-video').hide();
            $('#adminlgb_row-bg-video-mute').hide();
            $('#adminlgb_row-bg-color').hide();
        } else if (selectedInfo === 'video') {
            $('#adminlgb_row-bg-image').hide();
            $('#adminlgb_row-bg-video').show();
            $('#adminlgb_row-bg-video-mute').show();
            $('#adminlgb_row-bg-color').hide();
        } else {
            $('#adminlgb_row-bg-image').hide();
            $('#adminlgb_row-bg-video').hide();
            $('#adminlgb_row-bg-video-mute').hide();
            $('#adminlgb_row-bg-color').show();
        }
    }

    // Run on load and on change
    $('input[name="admilogu_bg_type"]').on('change', toggleBgType);
    toggleBgType();

    /* ------------------------------------------------------------------ */
    /*  Custom Login URL Toggle                                           */
    /* ------------------------------------------------------------------ */

    /**
     * Show or hide the "Custom Login URL Slug" row depending on the
     * state of the "Enable Custom Login URL" checkbox.
     */
    function toggleCustomLogin() {
        var isChecked = $('#adminlgb_enable_custom_login').is(':checked');
        if (isChecked) {
            $('#adminlgb_row-custom-slug').show();
        } else {
            $('#adminlgb_row-custom-slug').hide();
        }
    }
    $('#adminlgb_enable_custom_login').on('change', toggleCustomLogin);
    toggleCustomLogin();

    /* ------------------------------------------------------------------ */
    /*  Hide Logo Toggle                                                  */
    /* ------------------------------------------------------------------ */

    function toggleHideLogo() {
        var isChecked = $('input[name="admilogu_hide_logo"]').is(':checked');
        if (isChecked) {
            $('#adminlgb_row-admin-logo, #adminlgb_row-logo-dimensions, #adminlgb_row-logo-details, #adminlgb_row-logo-link-target').hide();
        } else {
            $('#adminlgb_row-admin-logo, #adminlgb_row-logo-dimensions, #adminlgb_row-logo-details, #adminlgb_row-logo-link-target').show();
        }
    }
    $('input[name="admilogu_hide_logo"]').on('change', toggleHideLogo);
    toggleHideLogo();

    /* ------------------------------------------------------------------ */
    /*  DataTables — Login History                                        */
    /* ------------------------------------------------------------------ */

    /** Initialise DataTable on the login-history tables (sorted by time descending). */
    if ($('.adminlgb_history-table').length) {
        $('.adminlgb_history-table').DataTable({
            "order": [[4, "desc"]]
        });
    }

    /* ------------------------------------------------------------------ */
    /*  Telemetry Card Selection                                          */
    /* ------------------------------------------------------------------ */

    /** Highlight the active telemetry preference card on radio change. */
    $('input[name="admilogu_tracking_optin"]').on('change', function () {
        $('.adminlgb-telemetry-card').removeClass('is-active');
        $(this).closest('.adminlgb-telemetry-card').addClass('is-active');
    });
});
