/**
 * Handles copying text to the clipboard with a fallback for insecure contexts.
 * In non-HTTPS/non-localhost environments, navigator.clipboard is not available.
 */
export const copyToClipboard = async (text: string): Promise<boolean> => {
    // 1. Try modern Clipboard API first (requires secure context)
    if (navigator.clipboard && window.isSecureContext) {
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (err) {
            console.error('Clipboard API failed:', err);
            // Fall through to fallback
        }
    }

    // 2. Fallback: document.execCommand('copy')
    try {
        const textArea = document.createElement('textarea');
        textArea.value = text;

        // Ensure the textarea is not visible but stays in the DOM
        textArea.style.position = 'fixed';
        textArea.style.left = '-9999px';
        textArea.style.top = '0';
        document.body.appendChild(textArea);

        textArea.focus();
        textArea.select();

        const successful = document.execCommand('copy');
        document.body.removeChild(textArea);

        return successful;
    } catch (err) {
        console.error('Fallback copy failed:', err);
        return false;
    }
};
