// /AIWK_COMMON/modules/comm/nr_test.js
// AIWK EXT4 v027 · Node-RED 통신 테스트창: 입력 레이아웃 안정화
(function () {
    "use strict";

    const AIWK = window.AIWK;
    function el(tag, cls, text) { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; }
    function pretty(v) { try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); } }
    function nowIso(){ return new Date().toISOString(); }
    function makeBtn(label, fn, extra) { const b = document.createElement("button"); b.type = "button"; b.className = "aiwk-btn" + (extra ? " " + extra : ""); b.textContent = label; b.onclick = fn; return b; }
    function makeLogTools(out) { const line=el("div","aiwk-comm-logline",""); const ck=document.createElement("input"); ck.type="checkbox"; ck.checked=AIWK.comm?AIWK.comm.getLogEnabled():true; const label=document.createElement("label"); label.appendChild(ck); label.appendChild(document.createTextNode(" 로그")); const trash=makeBtn("🗑",function(){out.textContent="";},"aiwk-comm-trash"); trash.title="로그 삭제"; ck.onchange=function(){ if(AIWK.comm) AIWK.comm.setLogEnabled(ck.checked); }; line.appendChild(label); line.appendChild(trash); line.appendChild(el("span","select-text","5000줄 초과 시 자동 정리")); return {line:line, checkbox:ck}; }
    function logTo(out, title, obj) { if (AIWK.comm) AIWK.comm.appendToBox(out, title, obj, AIWK.comm.getLogEnabled(), 5000); }
    function fullField(labelText, control) {
        const wrap = el("div", "aiwk-comm-field-full", "");
        const lab = el("div", "aiwk-comm-field-label", labelText);
        control.style.width = "100%";
        control.style.boxSizing = "border-box";
        control.style.display = "block";
        wrap.appendChild(lab);
        wrap.appendChild(control);
        return wrap;
    }

    AIWK.modules.register("comm.nr_test", {
        name: "comm.nr_test",
        run: async function(ctx) { return { ok: 1, module: "comm.nr_test", win_id: ctx.win.id, status: AIWK.comm ? AIWK.comm.status() : {}, received: ctx.msg || {}, message: "Node-RED test window run completed" }; },
        mount: function(ctx) {
            const box = el("div", "space-y-2 text-sm select-text");
            const title = el("div", "text-base font-semibold", "Node-RED 통신 테스트창 v059");
            const desc = el("div", "text-xs", "userdir_A1의 aiwk-config/aiwk-in/out 구조 기준입니다. 기본은 WSS를 통해 Node-RED endpoint로 보냅니다.");
            const statusBar = el("div", "aiwk-comm-status-row", "");
            const status = el("pre", "aiwk-auth-payload select-text", "");
            const row = el("div", "aiwk-comm-toolbar", "");
            const target = document.createElement("input"); target.className = "aiwk-input"; target.placeholder = "Node-RED 대상 endpoint";
            const action = document.createElement("input"); action.className = "aiwk-input"; action.value = "aiwk_ping"; action.placeholder = "action";
            const payload = document.createElement("textarea"); payload.className = "aiwk-input"; payload.setAttribute("data-aiwk-textarea-key", "nr_payload"); payload.value = JSON.stringify({ text:"Node-RED 테스트", at:nowIso() }, null, 2);
            const out = el("pre", "aiwk-run-result select-text", "");
            const logTools = makeLogTools(out);
            function defaultTarget(){ const p=AIWK.comm.getProfile(); const room=p.roomId?String(p.roomId)+"@":""; return "aiwk://"+room+[p.group||"home", p.project||"IG_CRM", "N1"].join(".")+"#node-red"; }
            function refresh(){ if(!target.value) target.value = defaultTarget(); const s=AIWK.comm ? AIWK.comm.status() : { error:"AIWK.comm missing" }; status.textContent = pretty(s); if(AIWK.comm) AIWK.comm.renderStatusBar(statusBar); ctx.status.textContent = "NR 상태: " + ((s.indicators && s.indicators.nr && s.indicators.nr.text) || "?") + " / " + (s.indicator_text || ""); }
            row.appendChild(makeBtn("WSS 접속", function(){ logTo(out,"WSS 접속",AIWK.comm.wssConnect({ force:false })); setTimeout(refresh,300); }));
            row.appendChild(makeBtn("Node-RED 전송", function(){ let p={}; try{p=JSON.parse(payload.value||"{}");}catch(e){p={raw:payload.value};} logTo(out,"Node-RED 전송",AIWK.comm.noderedSend(target.value, action.value, p)); refresh(); }));
            row.appendChild(makeBtn("기본 대상 복원", function(){ target.value=defaultTarget(); refresh(); }));
            row.appendChild(makeBtn("상태 갱신", refresh));
            box.appendChild(title); box.appendChild(desc); box.appendChild(statusBar); box.appendChild(status); box.appendChild(row); box.appendChild(fullField("Node-RED 대상", target)); box.appendChild(fullField("action", action)); box.appendChild(fullField("payload", payload)); box.appendChild(logTools.line); box.appendChild(out);
            ctx.body.appendChild(box); refresh();
            AIWK.events.on("comm:status", refresh);
            AIWK.events.on("comm:wss:message", function(packet){ logTo(out,"Node-RED/WSS 수신",packet); refresh(); });
        }
    });
}());
