{% comment %}
Template for encrypted password field with copy button.
Based on Django's default password widget with Unfold styling and copy button.
{% endcomment %}

<div class="max-w-2xl relative w-full">
    {% include "django/forms/widgets/input.html" %}

    {% if widget.show_copy_button %}
        <button
            type="button"
            onclick="copyEncryptedPassword(this)"
            class="material-symbols-outlined absolute right-3 top-0 bottom-0 flex items-center justify-center text-base-400 hover:text-primary-600 dark:text-base-500 dark:hover:text-primary-500 cursor-pointer transition-colors"
            title="Copy to clipboard"
        >
            content_copy
        </button>
    {% endif %}
</div>

<script>
function copyEncryptedPassword(button) {
    // Get the input field (previous sibling of button's parent)
    const container = button.parentElement;
    const input = container.querySelector('input');

    if (!input || !input.value) {
        return;
    }

    // For password fields, we need to temporarily change type to text to get the real value
    const originalType = input.type;
    input.type = 'text';
    const value = input.value;
    input.type = originalType;

    // Copy to clipboard
    navigator.clipboard.writeText(value).then(() => {
        // Visual feedback - change icon temporarily
        const originalIcon = button.textContent;
        button.textContent = 'check';
        button.classList.add('text-green-600', 'dark:text-green-500');

        // Reset after 2 seconds
        setTimeout(() => {
            button.textContent = originalIcon;
            button.classList.remove('text-green-600', 'dark:text-green-500');
        }, 2000);
    }).catch(err => {
        console.error('Failed to copy:', err);
        // Show error feedback
        const originalIcon = button.textContent;
        button.textContent = 'error';
        button.classList.add('text-red-600', 'dark:text-red-500');

        setTimeout(() => {
            button.textContent = originalIcon;
            button.classList.remove('text-red-600', 'dark:text-red-500');
        }, 2000);
    });
}
</script>
