/**
 * SummPress Admin JavaScript
 *
 * Handles JavaScript functionality for the SummPress admin settings page.
 */
(function($) {
    'use strict';

    /**
     * Initialize the admin page functionality.
     */
    function initAdmin() {

        // Copy browser extension endpoint
        $('.summpress-copy-extension-endpoint-url').on('click', function() {
            const text = $('.extension-endpoint-url').text().trim();
            const tempInput = $('<input>');

            $('body').append(tempInput);
            tempInput.val(text).select();

            document.execCommand('copy');

            tempInput.remove();

            $(this).text('Copied!');

            setTimeout(() => {
                $(this).text('Copy');
            }, 2000);
        });


        // Toggle password visibility for API key fields
        $('.summpress-toggle-password, .summpress-toggle-extension-token').on('click', function() {
            const targetId = $(this).data('target');
            const inputField = $('#' + targetId);

            if (inputField.attr('type') === 'password') {
                inputField.attr('type', 'text');
                $(this).text('Hide');
            } else {
                inputField.attr('type', 'password');
                $(this).text('Show');
            }
        });

        // Generate browser extension token
        $('.summpress-generate-extension-token').on('click', function() {
            const targetId = $(this).data('target');
            const inputField = $('#' + targetId);
            inputField.attr('type', 'text');
            $('.summpress-toggle-extension-token').text('Hide');

            const prefix = 'sp_';
            const randomBytes = crypto.getRandomValues(new Uint8Array(16));
            const hex = Array.from(randomBytes).map(b => b.toString(16).padStart(2, '0')).join('');
            const token = prefix + hex;
            inputField.val(token);
        });

        // Highlight active tab
        const currentTab = $('.nav-tab-active').text().trim().toLowerCase();
        $('#summpress_' + currentTab + '_section').addClass('active-section');
    }

    // Initialize when the DOM is ready
    $(document).ready(function() {
        initAdmin();
    });

})(jQuery);
