// 🧩 Patch pour Symfony UX LiveComponent
import { getValueFromElement } from "./executeMorphdom";
import { Component } from '@symfony/ux-live-component';

function htmlToElement(html) {
    const template = document.createElement('template');
    html = html.trim();
    template.innerHTML = html;
    if (template.content.childElementCount > 1) {
        throw new Error(`Component HTML contains ${template.content.childElementCount} elements, but only 1 root element is allowed.`);
    }
    const child = template.content.firstElementChild;
    if (!child) {
        throw new Error('Child not found');
    }
    if (!(child instanceof HTMLElement)) {
        throw new Error(`Created element is not an HTMLElement: ${html.trim()}`);
    }
    return child;
}

// ✅ Patch du processRerender pour utiliser ta fonction personnalisée
Component.prototype.processRerender = function (html, backendResponse) {
    const controls = { shouldRender: true };
    this.hooks.triggerHook('render:started', html, backendResponse, controls);
    if (!controls.shouldRender) return;

    if (backendResponse.response.headers.get('Location')) {
        if (this.isTurboEnabled()) {
            Turbo.visit(backendResponse.response.headers.get('Location'));
        } else {
            window.location.href = backendResponse.response.headers.get('Location') || '';
        }
        return;
    }

    this.hooks.triggerHook('loading.state:finished', this.element);

    const modifiedModelValues = {};
    Object.keys(this.valueStore.getDirtyProps()).forEach((modelName) => {
        modifiedModelValues[modelName] = this.valueStore.get(modelName);
    });

    let newElement;
    try {
        newElement = htmlToElement(html);
        if (!newElement.matches('[data-controller~=live]')) {
            throw new Error('A live component template must contain a single root controller element.');
        }
    } catch (error) {
        console.error(`There was a problem with the '${this.name}' component HTML returned:`, { id: this.id });
        throw error;
    }

    this.externalMutationTracker.handlePendingChanges();
    this.externalMutationTracker.stop();

    // ⚡ Appel de TA fonction globale
    window.executeMorphdom(
        this.element,
        newElement,
        this.unsyncedInputsTracker.getUnsyncedInputs(),
        (element) => getValueFromElement(element, this.valueStore),
        this.externalMutationTracker
    );

    this.externalMutationTracker.start();

    const newProps = this.elementDriver.getComponentProps();
    this.valueStore.reinitializeAllProps(newProps);

    const eventsToEmit = this.elementDriver.getEventsToEmit();
    const browserEventsToDispatch = this.elementDriver.getBrowserEventsToDispatch();

    Object.keys(modifiedModelValues).forEach((modelName) => {
        this.valueStore.set(modelName, modifiedModelValues[modelName]);
    });

    eventsToEmit.forEach(({ event, data, target, componentName }) => {
        if (target === 'up') {
            this.emitUp(event, data, componentName);
            return;
        }
        if (target === 'self') {
            this.emitSelf(event, data);
            return;
        }
        this.emit(event, data, componentName);
    });

    browserEventsToDispatch.forEach(({ event, payload }) => {
        this.element.dispatchEvent(new CustomEvent(event, {
            detail: payload,
            bubbles: true,
        }));
    });

    this.hooks.triggerHook('render:finished', this);
};
