// /AIWK_COMMON/win/aiwk_win_render.js
// AIWK v102-stage4.9-ext4-store-resize-noise-fix
(function () {
    "use strict";

    const AIWK = window.AIWK;

    function iconForModule(moduleName, title) {
        const key = String(moduleName || title || "").toLowerCase();
        if (key.indexOf("chart") >= 0 || key.indexOf("apex") >= 0) { return "📈"; }
        if (key.indexOf("insta") >= 0 || key.indexOf("instagram") >= 0) { return "💬"; }
        if (key.indexOf("tiktok") >= 0) { return "🎵"; }
        if (key.indexOf("wss") >= 0 || key.indexOf("comm") >= 0 || key.indexOf("bus") >= 0 || key.indexOf("nr") >= 0) { return "🔌"; }
        if (key.indexOf("test") >= 0 || key.indexOf("dev") >= 0) { return "🧪"; }
        if (key.indexOf("auth") >= 0) { return "🔐"; }
        if (key.indexOf("site") >= 0 || key.indexOf("profile") >= 0) { return "🌐"; }
        if (key.indexOf("zone") >= 0 || key.indexOf("group") >= 0) { return "🧩"; }
        return "🪟";
    }

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

    AIWK.winRender = {
        applyAuthToButton: function (btn) {
            const needRole = btn.dataset.needRole || "guest";
            if (!AIWK.auth.can(needRole)) {
                btn.disabled = false;
                btn.setAttribute("aria-disabled", "true");
                btn.dataset.locked = "1";
                btn.classList.add("aiwk-disabled");
                btn.classList.add("aiwk-locked");
                btn.title = AIWK.i18n.t("auth.locked", "권한 없음") + " / need=" + needRole + " / role=" + AIWK.auth.role + " / 토큰을 입력하십시오.";
            } else {
                btn.disabled = false;
                btn.removeAttribute("aria-disabled");
                btn.dataset.locked = "0";
                btn.classList.remove("aiwk-disabled");
                btn.classList.remove("aiwk-locked");
                btn.title = "need=" + needRole + " / role=" + AIWK.auth.role;
            }
        },
        refreshAuth: function (win) {
            if (!win || !win.el) {
                return;
            }
            if (win.parts && win.parts.role) {
                win.parts.role.textContent = AIWK.auth.role;
                win.parts.role.dataset.role = AIWK.auth.role;
            }
            if (win.parts && win.parts.clientBadge) {
                const profile = AIWK.store ? AIWK.store.get("profile", {}) : {};
                const clientId = String((profile && profile.clientId) || "").trim() || "?";
                win.parts.clientBadge.textContent = clientId;
                win.parts.clientBadge.title = "client_id: " + clientId;
            }
            win.el.querySelectorAll("button[data-need-role]").forEach(function (btn) {
                AIWK.winRender.applyAuthToButton(btn);
            });
        },
        build: function (cfg) {
            const el = document.createElement("section");
            el.className = "aiwk-win fixed flex flex-col rounded-xl shadow-xl overflow-hidden";
            el.dataset.winId = cfg.id;
            el.dataset.projectId = cfg.project_id || "default";
            el.dataset.stage1Id = cfg.stage1_id || "st1_control";
            el.dataset.stage2Id = cfg.stage2_id || "st2_default";
            el.dataset.singleton = cfg.singleton !== undefined ? String(cfg.singleton) : "1";

            const header = document.createElement("header");
            header.className = "aiwk-win-header flex items-center gap-1 px-2 py-1";

            const winMenuWrap = document.createElement("span");
            winMenuWrap.className = "aiwk-win-menu-wrap aiwk-nobr";
            const winMenuBtn = document.createElement("button");
            winMenuBtn.type = "button";
            winMenuBtn.className = "aiwk-win-menu-btn aiwk-nobr";
            winMenuBtn.dataset.action = "window-menu";
            winMenuBtn.dataset.needRole = "guest";
            winMenuBtn.textContent = "☰";
            winMenuBtn.title = "창 메뉴 / 접기·펼침·편집·테스트";
            const winMenuPanel = document.createElement("div");
            winMenuPanel.className = "aiwk-win-menu-panel";
            function normalizeMenuRows(rows) {
                const out = [];
                if (!Array.isArray(rows)) return out;
                rows.forEach(function (row) {
                    if (row === "--" || (row && row.sep)) {
                        out.push({ sep: 1 });
                        return;
                    }
                    if (!row || typeof row !== "object") return;
                    out.push(row);
                });
                return out;
            }
            function buildWindowMenuRows() {
                const commonRows = [
                    { label: "모드", kind: "label" },
                    { label: "운영용 모드", kind: "action", value: "mode-viewer", role: "guest", title: "보기/운영용 template로 전환" },
                    { label: "편집용 모드", kind: "action", value: "mode-editor", role: "editor", title: "위치·스킨·일부 설정 편집" },
                    { label: "개발자 모드", kind: "action", value: "mode-dev", role: "dev", title: "selector/JS/flow/상세 로그 편집" },
                    { sep: 1 },
                    { label: "창", kind: "label" },
                    { label: "접기", kind: "inline", buttons: [
                        { label: "0", kind: "fold", value: "0", role: "guest", title: "펼침" },
                        { label: "1", kind: "fold", value: "1", role: "guest", title: "1단 접기" },
                        { label: "2", kind: "fold", value: "2", role: "guest", title: "2단 노드" },
                        { label: "3", kind: "fold", value: "3", role: "guest", title: "3단 아이콘" }
                    ] },
                    { label: "투명도", kind: "inline", buttons: [
                        { label: "1", kind: "action", value: "alpha-1", role: "guest", title: "불투명 100%" },
                        { label: "2", kind: "action", value: "alpha-2", role: "guest", title: "투명도 88%" },
                        { label: "3", kind: "action", value: "alpha-3", role: "guest", title: "투명도 72%" },
                        { label: "4", kind: "action", value: "alpha-4", role: "guest", title: "투명도 56%" },
                        { label: "5", kind: "action", value: "alpha-5", role: "guest", title: "투명도 40%" }
                    ] },
                    { label: "스킨", kind: "inline", buttons: [
                        { label: "D", kind: "action", value: "skin-d", role: "guest", title: "Dark / nssb-dark" },
                        { label: "W", kind: "action", value: "skin-w", role: "guest", title: "White / nssb-light" },
                        { label: "C", kind: "action", value: "skin-c", role: "guest", title: "Cyan" },
                        { label: "P", kind: "action", value: "skin-p", role: "guest", title: "Purple" }
                    ] },
                    { sep: 1 },
                    { label: "기능", kind: "label" },
                    { label: "실행", kind: "action", value: "run", role: "guest", title: "모듈 기본 run() 실행. 아직 없는 모듈은 준비 상태 표시" },
                    { label: "테스트", kind: "action", value: "test", role: "guest", requiredModule: "dev.test_launcher" },
                    { label: "설정", kind: "action", value: "function-setting", role: "editor" },
                    { label: "로그", kind: "action", value: "log", role: "guest" },
                    { sep: 1 },
                    { label: "설계도", kind: "label" },
                    { label: "창 내보내기", kind: "action", value: "export-window", role: "guest" },
                    { label: "창 불러오기", kind: "action", value: "import-window", role: "editor" },
                    { label: "전체 내보내기", kind: "action", value: "export-layout", role: "guest" },
                    { label: "전체 불러오기", kind: "action", value: "import-layout", role: "dev" },
                    { sep: 1 },
                    { label: "구조", kind: "label" },
                    { label: "템플릿 변경", kind: "action", value: "template-next", role: "editor" },
                    { label: "스킨 변경", kind: "action", value: "skin-next", role: "editor" },
                    { label: "메뉴 수정", kind: "action", value: "menu-edit", role: "editor" },
                    { label: "JS 보기", kind: "action", value: "js", role: "dev" },
                    { label: "디자인", kind: "action", value: "design", role: "editor" },
                    { label: "패키지/팔레트", kind: "action", value: "package-palette", role: "editor" },
                    { sep: 1 },
                    { label: "폴더 route", kind: "action", value: "route-info", role: "guest" },
                    { sep: 1 },
                    { label: "닫기", kind: "action", value: "close", role: "guest" }
                ];
                const winRows = normalizeMenuRows(cfg.menuRows || cfg.menu || []);
                const moduleRows = [];
                try {
                    const mod = AIWK.modules && typeof AIWK.modules.get === "function" ? AIWK.modules.get(cfg.module || cfg.moduleName || "") : null;
                    const raw = mod && (typeof mod.menuRows === "function" ? mod.menuRows({ cfg: cfg }) : mod.menuRows);
                    moduleRows.push.apply(moduleRows, normalizeMenuRows(raw || []));
                } catch (err) {}
                if (winRows.length || moduleRows.length) {
                    return commonRows.concat([{ sep: 1 }, { label: "창/모듈 메뉴", kind: "label" }], winRows, moduleRows);
                }
                return commonRows;
            }
            const winMenuRows = buildWindowMenuRows();
            function moduleExists(name) {
                if (!name) return true;
                try { return !!(AIWK.modules && typeof AIWK.modules.get === "function" && AIWK.modules.get(name)); } catch (err) { return false; }
            }
            function appendMenuButton(panel, row) {
                if (row && row.requiredModule && !moduleExists(row.requiredModule)) {
                    return;
                }
                if (row.sep) {
                    const sep = document.createElement("div");
                    sep.className = "aiwk-win-menu-sep";
                    panel.appendChild(sep);
                    return;
                }
                if (row.kind === "label") {
                    const label = document.createElement("div");
                    label.className = "aiwk-win-menu-label select-text";
                    label.textContent = row.label || "메뉴";
                    panel.appendChild(label);
                    return;
                }
                if (row.kind === "inline") {
                    const line = document.createElement("div");
                    line.className = "aiwk-win-menu-inline";
                    if (row.label) {
                        const lab = document.createElement("span");
                        lab.className = "aiwk-win-menu-inline-label select-text";
                        lab.textContent = row.label;
                        line.appendChild(lab);
                    }
                    (row.buttons || []).forEach(function (child) {
                        appendMenuButton(line, child);
                    });
                    panel.appendChild(line);
                    return;
                }
                if (row.kind === "submenu") {
                    const wrap = document.createElement("div");
                    wrap.className = "aiwk-win-submenu-wrap aiwk-nobr";
                    const b = document.createElement("button");
                    b.type = "button";
                    b.className = "aiwk-win-menu-item aiwk-win-menu-parent aiwk-nobr";
                    b.dataset.menuKind = "submenu";
                    b.dataset.menuValue = row.value || "";
                    b.dataset.needRole = row.role || "guest";
                    b.textContent = row.label || "menu";
                    const sub = document.createElement("div");
                    sub.className = "aiwk-win-submenu-panel";
                    (row.children || []).forEach(function (child) {
                        appendMenuButton(sub, child);
                    });
                    wrap.appendChild(b);
                    wrap.appendChild(sub);
                    panel.appendChild(wrap);
                    return;
                }
                const b = document.createElement("button");
                b.type = "button";
                b.className = "aiwk-win-menu-item aiwk-nobr";
                b.dataset.menuKind = row.kind || "action";
                b.dataset.menuValue = row.value || "";
                b.dataset.needRole = row.role || "guest";
                b.textContent = row.label || row.value || "menu";
                if (row.title) b.title = row.title;
                if ((row.value || "") === "todo") b.classList.add("aiwk-menu-todo");
                panel.appendChild(b);
            }
            winMenuRows.forEach(function (row) {
                appendMenuButton(winMenuPanel, row);
            });
            winMenuWrap.appendChild(winMenuBtn);
            winMenuWrap.appendChild(winMenuPanel);

            const handle = document.createElement("div");
            handle.className = "aiwk-drag-handle cursor-move select-text aiwk-nobr";
            handle.textContent = "↕";
            handle.title = AIWK.i18n.t("win.drag", "드래그");

            const clientBadge = document.createElement("span");
            clientBadge.className = "aiwk-client-id-badge select-text";
            const profile = AIWK.store ? AIWK.store.get("profile", {}) : {};
            clientBadge.textContent = String((profile && profile.clientId) || "").trim() || "?";
            clientBadge.title = "client_id";

            const savedTitle = AIWK.store ? AIWK.store.get("win_title_" + cfg.id, cfg.title || cfg.id) : (cfg.title || cfg.id);
            const savedShortTitle = AIWK.store ? AIWK.store.get("win_short_title_" + cfg.id, "") : "";
            const savedIcon = AIWK.store ? AIWK.store.get("win_icon_" + cfg.id, cfg.icon || iconForModule(cfg.module, savedTitle || cfg.id)) : (cfg.icon || iconForModule(cfg.module, savedTitle || cfg.id));
            const savedOrder = AIWK.store ? AIWK.store.get("win_order_" + cfg.id, cfg.order || "") : (cfg.order || "");

            const iconBadge = document.createElement("span");
            iconBadge.className = "aiwk-win-icon-badge select-text";
            iconBadge.textContent = savedIcon || iconForModule(cfg.module, savedTitle || cfg.id);
            iconBadge.title = "창 기능 아이콘";

            const orderBadge = document.createElement("span");
            orderBadge.className = "aiwk-win-order-badge select-text";
            orderBadge.textContent = String(savedOrder || "");
            orderBadge.title = "창 order";

            const title = document.createElement("div");
            title.className = "aiwk-title flex-1 text-sm font-semibold select-text";
            title.textContent = savedTitle;
            title.dataset.fullTitle = savedTitle;
            title.dataset.shortTitle = savedShortTitle;
            title.title = savedShortTitle ? ("전체 제목: " + savedTitle + " / 2단 제목: " + savedShortTitle) : ("전체 제목: " + savedTitle);

            const commMini = document.createElement("span");
            commMini.className = "aiwk-title-comm-mini flex items-center gap-1 select-text";
            commMini.title = "NR / BUS / WSS 통신 상태";
            if (AIWK.comm && typeof AIWK.comm.bindStatusBar === "function") {
                AIWK.comm.bindStatusBar(commMini);
            }

            const role = document.createElement("span");
            role.className = "aiwk-role text-xs select-text";
            role.textContent = AIWK.auth.role;
            role.dataset.role = AIWK.auth.role;

            const menu = document.createElement("nav");
            menu.className = "aiwk-menu flex items-center gap-1";
            menu.appendChild(button(AIWK.i18n.t("menu.design", "디자인"), "design", "editor"));
            menu.appendChild(button(AIWK.i18n.t("menu.js", "JS"), "js", "dev"));
            menu.appendChild(button(AIWK.i18n.t("menu.test", "TEST"), "test", "guest"));
            menu.appendChild(button(AIWK.i18n.t("win.collapse", "접기"), "collapse", "guest"));
            menu.appendChild(button(AIWK.i18n.t("win.close", "닫기"), "close", "guest"));

            header.appendChild(winMenuWrap);
            header.appendChild(handle);
            header.appendChild(clientBadge);
            header.appendChild(iconBadge);
            header.appendChild(orderBadge);
            header.appendChild(title);
            header.appendChild(commMini);
            header.appendChild(role);
            // v079: 헤더 오른쪽 빠른 테스트 버튼은 중복 UI라서 더 이상 표시하지 않는다.
            // 모든 창별 기능은 ☰ 공통 메뉴에 모은다. parts.menu는 호환성용으로만 유지한다.

            const body = document.createElement("main");
            body.className = "aiwk-win-body flex-1 p-2 overflow-auto";

            const status = document.createElement("footer");
            status.className = "aiwk-status px-2 py-1 text-xs select-text";
            status.textContent = AIWK.i18n.t("status.ready", "ready");

            const bottomDrag = document.createElement("div");
            bottomDrag.className = "aiwk-bottom-drag-handle cursor-move select-text";
            bottomDrag.textContent = "↕";
            bottomDrag.title = AIWK.i18n.t("win.drag", "드래그");

            const resize = document.createElement("div");
            resize.className = "aiwk-resize-handle";
            resize.title = AIWK.i18n.t("win.resize", "크기 조절");

            el.appendChild(header);
            el.appendChild(body);
            el.appendChild(status);
            el.appendChild(bottomDrag);
            el.appendChild(resize);

            const parts = {
                el: el,
                header: header,
                body: body,
                status: status,
                resize: resize,
                handle: handle,
                winMenuWrap: winMenuWrap,
                winMenuBtn: winMenuBtn,
                winMenuPanel: winMenuPanel,
                clientBadge: clientBadge,
                iconBadge: iconBadge,
                orderBadge: orderBadge,
                title: title,
                bottomDrag: bottomDrag,
                role: role,
                commMini: commMini,
                menu: menu
            };

            el.querySelectorAll("button[data-need-role]").forEach(function (btn) {
                AIWK.winRender.applyAuthToButton(btn);
            });

            return parts;
        }
    };
}());
