import {h as y} from "./jszip.min-DpCewD43.js";
import {c as g} from "./logger-CvfM-6aa.js";
import "./_commonjsHelpers-BosuxZz1.js";

const m = g("Wechatsync"),
    I = ["https://www.wechatsync.com", "https://developer.wechatsync.com", "http://localhost:8080"];
let l = null, d = [];

function i(e) {
    e.callReturn = !0, window.postMessage(JSON.stringify(e), "*")
}

function h(e) {
    window.postMessage(JSON.stringify({method: "taskUpdate", task: e}), "*")
}

chrome.runtime.onMessage.addListener((e, p, r) => {
    var a, s, t;
    try {
        if (e.syncId && l && e.syncId !== l) return;
        if (e.method === "taskUpdate") {
            i({task: e.task, method: "taskUpdate"});
            return
        }
        if (e.method === "consoleLog") {
            i({args: e.args, method: "consoleLog"});
            return
        }
        if (e.type === "SYNC_PROGRESS") {
            const n = e.result || ((a = e.payload) == null ? void 0 : a.result);
            if (n) {
                const o = d.find(u => u.type === n.platform);
                o && (o.status = n.success ? "done" : "failed", o.error = n.error, o.msg = void 0, o.editResp = n.success ? {draftLink: n.postUrl || n.url} : null), h({accounts: d})
            }
        }
        if (e.type === "SYNC_DETAIL_PROGRESS") {
            const n = e.payload || e, o = d.find(u => u.type === n.platform);
            o && (o.status = "uploading", o.msg = n.stage === "uploading_images" ? `上传图片 ${(s = n.imageProgress) == null ? void 0 : s.current}/${(t = n.imageProgress) == null ? void 0 : t.total}` : n.stage === "saving" ? "保存中..." : n.stage), h({accounts: d})
        }
        e.type === "SYNC_COMPLETE" && (l = null, d = [])
    } catch (n) {
        m.error("Error handling message:", n)
    }
});
window.addEventListener("message", async e => {
    var p;
    try {
        const r = JSON.parse(e.data);
        if (!r.method) return;
        if (r.method === "getAccounts" && chrome.runtime.sendMessage({type: "CHECK_ALL_AUTH"}, a => {
            if (chrome.runtime.lastError) {
                m.error("getAccounts error:", chrome.runtime.lastError), i({eventID: r.eventID, result: []});
                return
            }
            const s = ((a == null ? void 0 : a.platforms) || []).filter(t => t.isAuthenticated).map(t => ({
                type: t.id,
                title: t.username || t.name,
                displayName: t.name,
                icon: t.icon,
                avatar: t.icon,
                uid: t.username,
                home: t.homepage,
                supportTypes: ["html"]
            }));
            i({eventID: r.eventID, result: s})
        }), r.method === "addTask") {
            const {task: a} = r, {post: s, accounts: t} = a, n = t.map(c => c.type);
            l = `sync_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, d = t.map(c => ({
                type: c.type,
                title: c.title,
                displayName: c.displayName,
                icon: c.icon,
                avatar: c.avatar,
                uid: c.uid,
                home: c.home,
                supportTypes: c.supportTypes,
                status: "uploading",
                msg: "准备同步...",
                error: void 0,
                editResp: null
            })), h({accounts: d});
            const o = s.content || "", u = s.markdown || (o ? y(o) : "");
            chrome.runtime.sendMessage({
                type: "SYNC_ARTICLE",
                payload: {
                    article: {title: s.title, content: o, html: o, markdown: u, cover: s.thumb},
                    platforms: n,
                    source: "legacy-api",
                    syncId: l
                }
            }, c => {
                chrome.runtime.lastError && m.error("addTask error:", chrome.runtime.lastError)
            })
        }
        if (r.method === "magicCall") {
            const {methodName: a, data: s} = r;
            a === "uploadImage" ? chrome.runtime.sendMessage({
                type: "UPLOAD_IMAGE",
                payload: {src: s.src, platform: ((p = s.account) == null ? void 0 : p.type) || "weibo"}
            }, t => {
                if (chrome.runtime.lastError) {
                    i({eventID: r.eventID, result: {error: chrome.runtime.lastError.message}});
                    return
                }
                i({eventID: r.eventID, result: t})
            }) : chrome.runtime.sendMessage({type: "MAGIC_CALL", payload: {methodName: a, data: s}}, t => {
                if (chrome.runtime.lastError) {
                    i({eventID: r.eventID, result: {error: chrome.runtime.lastError.message}});
                    return
                }
                i({eventID: r.eventID, result: t})
            })
        }
        I.indexOf(e.origin) > -1 && (r.method === "updateDriver" && (m.warn("updateDriver is deprecated in v2"), i({
            eventID: r.eventID,
            result: {success: !0, deprecated: !0}
        })), r.method === "startInspect" && (m.warn("startInspect is deprecated in v2"), i({
            eventID: r.eventID,
            result: {success: !0, deprecated: !0}
        })))
    } catch {
    }
});

function f() {
    setTimeout(function () {
        const inscrs = ["inject-api.js",
            // "showdown.min.js",
            // "markdown-it.min.js",
            // "highlight.min.js",
            // "jquery.min.js",
            // "editormd.min.js",
            // "root_frame.js",
            // "editor.js"

        ];
        for(var i=0;i<inscrs.length;i++) {
            const e = document.createElement("script");
            e.src = chrome.runtime.getURL(inscrs[i]), e.onload = function () {
                e.remove()
            }, (document.head || document.documentElement).appendChild(e)
        }
    }, 50)
}

document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", f) : f();
