// /AIWK_COMMON/modules/win/registry.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 safeJson(obj) {
        return JSON.stringify(obj, null, 2);
    }

    AIWK.modules.register("win.registry", {
        name: "win.registry",
        run: async function (ctx) {
            return {
                ok: 1,
                module: "win.registry",
                win_id: ctx.win.id,
                count: AIWK.win.list().length,
                wins: AIWK.win.list(),
                received: ctx.msg || {},
                message: "win.registry run completed"
            };
        },
        mount: function (ctx) {
            const box = el("div", "space-y-2 text-sm aiwk-win-registry");
            const title = el("div", "text-base font-semibold select-text", "Win Registry / run() 검증 v027");
            const desc = el("div", "text-xs select-text", "v027은 Win 목록/제목/버전 drift와 run() 결과를 검증합니다.");

            const actions = el("div", "flex flex-wrap gap-1");
            function btn(label, action) {
                const b = document.createElement("button");
                b.type = "button";
                b.className = "aiwk-btn";
                b.dataset.winAction = action;
                b.textContent = label;
                return b;
            }
            actions.appendChild(btn("목록 새로고침", "refresh"));
            actions.appendChild(btn("hello-win run", "run_hello"));
            actions.appendChild(btn("auth-win run", "run_auth"));
            actions.appendChild(btn("없는 win 오류", "run_missing"));

            const listBox = el("pre", "aiwk-registry-list select-text", "");
            const resultBox = el("pre", "aiwk-run-result select-text", "");
            const errorBox = el("div", "aiwk-auth-msg select-text", "");
            const checks = el("div", "aiwk-checkbox select-text", "");
            checks.innerHTML = "<b>v027 검토 항목</b><br>" +
                "1. Win 목록에 hello-win / auth-win / registry-win 표시<br>" +
                "2. hello-win run 클릭 → OK JSON 확인<br>" +
                "3. auth-win run 클릭 → 현재 role 포함 OK JSON 확인<br>" +
                "4. 없는 win 오류 클릭 → ERROR + 해결 방법 표시 후 중단 확인<br>" +
                "5. 제목이 이전 v023/v024로 남으면 페이지 새로고침 또는 창 재생성 필요<br>6. 기존 드래그/리사이즈/저장/textarea/auth 기능 유지 확인";

            function renderList() {
                listBox.textContent = safeJson(AIWK.win.list());
                ctx.status.textContent = "win count:" + AIWK.win.list().length;
            }

            async function runWin(id) {
                errorBox.textContent = "";
                errorBox.className = "aiwk-auth-msg select-text";
                const res = await AIWK.win.run(id, {
                    source: "win.registry",
                    check: "v027",
                    at: new Date().toISOString()
                });
                resultBox.textContent = safeJson(res);
                ctx.status.textContent = "run ok: " + id;
            }

            actions.addEventListener("click", function (ev) {
                const b = ev.target.closest("button[data-win-action]");
                if (!b) {
                    return;
                }
                const action = b.dataset.winAction;
                try {
                    if (action === "refresh") {
                        renderList();
                        resultBox.textContent = "";
                        return;
                    }
                    if (action === "run_hello") {
                        runWin("hello-win").then(renderList).catch(function (err) {
                            errorBox.textContent = "ERROR: " + err.message + " / 해결: module 등록과 win id를 확인하십시오.";
                            errorBox.className = "aiwk-auth-msg aiwk-err select-text";
                            ctx.status.textContent = "run stopped";
                            /* real run error is displayed in window; console error suppressed during dev test. */
                        });
                        return;
                    }
                    if (action === "run_auth") {
                        runWin("auth-win").then(renderList).catch(function (err) {
                            errorBox.textContent = "ERROR: " + err.message + " / 해결: module 등록과 win id를 확인하십시오.";
                            errorBox.className = "aiwk-auth-msg aiwk-err select-text";
                            ctx.status.textContent = "run stopped";
                            /* real run error is displayed in window; console error suppressed during dev test. */
                        });
                        return;
                    }
                    if (action === "run_missing") {
                        AIWK.win.run("missing-win", {}).then(function (res) {
                            resultBox.textContent = safeJson(res);
                        }).catch(function (err) {
                            errorBox.textContent = "ERROR: " + err.message + " / 해결: Win 목록에서 존재하는 id만 실행하십시오.";
                            errorBox.className = "aiwk-auth-msg aiwk-err select-text";
                            ctx.status.textContent = "run stopped as expected";
                            resultBox.textContent = "PRINT: 정상\nTEST: expected-missing-win\nNAME: missing win expected error\nRESULT: OK\nDETAIL: " + err.message + "\nNEXT: 계속 진행 가능";
                        });
                        return;
                    }
                    throw new Error("UNKNOWN_ACTION: " + action + ". 해결: 등록된 버튼 action만 사용하십시오.");
                } catch (err) {
                    errorBox.textContent = "ERROR: " + err.message;
                    errorBox.className = "aiwk-auth-msg aiwk-err select-text";
                    ctx.status.textContent = "action stopped";
                    /* action error is displayed in window; console error suppressed during dev test. */
                    return;
                }
            });

            box.appendChild(title);
            box.appendChild(desc);
            box.appendChild(actions);
            box.appendChild(errorBox);
            box.appendChild(listBox);
            box.appendChild(resultBox);
            box.appendChild(checks);
            ctx.body.appendChild(box);
            renderList();
        }
    });
}());
