// retoor <retoor@molodetz.nl>

import { devrantSession } from "./DevRantSession.js";

function el(tag, props = {}, children = []) {
    const node = document.createElement(tag);
    for (const [key, value] of Object.entries(props)) {
        if (key === "class") node.className = value;
        else if (key === "text") node.textContent = value;
        else if (key === "html") node.innerHTML = value;
        else if (value === true) node.setAttribute(key, "");
        else if (value !== false && value !== null) node.setAttribute(key, value);
    }
    for (const child of children) {
        if (child) node.appendChild(child);
    }
    return node;
}

export class DevRantLogin {
    constructor(mount) {
        this.mount = mount;
        this.render();
        devrantSession.onChange(() => this.render());
    }

    render() {
        this.mount.innerHTML = "";
        const bar = el("div", { class: "api-tester devrant-login" });
        if (devrantSession.isLoggedIn()) {
            bar.appendChild(
                el("span", {
                    class: "try-note",
                    text: `Authenticated as ${devrantSession.username || "user " + devrantSession.auth.user_id} (token #${devrantSession.auth.token_id}).`,
                }),
            );
            const out = el("button", { type: "button", class: "btn try-send", text: "Log out" });
            out.addEventListener("click", () => devrantSession.logout());
            bar.appendChild(out);
            this.mount.appendChild(bar);
            return;
        }
        const user = el("input", { class: "param-input", type: "text", placeholder: "username or email" });
        const pass = el("input", { class: "param-input", type: "password", placeholder: "password" });
        const docs = window.DEVPLACE_DOCS || {};
        if (docs.username) user.value = docs.username;
        const send = el("button", { type: "button", class: "btn btn-primary try-send", text: "Log in" });
        const note = el("span", { class: "try-note", text: "Log in once to enable the authenticated widgets on every devRant page." });
        send.addEventListener("click", async () => {
            send.disabled = true;
            note.textContent = "Logging in...";
            try {
                await devrantSession.login(user.value.trim(), pass.value);
            } catch (error) {
                note.textContent = error.message || "Login failed";
                send.disabled = false;
            }
        });
        bar.appendChild(el("div", { class: "auth-field" }, [el("label", { text: "Username" }), user]));
        bar.appendChild(el("div", { class: "auth-field" }, [el("label", { text: "Password" }), pass]));
        bar.appendChild(send);
        bar.appendChild(note);
        this.mount.appendChild(bar);
    }
}
