'use strict';

import {Controller} from '@hotwired/stimulus';
// @ts-ignore
import {Component, getComponent} from '@symfony/ux-live-component';

/**
 * Consent management page: toggles the withdraw confirm sub-step in place of
 * the action buttons — purely client-side, the actual withdrawal is a live
 * action on the confirm button.
 */
export default class extends Controller {
    private comp: Component | null = null;

    async initialize(): Promise<void> {
        try {
            this.comp = await getComponent(this.element as HTMLElement);
            // The Live Component protects external DOM mutations (our `hidden`
            // toggles) from being morphed away — reset to the default state
            // after each render, the correct one once a confirm step was
            // executed or has become obsolete.
            this.comp.on('render:finished', () => this.reset());
        } catch {
            this.comp = null;
        }
    }

    ask(event: Event): void {
        this.toggle(event, true);
    }

    cancel(event: Event): void {
        this.toggle(event, false);
    }

    private reset(): void {
        this.element.querySelectorAll('[data-manage]').forEach((manage) => {
            manage.querySelector('[data-actions]')?.classList.remove('hidden');
            manage.querySelector('[data-confirm]')?.classList.add('hidden');
        });
    }

    private toggle(event: Event, confirming: boolean): void {
        const manage = (event.currentTarget as HTMLElement).closest('[data-manage]');
        if (!manage) {
            return;
        }

        manage.querySelector('[data-actions]')?.classList.toggle('hidden', confirming);
        manage.querySelector('[data-confirm]')?.classList.toggle('hidden', !confirming);
    }
}
