// /AIWK_COMMON/modules/auth/panel.js
// AIWK EXT4 v027
(function () {
    "use strict";

    const AIWK = window.AIWK;

    function el(tag, className, text) {
        const node = document.createElement(tag);
        if (className) node.className = className;
        if (text !== undefined) node.textContent = text;
        return node;
    }

    function getProfile() {
        try {
            return AIWK.store.get("profile", {}) || {};
        } catch (err) {
            return {};
        }
    }

    AIWK.modules.register("auth.panel", {
        name: "auth.panel",
        run: async function (ctx) {
            return {
                ok: 1,
                module: "auth.panel",
                win_id: ctx.win.id,
                role: AIWK.auth.role,
                mode: AIWK.auth.mode || "empty",
                profile: getProfile(),
                received: ctx.msg || {},
                message: "auth.panel run completed"
            };
        },
        mount: function (ctx) {
            const box = el("div", "space-y-2 text-sm aiwk-auth-panel");
            const title = el("div", "text-base font-semibold select-text", "AIWK 매인 제어창 상태 v027");
            const desc = el("div", "text-xs select-text", "이 창은 로그인 이후 현재 탭에서 동작하는 AIWK 매인 제어창입니다. 토큰 입력과 검증은 EXT 아이콘 클릭 시 뜨는 접속창에서 처리합니다.");
            const roleLine = el("div", "aiwk-auth-role select-text", "");
            const modeLine = el("div", "aiwk-auth-mode select-text", "");
            const commStatusBar = el("div", "aiwk-comm-status-row", "");
            const profileBox = el("pre", "aiwk-auth-payload select-text", "");
            const msg = el("div", "aiwk-auth-msg select-text", "");
            const actions = el("div", "aiwk-auth-actions flex flex-wrap gap-1", "");

            function makeBtn(label, action) {
                const btn = document.createElement("button");
                btn.type = "button";
                btn.className = "aiwk-btn";
                btn.dataset.authAction = action;
                btn.textContent = label;
                return btn;
            }
            actions.appendChild(makeBtn("TEST 런처", "open_test"));
            actions.appendChild(makeBtn("통신 3창", "open_comm_test"));
            actions.appendChild(makeBtn("너의 기능은?", "whatcanido"));
            actions.appendChild(makeBtn("너의 사용법은?", "help"));
            actions.appendChild(makeBtn("로그아웃", "logout"));

            const checks = el("div", "aiwk-checkbox select-text", "");
            checks.innerHTML = "<b>v023 검토 항목</b><br>" +
                "1. EXT 아이콘 클릭 → v0.8.1 방식 접속창 표시 확인<br>" +
                "2. 토큰 비움 → guest로 현재 탭 AIWK 창 열림 확인<br>" +
                "3. 틀린 토큰 입력 → popup에서 중단, 현재 탭 창 열리지 않음 확인<br>" +
                "4. USER 토큰 → editor/편집자 확인<br>" +
                "5. ADMIN 토큰 → dev/개발자 확인<br>" +
                "" +
                "7. TEST 런처 → 창 목록/전체 selftest 확인<br>8. 통신 3창 → BUS/WSS/Node-RED 각각 연결 테스트 확인";

            function safeProfileForView(profile) {
                profile = Object.assign({}, profile || {});
                if (profile.authToken) profile.authToken = "***";
                if (profile.token) profile.token = "***";
                return profile;
            }

            function render() {
                const profile = getProfile();
                if (AIWK.comm && typeof AIWK.comm.renderStatusBar === "function") AIWK.comm.renderStatusBar(commStatusBar);
                const userType = AIWK.auth.getUserType ? AIWK.auth.getUserType() : ((AIWK.auth.payload && AIWK.auth.payload.user_type) || "GUEST");
                const roleName = (AIWK.auth.role === "dev") ? "개발자" : ((AIWK.auth.role === "editor") ? "편집자" : ((AIWK.auth.role === "host") ? "특수 계정" : "손님"));
                roleLine.textContent = "현재 권한: " + (AIWK.auth.role || "guest") + " / " + roleName + " / " + userType;
                modeLine.textContent = "mode: " + (AIWK.auth.mode || "empty");
                profileBox.textContent = JSON.stringify({
                    auth: {
                        role: AIWK.auth.role || "guest",
                        user_type: userType,
                        role_name: roleName,
                        mode: AIWK.auth.mode || "empty",
                        payload: AIWK.auth.getPayload ? AIWK.auth.getPayload() : {}
                    },
                    profile: safeProfileForView(profile)
                }, null, 2);
                const commText = AIWK.comm && AIWK.comm.status ? (AIWK.comm.status().indicator_text || "") : "";
                ctx.status.textContent = "role:" + (AIWK.auth.role || "guest") + " / " + roleName + " / " + commText;
            }

            actions.addEventListener("click", async function (ev) {
                const btn = ev.target.closest("button[data-auth-action]");
                if (!btn) return;
                const action = btn.dataset.authAction;
                try {
                    if (action === "open_test") {
                        if (AIWK.ext4 && AIWK.ext4.openTest) {
                            await AIWK.ext4.openTest();
                            msg.textContent = "OK: TEST 런처를 열었습니다.";
                            msg.className = "aiwk-auth-msg aiwk-ok select-text";
                        } else {
                            throw new Error("TEST_LAUNCHER_UNAVAILABLE");
                        }
                    } else if (action === "open_comm_test") {
                        if (AIWK.ext4 && AIWK.ext4.openCommTest) {
                            await AIWK.ext4.openCommTest();
                            msg.textContent = "OK: BUS/WSS/Node-RED 통신 3창을 열었습니다.";
                            msg.className = "aiwk-auth-msg aiwk-ok select-text";
                        } else {
                            throw new Error("COMM_TEST_UNAVAILABLE");
                        }
                    } else if (action === "whatcanido") {
                        const res = await AIWK.bus.ask("auth-win", "너의 기능은?", { source: "auth.panel" });
                        msg.textContent = JSON.stringify(res, null, 2);
                        msg.className = "aiwk-auth-msg aiwk-ok select-text";
                    } else if (action === "help") {
                        const res = await AIWK.bus.ask("auth-win", "너의 사용법은?", { source: "auth.panel" });
                        msg.textContent = JSON.stringify(res, null, 2);
                        msg.className = "aiwk-auth-msg aiwk-ok select-text";
                    } else if (action === "logout") {
                        AIWK.auth.clearToken();
                        msg.textContent = "OK: 로그아웃했습니다. 다시 인증하려면 EXT 아이콘을 눌러 접속창에서 입력하십시오.";
                        msg.className = "aiwk-auth-msg aiwk-ok select-text";
                    }
                    render();
                } catch (err) {
                    msg.textContent = "ERROR: " + (err && err.message ? err.message : String(err));
                    msg.className = "aiwk-auth-msg aiwk-err select-text";
                    ctx.status.textContent = "auth panel error";
                }
            });

            AIWK.events.on("auth:change", render);
            AIWK.events.on("comm:status", render);
            box.appendChild(title);
            box.appendChild(desc);
            box.appendChild(roleLine);
            box.appendChild(modeLine);
            box.appendChild(commStatusBar);
            box.appendChild(actions);
            box.appendChild(msg);
            box.appendChild(profileBox);
            box.appendChild(checks);
            ctx.body.appendChild(box);
            render();
        }
    });
}());
