
const initializeFqdnGeneration = (prefix) => {
    const nameField = document.querySelector(`input#id_${prefix}-display_name`);
    if (!nameField) return

    // Try to find array input first (DynamicArrayWidget), then fallback to regular text input
    const fqdnFieldContainer = document.getElementById(`${prefix}-spec.parameters.service.fqdn_container`)
    let fqdnField = null;
    let isArrayField = true;

    if (fqdnFieldContainer) {
        fqdnField = fqdnFieldContainer.querySelector("input.array-item-input")
        if (!fqdnField) {
            // We retry, as there is a field meant to be here, but not rendered yet
            setTimeout(() => {initializeFqdnGeneration(prefix)}, 200)
            return
        }
    } else {
        fqdnField = document.getElementById(`id_${prefix}-spec.parameters.service.fqdn`);
        isArrayField = false;
    }

    if (!fqdnField) return

    if (nameField && fqdnField) {
        const sanitizeForFqdn = (name) => {
            return name
                .toLowerCase()
                .replace(/[^a-z0-9-]/g, '-')  // Replace invalid chars with hyphens
                .replace(/-+/g, '-')           // Collapse multiple hyphens
                .replace(/^-|-$/g, '');        // Trim hyphens from start/end
        }

        const generateFqdn = (instanceName) => {
            if (!instanceName) return '';
            const sanitized = sanitizeForFqdn(instanceName);
            if (!sanitized) return ''
            return `${sanitized}-${fqdnConfig.namespace}.${fqdnConfig.wildcardDns}`;
        }

        nameField.addEventListener('input', function() {
            if (!fqdnField.dataset.manuallyEdited) {
                fqdnField.value = generateFqdn(this.value);
                if (isArrayField) {
                    // Update hidden input for array fields
                    const container = fqdnField.closest('.dynamic-array-widget');
                    if (container && window.updateHiddenInput) {
                        window.updateHiddenInput(container);
                    }
                }
            }
        });

        fqdnField.addEventListener('input', function() {
            this.dataset.manuallyEdited = 'true';
        });

        if (nameField.value && !fqdnField.value) {
            fqdnField.value = generateFqdn(nameField.value);
            if (isArrayField) {
                // Update hidden input for array fields
                const container = fqdnField.closest('.dynamic-array-widget');
                if (container && window.updateHiddenInput) {
                    window.updateHiddenInput(container);
                }
            }
        }
    }
}

const runFqdnInit = () => {
    initializeFqdnGeneration("custom");
    initializeFqdnGeneration("expert");
}

document.addEventListener('DOMContentLoaded', runFqdnInit)
document.body.addEventListener('htmx:afterSwap', function(event) {
    if (event.detail.target.id === 'service-form') runFqdnInit()
});
