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

    if (window.AIWK && window.AIWK.version) {
        return;
    }

    const AIWK = window.AIWK || {};

    AIWK.version = "v102-stage4.9-ext4-store-resize-noise-fix";
    AIWK.buildVersion = "0.0.98-stage4.5";
    AIWK.versionText = "AIWK v102-stage4.9-ext4-store-resize-noise-fix";
    AIWK.paths = {
        tailwindCss: "AIWK_COMMON/styles/tailwind.css",
        baseCss: "AIWK_COMMON/styles/aiwk_ext4_base.css",
        templateDev: "AIWK_COMMON/templates/win-dev.json",
        skinDarkJson: "AIWK_COMMON/skins/dark/skin.json",
        skinDarkCss: "AIWK_COMMON/skins/dark/skin.css",
        i18nKo: "AIWK_COMMON/i18n/ko.json",
        i18nEn: "AIWK_COMMON/i18n/en.json",
        manualTestsJson: "AIWK_COMMON/test/aiwk_manual_tests.json",
        planJson: "AIWK_COMMON/plan/aiwk_ext4_plan.json",
        diagnosticJson: ""
    };

    AIWK.rootId = "aiwk-ext4-root";

    AIWK.root = AIWK.root || {};
    AIWK.root.get = AIWK.root.get || function () {
        let root = document.getElementById(AIWK.rootId || "aiwk-ext4-root");
        if (!root) {
            root = document.createElement("div");
            root.id = AIWK.rootId || "aiwk-ext4-root";
            root.setAttribute("data-aiwk-root", "1");
            document.documentElement.appendChild(root);
        }
        root.dataset.version = AIWK.version || "v102-stage4.9-ext4-store-resize-noise-fix";
        return root;
    };


    AIWK.ui = AIWK.ui || {};
    AIWK.ui.applyPlaceholderTooltips = function (root) {
        root = root || document;
        const list = root.querySelectorAll ? root.querySelectorAll("input[placeholder], textarea[placeholder], select[placeholder]") : [];
        list.forEach(function (node) {
            const ph = String(node.getAttribute("placeholder") || "").trim();
            if (!ph) {
                return;
            }
            const oldTitle = String(node.getAttribute("title") || "").trim();
            if (!oldTitle || oldTitle.indexOf("placeholder:") === 0) {
                node.setAttribute("title", "placeholder: " + ph);
            }
        });
    };

    AIWK.getUrl = function (path) {
        if (typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.getURL) {
            return chrome.runtime.getURL(path);
        }
        return path;
    };


    AIWK.debug = AIWK.debug || {};
    AIWK.debug.enabled = function () {
        try { return localStorage.getItem("AIWK_DEBUG_CONSOLE_V1") === "1"; } catch(e) { return false; }
    };
    AIWK.debug.log = function (tag, data) {
        if (!AIWK.debug.enabled()) return;
        try { console.log("[" + tag + "]", data || {}); } catch(e) {}
    };

    AIWK.error = AIWK.error || {};
    AIWK.error.isIgnorable = function (msg) {
        msg = String(msg || "");
        if (msg.indexOf("ResizeObserver loop completed with undelivered notifications") >= 0) return true;
        if (msg.indexOf("ResizeObserver loop limit exceeded") >= 0) return true;
        return false;
    };

    AIWK.error.report = function (err, context) {
        context = context || {};
        const probeMsg = err && err.message ? String(err.message) : String(err || "");
        if (AIWK.error.isIgnorable(probeMsg)) {
            if (AIWK.debug && typeof AIWK.debug.log === "function") {
                AIWK.debug.log("AIWK_ERROR_IGNORED", { message: probeMsg, url: location.href, at: new Date().toISOString() });
            }
            return { ok: 1, ignored: 1, message: probeMsg };
        }
        function stringify(value) {
            if (value === undefined || value === null) return "";
            if (value instanceof Error) return value.message || String(value);
            if (typeof value === "string") return value;
            try { return JSON.stringify(value, null, 2); } catch (e) { return String(value); }
        }
        const msg = err && err.message ? err.message : (stringify(err) || "unknown error");
        const stack = err && err.stack ? String(err.stack) : "";
        const row = {
            ok: 0,
            kind: "AIWK_ERROR",
            message: msg,
            raw_error: err && err.message ? undefined : err,
            context: context,
            url: location.href,
            time: new Date().toISOString(),
            stack: stack
        };
        let detail = "";
        try { detail = JSON.stringify(row, null, 2); } catch (e) { detail = msg; }
        try { console.error("AIWK_ERROR_DETAIL\n" + detail); } catch (e) {}
        try {
            let box = document.getElementById("aiwk-error-panel");
            if (!box) {
                box = document.createElement("div");
                box.id = "aiwk-error-panel";
                box.style.cssText = "position:fixed;right:12px;bottom:12px;z-index:2147483647;max-width:720px;max-height:52vh;overflow:auto;background:#190b0b;color:#fff;border:1px solid #ef4444;border-radius:12px;box-shadow:0 18px 48px rgba(0,0,0,.45);font:12px/1.45 ui-monospace,Consolas,monospace;padding:12px;white-space:pre-wrap;user-select:text;";
                document.documentElement.appendChild(box);
            }
            const guide = context && context.guide ? context.guide : "해결 안내: 이 패널 전체를 복사해 전달하십시오.";
            box.textContent = "AIWK 오류\n" + msg + "\n\n위치: " + (context.file || "") + " " + (context.fn || "") + "\n원인 후보: " + (context.cause || "미확인") + "\n" + guide + "\n\nDETAIL_JSON:\n" + detail + "\n\nstack:\n" + stack;
        } catch (e) {}
        return row;
    };
    AIWK.error.installGlobal = function () {
        if (AIWK.error._installed) return;
        AIWK.error._installed = true;
        window.addEventListener("error", function (ev) {
            const msg = ev && ev.message ? String(ev.message) : String((ev && ev.error && ev.error.message) || "");
            if (AIWK.error.isIgnorable(msg)) return;
            AIWK.error.report(ev.error || ev.message, {file: ev.filename || "window", fn: "error", cause: "전역 JS 오류"});
        });
        window.addEventListener("unhandledrejection", function (ev) {
            const reason = ev && ev.reason;
            const msg = reason && reason.message ? String(reason.message) : String(reason || "");
            if (AIWK.error.isIgnorable(msg)) return;
            AIWK.error.report(reason || "unhandled rejection", {file: "window", fn: "unhandledrejection", cause: "Promise 처리 누락 오류"});
        });
    };
    AIWK.error.installGlobal();


    AIWK.ready = function (fn) {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", fn, { once: true });
            return;
        }
        fn();
    };

    window.AIWK = AIWK;
}());
