// VMO HTML to PDF - Publisher Engine v3.0
// Fixes: full-content capture, interactive PDF form fields, reliable hyperlinks

(function () {

    /* ═══════════════════════════════════════════════════════════
       STATE
       ═══════════════════════════════════════════════════════════ */
    const state = {
        docType:      'auto',   // auto | book | webpage | form
        isLandscape:  false,
        paperSize:    'a4',
        margin:       0.5,
        generateTOC:  true,
        smartMedia:   true,
        smartForms:   true,
        liveUrl:      '',
        contactEmail: ''
    };

    /* ═══════════════════════════════════════════════════════════
       PREVIEW
       ═══════════════════════════════════════════════════════════ */
    window.vmoUpdatePreview = function () {
        const source   = document.getElementById('vmo-pdf-code').value;
        const preview  = document.getElementById('vmo-pdf-preview');
        preview.innerHTML = source;

        // Re-execute inline scripts (admin-only tool – intentional)
        preview.querySelectorAll('script').forEach(function (old) {
            var s = document.createElement('script');
            s.textContent = old.textContent;
            preview.appendChild(s);
        });

        vmoUpdatePreviewStyles();
        console.log('VMO PDF: Preview updated');
    };

    window.vmoUpdateConfig = function (key, value) {
        state[key] = value;
    };

    window.vmoUpdatePreviewStyles = function () {
        var el  = document.getElementById('vmo-pdf-preview');
        var btn = document.getElementById('btn-orientation');

        el.style.transform = 'none';
        el.style.transformOrigin = 'top left';
        el.style.height = 'auto';

        if (state.docType === 'book') {
            btn.style.display = 'inline-block';
            el.style.width    = state.isLandscape ? '297mm' : '210mm';
            el.style.minHeight = state.isLandscape ? '210mm' : '297mm';
            btn.innerHTML = state.isLandscape
                ? '🔄 Orientation: Landscape (Pitch Mode)'
                : '🔄 Orientation: Portrait (Book Mode)';
            el.style.boxShadow = '0 0 10px rgba(0,0,0,0.5)';
            el.style.margin    = '20px auto';
            el.style.overflow  = 'hidden';
        } else if (state.docType === 'form') {
            btn.style.display  = 'none';
            el.style.width     = '800px';
            el.style.minHeight = '400px';
            el.style.boxShadow = 'none';
            el.style.border    = '1px dashed #ccc';
            el.style.margin    = '20px auto';
            el.style.overflow  = 'visible';
        } else {
            // auto | webpage
            btn.style.display  = 'none';
            el.style.width     = '1000px';
            el.style.minHeight = '500px';
            el.style.boxShadow = '0 0 20px rgba(0,0,0,0.2)';
            el.style.margin    = '20px auto';
            el.style.overflow  = 'visible';
        }
    };

    window.vmoToggleOrientation = function () {
        state.isLandscape = !state.isLandscape;
        vmoUpdatePreviewStyles();
    };

    /* ═══════════════════════════════════════════════════════════
       PRE-PROCESS CLONE FOR PDF
       ═══════════════════════════════════════════════════════════ */
    function prepareForPDF(el) {

        // 0 ─ Flatten scroll / parallax libraries ─────────────
        el.querySelectorAll(
            '[data-scroll-container], .smooth-scroll, [data-scroll-section]'
        ).forEach(function (n) {
            n.style.setProperty('transform',  'none',     'important');
            n.style.setProperty('position',   'relative', 'important');
            n.style.setProperty('height',     'auto',     'important');
            n.style.setProperty('width',      '100%',     'important');
            n.style.setProperty('overflow',   'visible',  'important');
        });

        el.querySelectorAll('[data-scroll], [data-scroll-speed]').forEach(function (n) {
            n.style.setProperty('transform', 'none', 'important');
        });

        // 0.1 ─ Expand common sliders (Swiper / Slick / Owl) ─
        el.querySelectorAll('.swiper-wrapper, .slick-track, .owl-stage').forEach(function (track) {
            track.style.cssText += 'width:100%!important;transform:none!important;display:block!important;';
            Array.from(track.children).forEach(function (slide) {
                slide.style.cssText +=
                    'width:100%!important;opacity:1!important;visibility:visible!important;' +
                    'display:block!important;position:relative!important;left:auto!important;' +
                    'top:auto!important;margin:0 0 20px 0;';
            });
        });

        // 1 ─ Smart Media (video / audio → clickable overlay) ─
        if (state.smartMedia) {
            el.querySelectorAll('video, audio, embed, iframe').forEach(function (media) {
                var src = media.src || (media.querySelector('source') || {}).src;
                if (!src) return;

                var wrap = document.createElement('div');
                wrap.style.cssText = 'position:relative;display:inline-block;width:' +
                    (media.style.width || '100%') + ';';
                media.parentNode.insertBefore(wrap, media);
                wrap.appendChild(media);

                if (media.pause) media.pause();

                var overlay = document.createElement('a');
                overlay.href   = src;
                overlay.target = '_blank';
                overlay.title  = 'Click to Play Media';
                overlay.innerHTML = '▶';
                overlay.style.cssText =
                    'position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);' +
                    'width:60px;height:60px;background:rgba(0,0,0,0.6);border-radius:50%;' +
                    'display:flex;align-items:center;justify-content:center;color:white;' +
                    'font-size:30px;text-decoration:none;z-index:999;border:2px solid white;' +
                    'box-shadow:0 4px 6px rgba(0,0,0,0.3);';
                wrap.appendChild(overlay);
            });
        }

        // 2 ─ Smart Forms (style inputs, wrap submit in link) ─
        if (state.smartForms) {
            el.querySelectorAll('form').forEach(function (form) {
                form.querySelectorAll('input, textarea, select').forEach(function (inp) {
                    inp.style.border     = '1px solid #ccc';
                    inp.style.background = '#fff';
                });

                var submitBtn = form.querySelector(
                    'button[type="submit"], input[type="submit"], button:not([type])'
                );
                if (submitBtn) {
                    var email = state.contactEmail || 'admin@example.com';
                    var href  = state.liveUrl ||
                        ('mailto:' + email + '?subject=' + encodeURIComponent('Inquiry from PDF'));
                    var link  = document.createElement('a');
                    link.href   = href;
                    link.target = '_blank';
                    link.style.cssText = 'text-decoration:none;display:inline-block;position:relative;';
                    if (submitBtn.parentNode) {
                        submitBtn.parentNode.insertBefore(link, submitBtn);
                        link.appendChild(submitBtn);
                    }
                    submitBtn.title = 'Click to Submit (opens external)';
                }
            });
        }

        // 3 ─ Table of Contents (book mode only) ─────────────
        if (state.generateTOC && state.docType === 'book') {
            var headers = el.querySelectorAll('h1, h2');
            if (headers.length > 0) {
                var toc = document.createElement('div');
                toc.className = 'vmo-pdf-toc';
                toc.innerHTML = '<h2>Table of Contents</h2>';
                toc.style.pageBreakAfter = 'always';
                headers.forEach(function (h, i) {
                    if (!h.id) h.id = 'vmo-toc-' + i;
                    var item = document.createElement('div');
                    item.className = 'vmo-toc-item';
                    item.innerHTML = '<a href="#' + h.id + '" class="vmo-toc-link">' +
                        h.textContent + '</a>';
                    toc.appendChild(item);
                });
                el.prepend(toc);
            }
        }

        // 4 ─ Live-URL footer ─────────────────────────────────
        if (state.liveUrl) {
            var footer = document.createElement('div');
            footer.style.cssText =
                'margin-top:50px;padding-top:20px;border-top:2px solid #ddd;' +
                'text-align:center;page-break-inside:avoid;';
            footer.innerHTML =
                '<p style="font-size:14px;color:#64748b;">' +
                '<strong>Experience the Full Interactive Version:</strong><br>' +
                'Animations, Parallax, and Live Features are best viewed online.</p>' +
                '<a href="' + state.liveUrl + '" target="_blank" ' +
                'style="color:#06b6d4;font-weight:bold;font-size:16px;">' +
                state.liveUrl + '</a>';
            el.appendChild(footer);
        }
    }

    /* ═══════════════════════════════════════════════════════════
       WAIT FOR ALL IMAGES TO LOAD
       ═══════════════════════════════════════════════════════════ */
    function waitForImages(container) {
        var imgs = container.querySelectorAll('img');
        var promises = Array.from(imgs).map(function (img) {
            if (img.complete && img.naturalHeight > 0) return Promise.resolve();
            return new Promise(function (res) {
                img.onload  = res;
                img.onerror = res;
            });
        });
        // Also add a minimum 300ms settle time for CSS/fonts
        promises.push(new Promise(function (res) { setTimeout(res, 300); }));
        return Promise.all(promises);
    }

    /* ═══════════════════════════════════════════════════════════
       COLLECT FORM-FIELD GEOMETRY (relative to clone)
       ═══════════════════════════════════════════════════════════ */
    function collectFormFields(clone) {
        var fields = [];
        var root   = clone.getBoundingClientRect();

        clone.querySelectorAll(
            'input[type="text"], input[type="email"], input[type="tel"], ' +
            'input[type="number"], input[type="url"], input[type="search"], ' +
            'input:not([type]), textarea'
        ).forEach(function (inp, i) {
            var r = inp.getBoundingClientRect();
            if (r.width < 2 || r.height < 2) return; // skip hidden/collapsed
            fields.push({
                tag:         inp.tagName.toLowerCase(),
                type:        inp.type || 'text',
                name:        inp.name || inp.id || ('field_' + i),
                placeholder: inp.placeholder || '',
                value:       inp.value || '',
                x:           r.left - root.left,
                y:           r.top  - root.top,
                w:           r.width,
                h:           r.height
            });
        });
        return fields;
    }

    /* ═══════════════════════════════════════════════════════════
       OVERLAY REAL PDF FORM FIELDS (jsPDF AcroForm)
       Only for auto / webpage / form modes (single-page PDFs
       where the coordinate mapping is reliable).
       ═══════════════════════════════════════════════════════════ */
    function overlayFormFields(pdf, fields, htmlW, htmlH) {
        if (!fields.length || state.docType === 'book') return;

        // Locate the AcroFormTextField constructor (bundled inside jsPDF 2.x)
        var AcroTF = null;
        try {
            if (typeof window.AcroFormTextField === 'function')
                AcroTF = window.AcroFormTextField;
            else if (window.jsPDF && typeof window.jsPDF.AcroFormTextField === 'function')
                AcroTF = window.jsPDF.AcroFormTextField;
            else if (pdf.constructor && typeof pdf.constructor.AcroFormTextField === 'function')
                AcroTF = pdf.constructor.AcroFormTextField;
        } catch (e) { /* ignore */ }

        if (!AcroTF) {
            console.info('VMO PDF: AcroForm API not available — form fields rendered as images only.');
            return;
        }

        // The PDF page was created with format = [htmlW / 96, htmlH / 96] inches.
        // CSS-pixel positions map to inches at 96 DPI.
        var added = 0;
        fields.forEach(function (f) {
            try {
                var tf       = new AcroTF();
                tf.x         = f.x / 96;
                tf.y         = f.y / 96;
                tf.width     = f.w / 96;
                tf.height    = f.h / 96;
                tf.fieldName = f.name;
                tf.value     = f.value;
                tf.defaultValue = f.placeholder;
                tf.multiline = (f.tag === 'textarea');
                tf.maxFontSize = 12;
                pdf.addField(tf);
                added++;
            } catch (e) {
                console.warn('VMO PDF: Could not add field "' + f.name + '":', e.message);
            }
        });

        if (added > 0) {
            console.log('VMO PDF: Overlaid ' + added + ' interactive form field(s).');
        }
    }

    /* ═══════════════════════════════════════════════════════════
       MAIN GENERATION ENTRY POINT
       ═══════════════════════════════════════════════════════════ */
    window.vmoGeneratePDF = function () {
        var btn      = document.getElementById('btn-generate');
        var origHTML = btn.innerHTML;
        btn.innerHTML = '⏳ Rendering…';
        btn.disabled  = true;

        var source = document.getElementById('vmo-pdf-preview');
        var clone  = source.cloneNode(true);

        // ── Determine render width (CSS px) ──
        var renderW = 1000; // default for auto / webpage
        if (state.docType === 'book')  renderW = state.isLandscape ? 1122 : 794; // ≈ A4 at 96 dpi
        if (state.docType === 'form')  renderW = 800;

        // ── CRITICAL FIX: Build the hidden rendering container ──
        // Use position:fixed + opacity:0 so the element is IN the viewport
        // for accurate layout & html2canvas capture.
        // DO NOT use left:-9999px — that causes half-content clipping.
        var box = document.createElement('div');
        box.id = 'vmo-pdf-offscreen';
        box.style.cssText =
            'position:fixed;top:0;left:0;' +
            'width:' + renderW + 'px;' +
            'background:#fff;' +
            'z-index:-9999;opacity:0;pointer-events:none;' +
            'overflow:visible;box-sizing:border-box;' +
            'padding:0;margin:0;';

        // ── CRITICAL FIX: Reset clone styles that limit height ──
        // The preview pane sets overflow:hidden, min-height, etc.
        // These MUST be cleared so scrollHeight reports the FULL content.
        clone.style.width     = '100%';
        clone.style.height    = 'auto';
        clone.style.minHeight = 'auto';
        clone.style.maxHeight = 'none';
        clone.style.overflow  = 'visible';
        clone.style.boxShadow = 'none';
        clone.style.transform = 'none';
        clone.style.margin    = '0';
        clone.style.border    = 'none';
        // Keep padding for content spacing
        if (!clone.style.padding || clone.style.padding === '0px') {
            clone.style.padding = '20px';
        }

        box.appendChild(clone);
        document.body.appendChild(box);

        // Pre-process (TOC, media overlays, form links, live-URL footer)
        prepareForPDF(clone);

        // Wait for all images to load, then measure, then generate
        waitForImages(clone).then(function () {
            // Two requestAnimationFrame ticks to guarantee browser has completed layout
            requestAnimationFrame(function () {
                requestAnimationFrame(function () {
                    try {
                        doGenerate(clone, box, renderW, btn, origHTML);
                    } catch (err) {
                        console.error('VMO PDF fatal:', err);
                        alert('PDF generation failed: ' + err.message);
                        cleanup(btn, origHTML, box);
                    }
                });
            });
        });
    };

    /* ═══════════════════════════════════════════════════════════
       ACTUAL GENERATION (after layout is stable)
       ═══════════════════════════════════════════════════════════ */
    function doGenerate(clone, box, renderW, btn, origHTML) {
        // Force a reflow so dimensions are accurate
        void box.offsetHeight;

        // ── Measure FULL content dimensions ──
        var cW = Math.max(clone.scrollWidth,  clone.offsetWidth,  renderW);
        var cH = Math.max(clone.scrollHeight, clone.offsetHeight, 200);

        // Walk all descendants to find the true bottom edge
        // (catches margin-collapsed elements and absolutely-positioned children)
        var rootRect   = clone.getBoundingClientRect();
        var deepBottom = 0;
        clone.querySelectorAll('*').forEach(function (child) {
            var r = child.getBoundingClientRect();
            var bottom = r.bottom - rootRect.top;
            if (bottom > deepBottom) deepBottom = bottom;
        });
        if (deepBottom > cH) cH = deepBottom;

        // Safety margin to prevent any final-pixel clipping
        var safeH = cH + 80;

        // Collect form field geometry (before html2canvas snapshot)
        var formFields = collectFormFields(clone);

        // ── Build configs ──
        var jsPDFCfg, pageBrk, fname;
        var wIn, hIn;

        if (state.docType === 'book') {
            jsPDFCfg = {
                unit:        'in',
                format:      state.paperSize || 'a4',
                orientation: state.isLandscape ? 'landscape' : 'portrait'
            };
            pageBrk = { mode: ['avoid-all', 'css', 'legacy'] };
            fname   = 'vmo-document.pdf';
        } else {
            // auto | webpage | form → single continuous page sized to content
            wIn = cW    / 96;
            hIn = safeH / 96;
            jsPDFCfg = {
                unit:        'in',
                format:      [wIn, hIn],
                orientation: 'portrait'
            };
            pageBrk = { mode: [], before: [], after: [], avoid: [] };
            fname   = 'vmo-digital-doc.pdf';
        }

        var opt = {
            margin:      (state.docType === 'book') ? state.margin : 0,
            filename:    fname,
            image:       { type: 'jpeg', quality: 0.95 },
            enableLinks: true,  // Preserve <a> tags as clickable PDF link annotations
            html2canvas: {
                scale:          2,
                useCORS:        true,
                allowTaint:     true,
                logging:        false,
                letterRendering:true,
                // CRITICAL: Explicit width & height prevent html2canvas
                // from using the viewport size and clipping content.
                width:          cW,
                height:         safeH,
                windowWidth:    cW,
                windowHeight:   safeH,
                scrollX:        0,
                scrollY:        0,
                x:              0,
                y:              0
            },
            jsPDF:     jsPDFCfg,
            pagebreak: pageBrk
        };

        var sizeLabel = jsPDFCfg.format.length
            ? (wIn.toFixed(1) + '×' + hIn.toFixed(1) + ' in')
            : jsPDFCfg.format;
        console.log('VMO PDF: Generating — content ' + cW + '×' + Math.round(safeH) +
                     'px → PDF ' + sizeLabel);

        // ── Generate → overlay form fields → save ──
        html2pdf()
            .set(opt)
            .from(clone)
            .toPdf()
            .get('pdf')
            .then(function (pdf) {
                // Overlay interactive AcroForm text fields on top of the rendered image
                overlayFormFields(pdf, formFields, cW, safeH);
            })
            .save()
            .then(function () {
                console.log('VMO PDF: Download complete ✅');
                cleanup(btn, origHTML, box);
            })
            .catch(function (err) {
                console.error('VMO PDF generation error:', err);
                alert('PDF generation failed: ' + (err.message || err));
                cleanup(btn, origHTML, box);
            });
    }

    /* ═══════════════════════════════════════════════════════════
       CLEANUP
       ═══════════════════════════════════════════════════════════ */
    function cleanup(btn, origHTML, box) {
        btn.innerHTML = origHTML;
        btn.disabled  = false;
        if (box && box.parentNode) box.parentNode.removeChild(box);
    }

})();

/* ═══════════════════════════════════════════════════════════════
   BOOT
   ═══════════════════════════════════════════════════════════════ */
document.addEventListener('DOMContentLoaded', function () {
    window.vmoUpdatePreview();
});
