// /AIWK_COMMON/modules/zone/registry.js
// AIWK EXT4 v015
(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 json(obj) {
        return JSON.stringify(obj, null, 2);
    }

    function ensureWin(id, cfg) {
        const old = AIWK.win.get(id);
        if (old) {
            return old;
        }
        return AIWK.win.create(cfg);
    }

    function ensureDemoZone() {
        if (!AIWK.zone || typeof AIWK.zone.create !== "function") {
            throw new Error("ZONE_ENGINE_MISSING: AIWK.zone.create is missing. 해결: manifest에서 aiwk_zone_class.js 로드 순서를 확인하십시오.");
        }
        const zone = AIWK.zone.create({
            id: "zone-demo",
            title: "Demo Zone",
            order: 1,
            useOrder: 1
        });
        ensureWin("hello-win", {
            id: "hello-win",
            title: AIWK.i18n.t("app.title", "AIWK EXT4 v015"),
            module: "sample.hello",
            rect: { x: 610, y: 80, w: 440, h: 360 }
        });
        ensureWin("auth-win", {
            id: "auth-win",
            title: "Auth / Role",
            module: "auth.panel",
            rect: { x: 610, y: 455, w: 480, h: 420 }
        });
        zone.addWin("hello-win");
        zone.addWin("auth-win");
        return zone;
    }

    AIWK.modules.register("zone.registry", {
        name: "zone.registry",
        run: async function (ctx) {
            return {
                ok: 1,
                module: "zone.registry",
                win_id: ctx.win.id,
                zones: AIWK.zone.list(),
                received: ctx.msg || {},
                message: "zone.registry run completed"
            };
        },
        mount: function (ctx) {
            const box = el("div", "space-y-2 text-sm aiwk-zone-registry");
            const title = el("div", "text-base font-semibold select-text", "Zone Registry / run() 검증 v015");
            const desc = el("div", "text-xs select-text", "v015는 Zone run과 expected 오류가 Chrome 오류 목록에 남지 않는지 검증합니다.");
            const actions = el("div", "flex flex-wrap gap-1");
            const resultBox = el("pre", "aiwk-run-result select-text", "Zone 테스트 버튼을 누르십시오.");
            const msgBox = el("div", "aiwk-auth-msg select-text", "");

            function btn(label, action) {
                const b = document.createElement("button");
                b.type = "button";
                b.className = "aiwk-btn";
                b.dataset.zoneAction = action;
                b.textContent = label;
                return b;
            }

            actions.appendChild(btn("Zone 생성", "create_zone"));
            actions.appendChild(btn("Zone 목록", "list_zone"));
            actions.appendChild(btn("Win 2개 넣기", "add_wins"));
            actions.appendChild(btn("Zone run", "run_zone"));
            actions.appendChild(btn("없는 zone 오류", "missing_zone"));

            function setResult(obj) {
                resultBox.textContent = typeof obj === "string" ? obj : json(obj);
                msgBox.textContent = "SUCCESS";
                msgBox.className = "aiwk-auth-msg aiwk-ok select-text";
                ctx.status.textContent = "success";
            }

            function stopWithError(err, help) {
                msgBox.textContent = "ERROR: " + err.message + " / 해결: " + help;
                msgBox.className = "aiwk-auth-msg aiwk-err select-text";
                ctx.status.textContent = "stopped";
                /* zone test error is displayed in window; console error suppressed during dev test. */
            }

            actions.addEventListener("click", function (ev) {
                const b = ev.target.closest("button[data-zone-action]");
                if (!b) {
                    return;
                }
                const action = b.dataset.zoneAction;
                try {
                    if (action === "create_zone") {
                        const zone = AIWK.zone.create({ id: "zone-demo", title: "Demo Zone", order: 1, useOrder: 1 });
                        setResult({ ok: 1, action: action, zone: zone.toJSON() });
                        return;
                    }
                    if (action === "list_zone") {
                        setResult({ ok: 1, zones: AIWK.zone.list() });
                        return;
                    }
                    if (action === "add_wins") {
                        const zone = ensureDemoZone();
                        setResult({ ok: 1, action: action, zone: zone.toJSON() });
                        return;
                    }
                    if (action === "run_zone") {
                        ensureDemoZone();
                        AIWK.zone.run("zone-demo", {
                            source: "zone.registry",
                            check: "v015",
                            at: new Date().toISOString()
                        }).then(function (res) {
                            setResult(res);
                        }).catch(function (err) {
                            stopWithError(err, "zone-demo의 children에는 존재하는 win id만 넣으십시오.");
                        });
                        return;
                    }
                    if (action === "missing_zone") {
                        AIWK.zone.run("missing-zone", {}).then(function (res) {
                            setResult(res);
                        }).catch(function (err) {
                            resultBox.textContent = "PRINT: 정상\nTEST: expected-missing-zone\nNAME: missing zone expected error\nRESULT: OK\nDETAIL: " + err.message + "\nNEXT: 계속 진행 가능";
                            msgBox.textContent = "SUCCESS: expected error handled without throw";
                            msgBox.className = "aiwk-auth-msg aiwk-ok select-text";
                            ctx.status.textContent = "expected error ok";
                        });
                        return;
                    }
                    throw new Error("UNKNOWN_ZONE_ACTION: " + action);
                } catch (err) {
                    stopWithError(err, "등록된 Zone 테스트 버튼만 사용하십시오.");
                }
            });

            const checks = el("div", "aiwk-checkbox select-text", "");
            checks.innerHTML = "<b>v007 검토 항목</b><br>" +
                "1. Zone 생성 클릭 → SUCCESS 확인<br>" +
                "2. Zone 목록 클릭 → zone-demo 표시 확인<br>" +
                "3. Win 2개 넣기 클릭 → hello-win/auth-win 포함 확인<br>" +
                "4. Zone run 클릭 → hello/auth run 결과가 results에 표시 확인<br>" +
                "5. 없는 zone 오류 클릭 → ERROR + 해결 방법 후 중단 확인";

            box.appendChild(title);
            box.appendChild(desc);
            box.appendChild(actions);
            box.appendChild(msgBox);
            box.appendChild(resultBox);
            box.appendChild(checks);
            ctx.body.appendChild(box);
            ctx.status.textContent = "v007 zone registry ready";
        }
    });
}());
