// AIWK EXT4 v123 - core window controls
// 역할: 선택 모듈이 아니라 모든 AIWK floating window에 기본 적용되는 코어 창 컨트롤입니다.
(function () {
  "use strict";
  const VERSION = "v123-window-controls-core";
  if (window.__AIWK_WINDOW_CONTROLS_V119__) return;
  window.__AIWK_WINDOW_CONTROLS_V119__ = true;

  const TARGET_IDS = [
    "aiwk_domain_module_manager_panel",
    "aiwk_iframe_chat_agent_module_panel",
    "aiwk_selector_tool_module_panel",
    "aiwk_local_pc_bridge_panel",
    "aiwk_iframe_agent_panel"
  ];

  function safe(v) { return v === undefined || v === null ? "" : String(v); }
  function clamp(n, min, max) { return Math.max(min, Math.min(max, n)); }
  function storageKey(panel) {
    return "AIWK_WIN_STATE::" + safe(location.hostname || location.origin || "unknown") + "::" + safe(panel.id || panel.getAttribute("data-aiwk-module-id") || "panel");
  }
  function canUseLocalStorage() {
    try { localStorage.setItem("__aiwk_wc_test__", "1"); localStorage.removeItem("__aiwk_wc_test__"); return true; }
    catch (e) { return false; }
  }
  const localOk = canUseLocalStorage();
  const memory = {};
  function getState(key) {
    try { if (localOk) { const raw = localStorage.getItem(key); if (raw) return JSON.parse(raw); } } catch (e) {}
    return memory[key] || null;
  }
  function setState(key, val) {
    memory[key] = val;
    try { if (localOk) localStorage.setItem(key, JSON.stringify(val)); } catch (e) {}
  }
  function isFormControl(el) {
    return !!(el && el.closest && el.closest("button,input,textarea,select,a,label,summary,[contenteditable='true'],[data-aiwk-no-drag='1']"));
  }
  function findTitle(panel) {
    return panel.querySelector("[data-aiwk-win-title]") || panel.querySelector("[data-aiwk-window-title]") || panel.firstElementChild;
  }
  function ensureTitle(panel) {
    let title = findTitle(panel);
    if (!title || title.nodeType !== 1) {
      title = document.createElement("div");
      title.textContent = panel.id || "AIWK";
      panel.insertBefore(title, panel.firstChild);
    }
    title.setAttribute("data-aiwk-win-title", "1");
    title.style.display = title.style.display || "flex";
    title.style.alignItems = title.style.alignItems || "center";
    title.style.gap = title.style.gap || "6px";
    // v123: 제목 텍스트는 복사/선택 가능해야 한다.
    // 이동은 전용 ↔ 버튼에서만 수행한다.
    title.style.userSelect = "text";
    title.style.touchAction = "auto";
    title.setAttribute("data-aiwk-title-selectable", "1");
    return title;
  }
  function removeLegacyWindowButtons(title) {
    // v123: 기존 모듈이 자체로 만들던 닫기 버튼과 공통 닫기 버튼이 중복되면
    // 사용자가 x 2개를 보게 된다. 공통 우측 x만 남긴다.
    const legacySelectors = [
      "[data-aiwk-agent-hide='1']",
      "[data-aiwk-module-manager-hide='1']",
      "[data-aiwk-module-close='1']",
      "[data-aiwk-agent-close='1']",
      "[data-aiwk-lpb-close='1']"
    ];
    legacySelectors.forEach(function (sel) {
      Array.from(title.querySelectorAll(sel)).forEach(function (el) {
        try { el.remove(); } catch (e) { try { el.style.display = "none"; } catch (_) {} }
      });
    });
  }

  function ensureFrameBadge(title) {
    // v123: iframe 안에서 뜬 창인지 복사/캡처만 봐도 구분되도록 짧게 표시한다.
    if (window.top === window) return null;
    let badge = title.querySelector("[data-aiwk-frame-badge='1']");
    if (badge) return badge;
    badge = document.createElement("span");
    badge.setAttribute("data-aiwk-frame-badge", "1");
    badge.textContent = "iframe";
    badge.title = "이 창은 iframe 내부에 주입된 AIWK 모듈창입니다.";
    badge.style.cssText = "font-size:10px;color:#93c5fd;border:1px solid #1d4ed8;border-radius:999px;padding:0 5px;line-height:1.4;user-select:text;";
    const firstNonDrag = Array.from(title.childNodes).find(function (n) {
      return !(n.nodeType === 1 && n.getAttribute && n.getAttribute("data-aiwk-wc-drag") === "1");
    });
    if (firstNonDrag) title.insertBefore(badge, firstNonDrag);
    else title.appendChild(badge);
    return badge;
  }

  function mkBtn(title, attr, text, tooltip, first) {
    let b = title.querySelector("[" + attr + "='1']");
    if (b) return b;
    b = document.createElement("button");
    b.type = "button";
    b.textContent = text;
    b.title = tooltip || text;
    b.setAttribute(attr, "1");
    b.setAttribute("data-aiwk-no-drag", "1");
    b.style.cssText = "background:#374151;color:#fff;border:0;border-radius:4px;padding:1px 6px;cursor:pointer;font:12px Arial;line-height:1.4;min-width:23px;";
    if (first && title.firstChild) title.insertBefore(b, title.firstChild);
    else title.appendChild(b);
    return b;
  }
  function makeRestore(panel, key, label) {
    const id = key.replace(/[^0-9A-Za-z_-]/g, "_") + "_restore";
    let r = document.getElementById(id);
    if (r) return r;
    r = document.createElement("button");
    r.id = id;
    r.type = "button";
    r.textContent = label || "AIWK";
    r.setAttribute("data-aiwk-no-drag", "1");
    r.setAttribute("data-aiwk-restore-button", "1");
    r.style.cssText = "position:fixed;right:10px;bottom:10px;z-index:2147483647;background:#111827;color:#fff;border:1px solid #60a5fa;border-radius:999px;padding:4px 9px;font:12px Arial;display:none;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,.45);";
    r.addEventListener("click", function () {
      panel.style.display = "block";
      r.style.display = "none";
      save(panel, key);
    }, true);
    (document.body || document.documentElement).appendChild(r);
    return r;
  }
  function save(panel, key) {
    try {
      const rect = panel.getBoundingClientRect();
      setState(key, {
        left: Math.round(rect.left), top: Math.round(rect.top),
        width: Math.round(rect.width), height: Math.round(rect.height),
        opacity: panel.style.opacity || "",
        collapsed: panel.getAttribute("data-aiwk-collapsed") === "1" ? 1 : 0,
        hidden: panel.style.display === "none" ? 1 : 0
      });
    } catch (e) {}
  }
  function restore(panel, key) {
    const st = getState(key);
    if (!st) return;
    if (st.left !== undefined) { panel.style.left = st.left + "px"; panel.style.right = "auto"; }
    if (st.top !== undefined) { panel.style.top = st.top + "px"; panel.style.bottom = "auto"; }
    if (st.width) panel.style.width = st.width + "px";
    if (st.height) panel.style.height = st.height + "px";
    if (st.opacity) panel.style.opacity = st.opacity;
    if (st.collapsed) panel.setAttribute("data-aiwk-collapsed", "1");
  }
  function bodyChildren(panel, title) {
    return Array.from(panel.children).filter(function (x) { return x !== title; });
  }
  function collapse(panel, title, key, on) {
    bodyChildren(panel, title).forEach(function (el) {
      if (on) { el.setAttribute("data-aiwk-prev-display", el.style.display || ""); el.style.display = "none"; }
      else { el.style.display = el.getAttribute("data-aiwk-prev-display") || ""; }
    });
    panel.setAttribute("data-aiwk-collapsed", on ? "1" : "0");
    panel.style.height = on ? "auto" : (panel.style.height || "");
    panel.style.minHeight = on ? "0" : (panel.style.minHeight || "28px");
    panel.style.overflow = on ? "hidden" : "auto";
    save(panel, key);
  }
  function bindDrag(panel, dragBtn, key) {
    if (!dragBtn || dragBtn.__aiwkWcDragBound) return;
    dragBtn.__aiwkWcDragBound = true;
    function down(ev) {
      if (ev.button !== undefined && ev.button !== 0) return;
      ev.preventDefault(); ev.stopPropagation();
      const r = panel.getBoundingClientRect();
      const sx = ev.clientX, sy = ev.clientY, sl = r.left, st = r.top;
      panel.style.position = "fixed";
      panel.style.left = sl + "px"; panel.style.top = st + "px";
      panel.style.right = "auto"; panel.style.bottom = "auto";
      panel.style.margin = "0";
      function move(e) {
        e.preventDefault(); e.stopPropagation();
        const w = Math.max(120, panel.offsetWidth || r.width || 220);
        const h = Math.max(28, panel.offsetHeight || r.height || 40);
        panel.style.left = clamp(sl + e.clientX - sx, 0, Math.max(0, window.innerWidth - 40)) + "px";
        panel.style.top = clamp(st + e.clientY - sy, 0, Math.max(0, window.innerHeight - 28)) + "px";
      }
      function up() {
        document.removeEventListener("pointermove", move, true);
        document.removeEventListener("pointerup", up, true);
        document.removeEventListener("mousemove", move, true);
        document.removeEventListener("mouseup", up, true);
        save(panel, key);
      }
      document.addEventListener("pointermove", move, true);
      document.addEventListener("pointerup", up, true);
      document.addEventListener("mousemove", move, true);
      document.addEventListener("mouseup", up, true);
    }
    dragBtn.addEventListener("pointerdown", down, true);
    dragBtn.addEventListener("mousedown", down, true);
  }
  function enhance(panel, opts) {
    if (!panel || panel.nodeType !== 1 || panel.__aiwkWindowControlsEnhancedV119) return panel;
    panel.__aiwkWindowControlsEnhancedV119 = true;
    const key = (opts && opts.key) || storageKey(panel);
    const label = (opts && opts.label) || panel.getAttribute("data-aiwk-window-label") || safe(panel.id || "AIWK").replace(/^aiwk_/, "AIWK ");
    const title = ensureTitle(panel);
    removeLegacyWindowButtons(title);
    panel.setAttribute("data-aiwk-window-controls", "1");
    panel.style.position = "fixed";
    panel.style.resize = "both";
    panel.style.overflow = panel.getAttribute("data-aiwk-collapsed") === "1" ? "hidden" : "auto";
    panel.style.minWidth = panel.style.minWidth || "160px";
    panel.style.minHeight = panel.style.minHeight || "28px";
    panel.style.maxWidth = panel.style.maxWidth || "96vw";
    panel.style.maxHeight = panel.style.maxHeight || "88vh";
    panel.style.boxSizing = "border-box";
    panel.style.pointerEvents = "auto";
    restore(panel, key);
    const drag = mkBtn(title, "data-aiwk-wc-drag", "↔", "이 버튼을 잡고 창 이동", true);
    drag.style.userSelect = "none";
    drag.style.touchAction = "none";
    ensureFrameBadge(title);
    const op = mkBtn(title, "data-aiwk-wc-opacity", "◐", "투명도");
    const mini = mkBtn(title, "data-aiwk-wc-collapse", "▣", "오므리기/펼치기");
    const close = mkBtn(title, "data-aiwk-wc-close", "×", "닫기");
    const restoreBtn = makeRestore(panel, key, label);
    bindDrag(panel, drag, key);
    if (!op.__aiwkBound) { op.__aiwkBound = true; op.addEventListener("click", function(e){ e.preventDefault(); e.stopPropagation(); const cur=parseFloat(panel.style.opacity||"1")||1; panel.style.opacity=String(cur>.9?.75:(cur>.55?.45:1)); save(panel,key); }, true); }
    if (!mini.__aiwkBound) { mini.__aiwkBound = true; mini.addEventListener("click", function(e){ e.preventDefault(); e.stopPropagation(); collapse(panel,title,key,panel.getAttribute("data-aiwk-collapsed")!=="1"); }, true); }
    if (!close.__aiwkBound) { close.__aiwkBound = true; close.addEventListener("click", function(e){ e.preventDefault(); e.stopPropagation(); panel.style.display="none"; restoreBtn.style.display="block"; save(panel,key); }, true); }
    if (panel.getAttribute("data-aiwk-collapsed") === "1") collapse(panel, title, key, true);
    try { const ro = new ResizeObserver(function(){ if(panel.style.display!=="none") save(panel,key); }); ro.observe(panel); panel.__aiwkWcResizeObserver=ro; } catch(e) {}
    panel.__aiwkHideToButton = function(){ panel.style.display="none"; restoreBtn.style.display="block"; save(panel,key); };
    const oldDestroy = panel.__aiwkDestroy;
    panel.__aiwkDestroy = function(){
      try { if (oldDestroy && oldDestroy !== panel.__aiwkDestroy) oldDestroy(); } catch(e) {}
      try { if (panel.__aiwkWcResizeObserver) panel.__aiwkWcResizeObserver.disconnect(); } catch(e) {}
      try { restoreBtn.remove(); } catch(e) {}
      try { panel.remove(); } catch(e) {}
    };
    return panel;
  }
  function disposeAll(reason) {
    const nodes = Array.from(document.querySelectorAll("[data-aiwk],[data-aiwk-module-window='1'],[data-aiwk-restore-button='1'],#aiwk_iframe_probe"));
    nodes.reverse().forEach(function(el){ try { if (el.__aiwkDestroy) el.__aiwkDestroy(); else el.remove(); } catch(e) {} });
    try { window.dispatchEvent(new CustomEvent("AIWK_WINDOW_CONTROLS_DISPOSED", { detail:{ reason: reason || "dispose_all" } })); } catch(e) {}
    return { ok:1, version:VERSION, disposed:nodes.length, reason:reason||"dispose_all" };
  }
  function auto() {
    TARGET_IDS.forEach(function(id){ const el=document.getElementById(id); if(el) enhance(el,{label:id.replace(/^aiwk_/,"AIWK ")}); });
    document.querySelectorAll("[data-aiwk='domain-module-manager'],[data-aiwk='iframe-agent-panel'],[data-aiwk-module-window='1']").forEach(function(el){ enhance(el,{label:el.id||"AIWK"}); });
  }
  window.AIWKWindowControls = { version: VERSION, enhance, auto, disposeAll };
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", auto, { once: true });
  else auto();
  setInterval(auto, 900);
}());
