// ==========================================
// print.js: CSS MEDIA QUERY GENERATOR
// ==========================================

/**
 * Clone a signed form-signature shell for print (ink + caption only, no designer chrome).
 */
window.cloneSignedFormSignatureForPrint = function(overlay, containerW, containerH) {
    if (!overlay || typeof window.isFormSignatureFieldSigned !== "function") return null;
    if (!window.isFormSignatureFieldSigned(overlay)) return null;

    const fill = overlay.querySelector(".form-field-fill");
    const clone = document.createElement("div");
    clone.className = "print-form-signature";
    clone.style.position = "absolute";
    clone.style.boxSizing = "border-box";
    clone.style.overflow = "hidden";
    clone.style.background = "rgba(255,255,255,0.92)";
    clone.style.border = "1px solid rgba(15, 23, 42, 0.12)";
    clone.style.borderRadius = "2px";
    clone.style.display = "flex";
    clone.style.flexDirection = "column";
    clone.style.pointerEvents = "none";

    const leftPx = parseFloat(overlay.style.left) || 0;
    const topPx = parseFloat(overlay.style.top) || 0;
    const widthPx = parseFloat(overlay.style.width) || overlay.offsetWidth || 0;
    const heightPx = parseFloat(overlay.style.height) || overlay.offsetHeight || 0;
    clone.style.left = ((leftPx / containerW) * 100) + "%";
    clone.style.top = ((topPx / containerH) * 100) + "%";
    if (widthPx) clone.style.width = ((widthPx / containerW) * 100) + "%";
    if (heightPx) clone.style.height = ((heightPx / containerH) * 100) + "%";

    // Ink area
    const ink = document.createElement("div");
    ink.style.flex = "1 1 auto";
    ink.style.minHeight = "40%";
    ink.style.backgroundSize = "contain";
    ink.style.backgroundRepeat = "no-repeat";
    ink.style.backgroundPosition = "center";
    const btn = fill && fill.querySelector(".form-field-fill-sig");
    const imgUrl = overlay.dataset.sigImage
        || (btn && btn.style.backgroundImage
            ? String(btn.style.backgroundImage).replace(/^url\(["']?/, "").replace(/["']?\)$/, "")
            : "");
    if (imgUrl && imgUrl.indexOf("data:image") === 0) {
        ink.style.backgroundImage = "url(" + imgUrl + ")";
    } else {
        const name = (overlay.dataset.defaultValue || "").trim();
        ink.style.display = "flex";
        ink.style.alignItems = "center";
        ink.style.justifyContent = "center";
        ink.style.fontFamily = "Georgia, 'Times New Roman', serif";
        ink.style.fontStyle = "italic";
        ink.style.fontSize = "14px";
        ink.style.color = "#0b4f6c";
        ink.textContent = name && name.indexOf("data:image") !== 0 ? name : "Signed";
    }
    clone.appendChild(ink);

    // Caption (reuse live caption HTML if present)
    const cap = fill && fill.querySelector(".form-field-sig-attestation");
    if (cap) {
        const capClone = cap.cloneNode(true);
        capClone.style.pointerEvents = "none";
        capClone.style.cursor = "default";
        capClone.removeAttribute("title");
        clone.appendChild(capClone);
    } else {
        // Minimal caption from datasets
        const foot = document.createElement("div");
        foot.className = "form-field-sig-attestation";
        foot.style.flex = "0 0 auto";
        foot.style.padding = "2px 4px";
        foot.style.fontSize = "7px";
        foot.style.borderTop = "1px solid rgba(15,23,42,0.12)";
        let att = null;
        try {
            if (overlay.dataset.sigAttestation) att = JSON.parse(overlay.dataset.sigAttestation);
        } catch (_) { att = null; }
        const nm = (att && att.signedName) || overlay.dataset.defaultValue || "Signed";
        const when = (att && att.signedAt && typeof window.formatSignatureCaptionTime === "function")
            ? window.formatSignatureCaptionTime(att.signedAt)
            : "";
        foot.innerHTML = "<span class=\"sig-att-primary\"><span class=\"sig-att-name\"></span> "
            + "<span class=\"sig-att-confirm\">✓</span>"
            + (when ? " <span class=\"sig-att-when\"></span>" : "")
            + "</span>";
        const nameEl = foot.querySelector(".sig-att-name");
        if (nameEl) nameEl.textContent = nm;
        const whenEl = foot.querySelector(".sig-att-when");
        if (whenEl) whenEl.textContent = when;
        clone.appendChild(foot);
    }

    return clone;
};

window.printBtn = async function() {
    if (window.isAppBusy && window.isAppBusy()) {
        return window.customAlert(
            "Please wait for the document to finish loading before printing.",
            "⏳ Still working"
        );
    }
    const pages = APP.DOM.viewer.querySelectorAll(".pageContainer");
    if (pages.length === 0) { window.customAlert("No pages loaded."); return; }

    const doPrint = async () => {
        const firstPage = pages[0];
        const isLandscape = firstPage.offsetWidth > firstPage.offsetHeight;
        const orientationStr = isLandscape ? "landscape" : "portrait";
        
        let dynamicPrintStyle = document.getElementById("dynamicPrintStyle");
        if (!dynamicPrintStyle) {
            dynamicPrintStyle = document.createElement("style");
            dynamicPrintStyle.id = "dynamicPrintStyle";
            document.head.appendChild(dynamicPrintStyle);
        }
        dynamicPrintStyle.innerHTML = `@media print { @page { size: ${orientationStr}; margin: 0mm !important; } }`;

        window.clearActiveOverlay();
        if (typeof window.hideSigAttestationPopover === "function") {
            window.hideSigAttestationPopover(true);
        }
        APP.DOM.printArea.innerHTML = "";

        const blobUrlsToRevoke = [];

        for (let i = 0; i < pages.length; i++) {
            const container = pages[i]; const canvas = container.querySelector("canvas.pageCanvas"); if (!canvas) continue;
            
            const containerW = container.offsetWidth; 
            const containerH = container.offsetHeight;

            const pageWrapper = document.createElement("div"); 
            pageWrapper.className = "print-page-wrapper";

            const printImg = new Image(); 
            const blobUrl = await new Promise(resolve => canvas.toBlob(blob => resolve(URL.createObjectURL(blob)), "image/png"));
            blobUrlsToRevoke.push(blobUrl);
            
            printImg.src = blobUrl; 
            printImg.className = "print-page-img";
            printImg.style.width = "100%"; printImg.style.display = "block";
            pageWrapper.appendChild(printImg);

            // Annotations at full opacity (skip form designer chrome)
            container.querySelectorAll(".overlayImg, .textOverlay, .shapeOverlay").forEach(overlay => {
                const clone = overlay.cloneNode(true);
                const controls = clone.querySelector(".textControls"); if(controls) controls.remove();
                clone.querySelectorAll(".textDragHandle, .resizeHandle, .deleteHandle, .rotateHandle").forEach(h => h.remove());
                clone.classList.remove("overlay-active");
                clone.style.opacity = "1";
                    
                const contentDiv = clone.querySelector(".textContent"); 
                if(contentDiv) {
                    contentDiv.contentEditable = "false";
                    contentDiv.style.padding = ((2 / containerW) * 100) + "cqw"; 
                }
                const leftPx = parseFloat(overlay.style.left) || 0; const topPx = parseFloat(overlay.style.top) || 0;
                clone.style.left = ((leftPx / containerW) * 100) + "%"; clone.style.top = ((topPx / containerH) * 100) + "%";

                const widthPx = parseFloat(overlay.style.width) || 0;
                if (widthPx) clone.style.width = ((widthPx / containerW) * 100) + "%";

                const heightPx = parseFloat(overlay.style.height) || 0;
                if (heightPx) clone.style.height = ((heightPx / containerH) * 100) + "%";

                if (overlay.classList.contains("textOverlay")) {
                    clone.style.fontSize = (((parseFloat(overlay.style.fontSize) || 12) / containerW) * 100) + "cqw";
                }
                
                pageWrapper.appendChild(clone);
            });

            // Signed form signatures (ink + caption) — previously omitted entirely
            container.querySelectorAll(".formFieldOverlay.form-field-signature").forEach((overlay) => {
                const sigClone = typeof window.cloneSignedFormSignatureForPrint === "function"
                    ? window.cloneSignedFormSignatureForPrint(overlay, containerW, containerH)
                    : null;
                if (sigClone) pageWrapper.appendChild(sigClone);
            });

            APP.DOM.printArea.appendChild(pageWrapper);
        }
        
        setTimeout(() => { 
            window.print(); 
            setTimeout(() => { blobUrlsToRevoke.forEach(url => URL.revokeObjectURL(url)); }, 1000);
        }, 150);
    };

    if (window.withCaptureSafeAppearance) {
        await window.withCaptureSafeAppearance(doPrint);
    } else {
        await doPrint();
    }
};
