"use strict";

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

export default class extends Controller {
    static values = {
        source: {type: String, default: "[data-current-user-firstname]"},
    };

    connect() {
        this.apply();
        this.boundApply = this.apply.bind(this);
        document.addEventListener("turbo:render", this.boundApply);
    }

    disconnect() {
        document.removeEventListener("turbo:render", this.boundApply);
    }

    apply() {
        const src = document.querySelector(this.sourceValue);
        if (!src) return;
        const text = src.textContent.trim();
        if (text === "" || text === this.element.textContent) return;
        this.element.textContent = text;
    }
}
