// ==========================================
// host-bridge.js: Desktop shell integration
// WebView2 (Windows) + future hosts. PWA uses launchQueue in io.js / workspace.js.
// ==========================================

/**
 * Open files delivered by a native shell.
 * entries: [{ name: "doc.pdf", url: "https://ccs-open.local/...." }]
 * Host maps a temp folder so large files avoid base64 postMessage limits.
 */
window.openFromHostUrls = async function (entries) {
    if (!Array.isArray(entries) || entries.length === 0) return;

    const files = [];
    for (const entry of entries) {
        if (!entry || !entry.url || !entry.name) continue;
        try {
            const res = await fetch(entry.url);
            if (!res.ok) throw new Error("HTTP " + res.status);
            const blob = await res.blob();
            const lower = String(entry.name).toLowerCase();
            const type = lower.endsWith(".pdf")
                ? "application/pdf"
                : (lower.endsWith(".ccspdf") ? "application/octet-stream" : (blob.type || "application/octet-stream"));
            files.push(new File([blob], entry.name, { type: type }));
        } catch (err) {
            console.error("openFromHostUrls failed for", entry.name, err);
            if (typeof window.customAlert === "function") {
                await window.customAlert("Could not open: " + entry.name + "\n" + (err && err.message ? err.message : err));
            }
        }
    }

    if (files.length === 0) return;

    // Mark startup opens so workspace can skip silent session restore under them
    if (window.CcsWorkspace && typeof window.CcsWorkspace.noteStartupOpen === "function") {
        window.CcsWorkspace.noteStartupOpen(files.length);
    } else {
        window.__CCS_STARTUP_OPEN_COUNT__ = (window.__CCS_STARTUP_OPEN_COUNT__ || 0) + files.length;
    }

    // Prefer multi-tab open when enabled (each host file → its own tab)
    if (window.CcsWorkspace && window.CcsWorkspace.tabbed && window.CcsWorkspace.tabbed()
        && typeof window.CcsWorkspace.openFilesAsTabs === "function") {
        await window.CcsWorkspace.openFilesAsTabs(files.map((f) => ({ file: f, handle: null })));
    } else if (typeof window.processPdfFiles === "function") {
        await window.processPdfFiles(files, false);
    } else {
        console.error("processPdfFiles not available yet");
    }
};

window.__CCS_SHELL__ = null;

(function initHostBridge() {
    // Microsoft Edge WebView2 injects chrome.webview
    const wv = window.chrome && window.chrome.webview;
    if (!wv) return;

    window.__CCS_SHELL__ = "webview2";
    console.log("CCS host bridge: WebView2");

    wv.addEventListener("message", async (event) => {
        let msg = event.data;
        if (typeof msg === "string") {
            try { msg = JSON.parse(msg); } catch (_) { return; }
        }
        if (!msg || typeof msg !== "object") return;

        if (msg.type === "open-files" && Array.isArray(msg.files)) {
            await window.openFromHostUrls(msg.files);
        }
    });

    /**
     * Only signal ready once the workspace is accepting startup opens.
     * Signaling too early races session restore and produces blank/wrong-named tabs.
     */
    const signalReady = () => {
        try {
            wv.postMessage({ type: "ready" });
        } catch (e) {
            console.warn("host ready signal failed", e);
        }
    };

    const whenAcceptingOpens = (cb) => {
        if (window.__CCS_WORKSPACE_ACCEPTING_STARTUP_OPENS__
            || window.__CCS_WORKSPACE_READY__) {
            cb();
            return;
        }
        const onAccept = () => cb();
        window.addEventListener("ccs-workspace-accepting-opens", onAccept, { once: true });
        // Fallback: full ready (restore already done)
        window.addEventListener("ccs-workspace-ready", onAccept, { once: true });
    };

    whenAcceptingOpens(() => {
        // Defer one tick so listeners on the same event can run first
        setTimeout(signalReady, 0);
    });
})();
