import { getComponent } from '@symfony/ux-live-component';

export function formReset(el) {
    const form = el.querySelector('[data-controller~="form-reset"]');
    form?.dispatchEvent(new CustomEvent('reset', {bubbles: true}));
}

export async function selectValue(el) {
    const rawEvent = el.dataset.liveEventParam;
    if (!rawEvent) return;

    const { componentName, eventName } = parseLiveEventParam(rawEvent);

    let componentEl = null;

    if (componentName) {
        componentEl = document.querySelector(`[data-live-name-value="${componentName}"]`);
    } else {
        componentEl = el.closest('[data-controller~="live"]');
    }
    if (!componentEl) {
        console.warn('Composant UX Live non trouvé pour', componentName);
        return;
    }

    const component = await getComponent(componentEl);

    el.addEventListener('change', async (event) => {
        const value = event.target.value;

        const fullEventName = componentName
            ? `name(${componentName})|${eventName}`
            : eventName;
        await component.emit(eventName, { value: value });
    });
}

function parseLiveEventParam(param) {
    const match = param.match(/^name\((.+)\)\|(.+)$/);
    if (match) {
        return {
            componentName: match[1],
            eventName: match[2],
        };
    }

    return {
        componentName: null,
        eventName: param,
    };
}
