// Export Dimensions PDF / JPG
// Exports the book-cover spread + Dimensions layer annotations as one file.
// Run "Book Cover Dimensions" first to create the annotations.
// Compatible: InDesign 2022 (v17)+
// Maxim Balabin | extralarge.dev


(function () {
    "use strict";

    var _savedUnit = app.scriptPreferences.measurementUnit;
    app.scriptPreferences.measurementUnit = MeasurementUnits.MILLIMETERS;
    function restoreUnit() { app.scriptPreferences.measurementUnit = _savedUnit; }

    function round1(v) { return Math.round(v * 10) / 10; }

    // ── Dialog ───────────────────────────────────────────────────────────────

    function run(doc) {
        var baseName = doc.name.replace(/\.indd$/i, "");

        var dlg = new Window("dialog", "Export Dimensions");
        dlg.orientation = "column";
        dlg.alignChildren = ["fill", "top"];
        dlg.spacing = 8; dlg.margins = 14;

        var pan = dlg.add("panel", undefined, "Options");
        pan.orientation = "column";
        pan.alignChildren = ["fill", "top"];
        pan.margins = [12, 16, 12, 10];
        pan.spacing = 6;

        // ── Format selector ───────────────────────────────────────────────────
        var fmtGrp = pan.add("group"); fmtGrp.spacing = 10;
        fmtGrp.add("statictext", undefined, "Format:");
        var rbJPG = fmtGrp.add("radiobutton", undefined, "JPG");
        var rbPDF = fmtGrp.add("radiobutton", undefined, "PDF");
        rbPDF.value = true; // PDF by default

        // ── Filename field (extension auto-updates) ───────────────────────────
        function row(parent, label, defVal, wide) {
            var g = parent.add("group"); g.spacing = 6;
            var st = g.add("statictext", undefined, label);
            st.preferredSize.width = 210;
            var et = g.add("edittext", undefined, String(defVal));
            et.preferredSize.width = wide || 50;
            return et;
        }

        var eName   = row(pan, "Output filename:", baseName + "_.pdf", 200);
        var eOff    = row(pan, "Annotation offset from bleed (mm):", 5);
        var eMargin = row(pan, "White margin outside annotations (mm):", 12);
        var eDPI    = row(pan, "JPG resolution (DPI):", 150);

        // Update filename extension when format changes
        function updateExt() {
            var cur = eName.text.replace(/\.(jpg|jpeg|pdf)$/i, "");
            eName.text = cur + (rbJPG.value ? ".jpg" : ".pdf");
        }
        rbJPG.onClick = updateExt;
        rbPDF.onClick = updateExt;

        var br = dlg.add("group"); br.alignment = "center"; br.spacing = 10;
        var btnOK  = br.add("button", undefined, "Choose folder \u0026 Export", { name: "ok" });
        var btnCnl = br.add("button", undefined, "Cancel", { name: "cancel" });
        btnOK.preferredSize.width  = 170;
        btnCnl.preferredSize.width = 80;

        btnCnl.onClick = function () { dlg.close(); };

        var params = null;
        btnOK.onClick = function () {
            params = {
                fileName : eName.text || (baseName + "_dimensions.jpg"),
                isJPG    : rbJPG.value,
                annOff   : parseFloat(eOff.text)   || 5,
                margin   : parseFloat(eMargin.text) || 12,
                dpi      : parseInt(eDPI.text, 10)  || 150
            };
            dlg.close();
        };

        dlg.center();
        dlg.show();
        if (!params) { restoreUnit(); return; }

        doExport(doc, params.fileName, params.isJPG, params.annOff, params.margin, params.dpi);
    }

    // ── Export ───────────────────────────────────────────────────────────────

    function doExport(doc, fileName, isJPG, annOff, whiteMargin, dpi) {
        dpi = dpi || 150;

        var origBT, origBB, origBL, origBR;
        var dimLayerWasPrintable = null;
        var annLayerWasPrintable = null;
        var bgLayerName = "__ExportBG__";

        try {
            var dp = doc.documentPreferences;

            // Original bleed (mm)
            origBT = round1(dp.documentBleedTopOffset);
            origBB = round1(dp.documentBleedBottomOffset);
            origBL = round1(dp.documentBleedInsideOrLeftOffset);
            origBR = round1(dp.documentBleedOutsideOrRightOffset);

            // Expanded bleed covers annotations + white margin
            var extra = annOff + 8 + whiteMargin;
            var newBT = origBT + extra,  newBB = origBB + extra;
            var newBL = origBL + extra,  newBR = origBR + extra;

            dp.documentBleedTopOffset            = newBT;
            dp.documentBleedBottomOffset         = newBB;
            dp.documentBleedInsideOrLeftOffset   = newBL;
            dp.documentBleedOutsideOrRightOffset = newBR;

            // ── White background layer ────────────────────────────────────────
            var bgLayer = doc.layers.add({ name: bgLayerName });
            bgLayer.move(LocationOptions.AT_END);
            var prevActive = doc.activeLayer;
            doc.activeLayer = bgLayer;

            var docBaseName = doc.name.replace(/\.indd$/i, "");
            var now = new Date();
            function p2(n) { return n < 10 ? "0" + n : String(n); }
            var dateStr = p2(now.getDate()) + "." + p2(now.getMonth() + 1) + "." +
                          now.getFullYear() + ", " +
                          p2(now.getHours()) + ":" + p2(now.getMinutes());
            var infoFS = 13; // pt
            var infoMM = infoFS * 0.352778;
            var dimCol = doc.colors.itemByName("Dimensions");

            // ── Loop over all spreads ─────────────────────────────────────────
            var allPageNames = [];
            for (var si = 0; si < doc.spreads.length; si++) {
                var spread = doc.spreads[si];

                var pgs = [];
                for (var pi = 0; pi < spread.pages.length; pi++) {
                    var b = spread.pages[pi].bounds;
                    pgs.push({ left: b[1], right: b[3], top: b[0], bottom: b[2] });
                    allPageNames.push(spread.pages[pi].name);
                }
                pgs.sort(function (a, c) { return a.left - c.left; });

                var ox = pgs[0].left,  oy = pgs[0].top;
                var sw = pgs[pgs.length - 1].right - ox;
                var sh = pgs[0].bottom - oy;

                var rx1 = ox - newBL,  ry1 = oy - newBT;
                var rx2 = ox + sw + newBR, ry2 = oy + sh + newBB;

                // White background rect
                var bg = spread.rectangles.add({ geometricBounds: [ry1, rx1, ry2, rx2] });
                bg.fillColor   = doc.swatches[0];
                bg.strokeColor = doc.swatches[1];

                // Info label
                var totalW  = Math.round(origBL + sw + origBR);
                var totalH  = Math.round(origBT + sh + origBB);
                var infoTxt = docBaseName + "  |  " + dateStr + "  |  " +
                              totalW + " \u00D7 " + totalH + " mm";

                var tfX1 = rx1 + 4,  tfX2 = rx2 - 4;
                var tfY2 = ry2 - whiteMargin * 0.3;
                var tfY1 = tfY2 - infoMM * 2;

                var infoTF = spread.textFrames.add({ geometricBounds: [tfY1, tfX1, tfY2, tfX2] });
                try { infoTF.fillColor   = doc.swatches.itemByName("None"); } catch(e) {}
                try { infoTF.strokeColor = doc.swatches.itemByName("None"); } catch(e) {}
                try {
                    infoTF.textFramePreferences.autoSizingType =
                        AutoSizingTypeEnum.HEIGHT_ONLY;
                    infoTF.textFramePreferences.autoSizingReferencePoint =
                        AutoSizingReferenceEnum.BOTTOM_LEFT_POINT;
                } catch (e) {}
                infoTF.contents = infoTxt;

                var ip = infoTF.paragraphs[0];
                try { ip.appliedParagraphStyle = doc.paragraphStyles[0]; } catch (e) {}
                app.scriptPreferences.measurementUnit = MeasurementUnits.POINTS;
                try { ip.pointSize     = infoFS;                            } catch (e) {}
                try { ip.leading       = infoFS;                            } catch (e) {}
                try { ip.justification = Justification.LEFT_ALIGN;          } catch (e) {}
                try { ip.otfFigureStyle = OTFFigureStyle.PROPORTIONAL_LINING; } catch (e) {}
                try { ip.otfOrdinal    = false;                             } catch (e) {}
                try { ip.otfFraction   = false;                             } catch (e) {}
                try { ip.appliedFont   = app.fonts.itemByName("Minion Pro\tRegular"); } catch (e) {}
                app.scriptPreferences.measurementUnit = MeasurementUnits.MILLIMETERS;
                try { ip.fillColor = dimCol.isValid ? dimCol : doc.swatches[2]; } catch (e) {}
            }

            doc.activeLayer = prevActive;

            // ── Make Dimensions + Annotations layers printable ───────────────
            var dimLayer = doc.layers.itemByName("Dimensions");
            if (dimLayer.isValid) {
                dimLayerWasPrintable = dimLayer.printable;
                dimLayer.printable   = true;
            }
            var annLayer2 = doc.layers.itemByName("Annotations");
            if (annLayer2.isValid) {
                annLayerWasPrintable = annLayer2.printable;
                annLayer2.printable  = true;
            }

            // ── Page range (all spreads) ──────────────────────────────────────
            var pageRangeStr = allPageNames.join(", ");

            // ── Choose output folder ──────────────────────────────────────────
            var fn = fileName.match(/\.(jpg|jpeg|pdf)$/i) ? fileName :
                     fileName + (isJPG ? ".jpg" : ".pdf");
            var outFolder = Folder.selectDialog("Choose folder to save \u201C" + fn + "\u201D");
            if (!outFolder) return;
            var outFile = new File(outFolder.fsName + "/" + fn);

            // ── Export ────────────────────────────────────────────────────────
            if (isJPG) {
                // Pre-fill JPEG preferences; show InDesign's native dialog so
                // the user can confirm "Spreads" and click Export.
                var jp = app.jpegExportPreferences;
                jp.jpegQuality       = JPEGOptionsQuality.HIGH;
                jp.exportResolution  = dpi;
                jp.useDocumentBleeds = true;
                jp.jpegExportRange   = ExportRangeOrAllPages.EXPORT_RANGE;
                jp.pageString        = pageRangeStr;
                // showingOptions = true → InDesign opens its Export JPEG dialog
                doc.exportFile(ExportFormat.JPG, outFile, true);
            } else {
                var pp = app.pdfExportPreferences;
                pp.pageRange              = pageRangeStr;
                pp.exportReaderSpreads    = true;
                pp.useDocumentBleedWithPDF = true;
                pp.includeSlugWithPDF     = false;
                pp.cropMarks              = false;
                pp.bleedMarks             = false;
                pp.registrationMarks      = false;
                pp.colorBars              = false;
                pp.pageInformationMarks   = false;
                doc.exportFile(ExportFormat.PDF_TYPE, outFile, false);
            }

            try { outFile.execute(); } catch (e) {}

        } catch (e) {
            alert("Error: " + e.message + "\nLine: " + (e.line || "?"));
        } finally {

            // ── Restore bleed ─────────────────────────────────────────────────
            try {
                var dp2 = doc.documentPreferences;
                dp2.documentBleedTopOffset            = origBT;
                dp2.documentBleedBottomOffset         = origBB;
                dp2.documentBleedInsideOrLeftOffset   = origBL;
                dp2.documentBleedOutsideOrRightOffset = origBR;
            } catch (e) {}

            // ── Restore layers ────────────────────────────────────────────────
            try {
                if (dimLayerWasPrintable !== null)
                    doc.layers.itemByName("Dimensions").printable = dimLayerWasPrintable;
            } catch (e) {}
            try {
                if (annLayerWasPrintable !== null)
                    doc.layers.itemByName("Annotations").printable = annLayerWasPrintable;
            } catch (e) {}

            // ── Remove temp layer ─────────────────────────────────────────────
            try {
                var bl = doc.layers.itemByName(bgLayerName);
                if (bl && bl.isValid) bl.remove();
            } catch (e) {}

            restoreUnit();
        }
    }

    // ── Entry point ───────────────────────────────────────────────────────────

    if (app.documents.length === 0) {
        alert("Please open a document first.");
        restoreUnit();
    } else {
        run(app.activeDocument);
    }

})();
