'use strict';

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

export default class extends Controller {
    static values = {
        nameUrl: String,
    };

    static targets = ["modal", "name", "webauthnButton"];

    declare readonly nameUrlValue: string;
    declare readonly hasModalTarget: boolean;
    declare readonly modalTarget: HTMLElement;
    declare readonly hasNameTarget: boolean;
    declare readonly nameTarget: HTMLInputElement;
    declare readonly hasWebauthnButtonTarget: boolean;
    declare readonly webauthnButtonTarget: HTMLElement;

    open() {
        if (this.hasModalTarget) {
            this.modalTarget.style.display = 'flex';
        }
        if (this.hasNameTarget) {
            this.nameTarget.value = '';
            this.nameTarget.focus();
        }
    }

    close() {
        if (this.hasModalTarget) {
            this.modalTarget.style.display = 'none';
        }
    }

    async create() {
        const name = this.hasNameTarget ? this.nameTarget.value.trim() : '';

        try {
            await fetch(this.nameUrlValue, {
                method: 'POST',
                headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
                body: JSON.stringify({name}),
            });
        } catch (e) {
        }

        this.close();

        if (this.hasWebauthnButtonTarget) {
            this.webauthnButtonTarget.click();
        }
    }

    reload() {
        window.location.reload();
    }
}
