/**
 * DiveWP AI Capabilities JavaScript
 *
 * Handles the config modal interactions.
 *
 * @package DiveWP
 * @version 1.0.0
 */

jQuery(document).ready(function($) {
    'use strict';

    const modal = $('.divewp-ai-config-modal');
    if (!modal.length) {
        return;
    }

    function openModal() {
        modal.attr('aria-hidden', 'false').addClass('open');
    }

    function closeModal() {
        modal.attr('aria-hidden', 'true').removeClass('open');
    }

    function getConfigText() {
        const code = $('#divewp-ai-config-code');
        if (!code.length) {
            return '';
        }
        return code.text().trim();
    }

    function setCopyState($button, isCopied) {
        const copyLabel = $button.data('copy-label') || $button.text();
        const copiedLabel = $button.data('copied-label') || 'Copied';
        $button.text(isCopied ? copiedLabel : copyLabel);
    }

    function fallbackCopy(text) {
        const $temp = $('<textarea>').val(text).appendTo('body');
        $temp[0].select();
        try {
            document.execCommand('copy');
        } catch (err) {
            // Silent fallback
        }
        $temp.remove();
    }

    $(document).on('click', '.divewp-ai-config-trigger', function(e) {
        e.preventDefault();
        const targetId = $(this).data('modal-target');
        if (targetId && modal.attr('id') !== targetId) {
            return;
        }
        openModal();
    });

    $(document).on('click', '.divewp-ai-config-modal__close, .divewp-ai-config-modal__overlay', function(e) {
        e.preventDefault();
        closeModal();
    });

    $(document).on('click', '.divewp-ai-config-modal__copy', function(e) {
        e.preventDefault();
        const $button = $(this);
        const text = getConfigText();
        if (!text) {
            return;
        }

        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).then(function() {
                setCopyState($button, true);
                setTimeout(function() { setCopyState($button, false); }, 2000);
            }).catch(function() {
                fallbackCopy(text);
                setCopyState($button, true);
                setTimeout(function() { setCopyState($button, false); }, 2000);
            });
        } else {
            fallbackCopy(text);
            setCopyState($button, true);
            setTimeout(function() { setCopyState($button, false); }, 2000);
        }
    });

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && modal.hasClass('open')) {
            closeModal();
        }
    });
});
