import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static targets = ['row'];

    connect() {
        this.rowTargets.forEach(row => this.#syncRow(row));
    }

    toggle(event) {
        this.#syncRow(event.target.closest('[data-mod-optional-target="row"]'));
    }

    #syncRow(row) {
        const modCheckbox = row.querySelector('[data-mod-checkbox]');
        const toggle      = row.querySelector('[data-opt-toggle]');
        const uiOpt       = row.querySelector('[data-ui-opt]');

        if (!modCheckbox || !toggle) return;

        const checked = modCheckbox.checked;
        toggle.classList.toggle('d-none', !checked);

        if (!checked && uiOpt) uiOpt.checked = false;
    }
}
