<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>DocuSign Template Builder</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
    <style>
        /* Your existing CSS remains exactly the same */
        /* ------------------------------
    General Reset
------------------------------ */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #f3f4f6;
            overflow: hidden;
            font-family: Arial, sans-serif;
        }

        /* ------------------------------
    Layout
------------------------------ */
        .main-container {
            display: flex;
            height: 100vh;
        }

        .left-tools {
            width: 250px;
            background: #fff;
            padding: 15px;
            border-right: 1px solid #ddd;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .field-btn {
            width: 100%;
            margin-bottom: 10px;
            border: 2px dashed #1d4ed8;
            background: #e0ecff;
            cursor: grab;
            transition: all 0.2s;
            /* **ADDED for Android touch-drag** */
            touch-action: none;
        }

        .field-btn:active {
            cursor: grabbing;
        }

        .field-btn:hover {
            background: #c7d2fe;
            border-color: #1e40af;
        }

        .canvas-area {
            flex: 1;
            padding: 20px;
            background: #e5e7eb;
            height: 100vh;
            overflow-y: auto;
            display: flex;
            justify-content: center;
        }

        #pdfPages {
            width: 100%;
            max-width: 850px;
        }

        .pdf-page {
            position: relative;
            margin: 0 auto 20px;
            background: #fff;
            box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .pdf-canvas {
            width: 100%;
            height: auto;
            display: block;
        }

        /* ------------------------------
    Field Overlay (labels & draggable)
------------------------------ */
        .field-overlay {
            position: absolute;
            border: 2px solid #2563eb;
            background: rgba(37, 99, 235, 0.1);
            padding: 2px 6px;
            cursor: move;
            font-size: 12px;
            font-weight: 600;
            border-radius: 4px;
            color: #1e40af;
            user-select: none;
            min-width: 80px;
            min-height: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: visible;
            white-space: nowrap;
            text-align: center;
        }

        .field-overlay:hover {
            background: rgba(37, 99, 235, 0.2);
            border-color: #1e40af;
        }

        /* Remove button */
        .field-overlay .remove-btn {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 14px;
            line-height: 1;
            display: none;
        }

        .field-overlay:hover .remove-btn {
            display: block;
        }

        /* Static label inside field (non-editable) */
        .field-label {
            display: inline-block;
            text-overflow: ellipsis;
            overflow: hidden;
            max-width: 100%;
        }

        /* Editable text field inside overlay */
        .field-overlay .editable-label {
            pointer-events: auto;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            user-select: text;
            cursor: text;
            outline: none;
        }

        /* Synced fields highlight */
        .synced-field {
            background-color: rgba(208, 211, 214, 0.15);
            border: 1px dashed #007bff;
            color: #007bff;
        }


        /* ------------------------------
    Field Counter / Info
------------------------------ */
        .field-count {
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 6px;
            padding: 8px;
            margin-top: 10px;
            font-size: 13px;
            color: #1e40af;
        }

        /* ------------------------------
    Upload Zone
------------------------------ */
        .upload-zone {
            border: 3px dashed #cbd5e1;
            border-radius: 8px;
            padding: 60px 20px;
            text-align: center;
            background: white;
            cursor: pointer;
            transition: all 0.3s;
            margin: 20px auto;
            max-width: 600px;
        }

        .upload-zone:hover {
            border-color: #1d4ed8;
            background: #f8fafc;
        }

        .upload-zone.drag-over {
            border-color: #10b981;
            background: #ecfdf5;
        }

        .upload-zone i {
            font-size: 3rem;
            color: #64748b;
            margin-bottom: 15px;
        }

        .upload-zone h3 {
            font-size: 1.5rem;
            color: #1f2937;
            margin-bottom: 10px;
        }

        .upload-zone p {
            color: #6b7280;
            margin-bottom: 20px;
        }

        .upload-zone.hidden {
            display: none;
        }

        /* ------------------------------
    Loading Overlay
------------------------------ */
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
            backdrop-filter: none;
        }

        .loading-overlay.show {
            display: flex;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #2563eb;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .edit-mode-badge {
            background: #fbbf24;
            color: #78350f;
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 10px;
            display: inline-block;
        }
    </style>
</head>

<body>
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
    </div>

    <div class="main-container">
        <div class="left-tools">
            <div id="editModeBadge" style="display: none;">
                <span class="edit-mode-badge">✏️ Edit Mode</span>
            </div>

            <h5 class="mb-3">📋 Field Types</h5>
            <button class="btn field-btn" draggable="true" ondragstart="dragField(event,'Signature')" ontouchstart="touchStartField(event,'Signature')" ontouchend="touchEndField(event)">✍️ Signature</button>
            <button class="btn field-btn" draggable="true" ondragstart="dragField(event,'Full Name')" ontouchstart="touchStartField(event,'Full Name')" ontouchend="touchEndField(event)">🧑 Full Name</button>
            <button class="btn field-btn" draggable="true" ondragstart="dragField(event,'Email')" ontouchstart="touchStartField(event,'Email')" ontouchend="touchEndField(event)">📧 Email</button>
            <button class="btn field-btn" draggable="true" ondragstart="dragField(event,'Date')" ontouchstart="touchStartField(event,'Date')" ontouchend="touchEndField(event)">📅 Date</button>
            <button class="btn field-btn" draggable="true" ondragstart="dragField(event,'Text')" ontouchstart="touchStartField(event,'Text')" ontouchend="touchEndField(event)">📝 Text</button>

            <hr class="my-3">

            <button class="btn btn-primary w-100 mb-2" id="loadBtn">📄 Upload Document</button>
            <button class="btn btn-success w-100" id="saveFieldsBtn">💾 Save Fields</button>

            <input type="hidden" id="docIdField" value="<?= $doc_id ?? '' ?>">

            <div class="field-count mt-3" id="fieldCount">
                <strong>Fields Added:</strong> <span id="fieldCountNum">0</span>
            </div>
        </div>

        <div class="canvas-area" id="pdfWrapper">
            <div id="pdfPages">
                <div class="upload-zone" id="uploadZone">
                    <i>📄</i>
                    <h3>Upload Document</h3>
                    <p>Drag & drop a <b>PDF</b> file here or click below to browse</p>

                    <label for="fileInput" class="btn btn-primary btn-lg" style="cursor: pointer;">
                        Browse Files
                    </label>
                </div>
            </div>
        </div>
    </div>



    <input type="file" id="fileInput" accept=".pdf" style="display: none;">

    <script>
        // ------------------------------
        // Configuration
        // ------------------------------
        const BASE_URL = "<?= base_url(); ?>";
        console.log("BASE_URL:", BASE_URL);
        // Get the full URL query parameters
        const params = new URLSearchParams(window.location.search);
        const docId = params.get('doc_id');
        const template_id = params.get('template_id');
                const myCaseLawId = params.get('myCaseLawId');
        console.log('docId:', docId);
        console.log('template_id:', template_id);

        // PDF.js worker - Use the SAME version as working code
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js';

        // ------------------------------
        // DOM References
        // ------------------------------
        const uploadZone = document.getElementById("uploadZone");
        const fileInput = document.getElementById("fileInput");
        const loadingOverlay = document.getElementById("loadingOverlay");
        const pdfWrapper = document.getElementById("pdfWrapper");
        const pdfPagesEl = document.getElementById("pdfPages");
        const loadBtn = document.getElementById("loadBtn");
        const saveBtn = document.getElementById("saveFieldsBtn");

        // ------------------------------
        // Global Variables
        // ------------------------------
        let pdfDoc = null;
        let scale = 1.5;
        let fields = [];
        let lastPdfBase64 = null;
        let lastDocxBase64 = null;
        let fileMimeType = null;
        let fileName = '';
        let fieldCounter = 0;
        let documentUploaded = false;
        let isEditMode = false;
        let existingTemplateId = null;
                let documentReplaced = false;


        // **MODIFIED/ADDED:** Global variables to track the field type and position for touch-drag
        let draggedFieldType = null;
        let lastTouchPosition = {
            clientX: 0,
            clientY: 0
        };

        // ------------------------------
        // Helper Functions
        // ------------------------------
        function getFieldDisplayNameFromTabType(tabType) {
            const map = {
                signHereTabs: "Signature",
                fullNameTabs: "Full Name",
                emailTabs: "Email",
                dateSignedTabs: "Date",
                textTabs: "Text",
                checkboxTabs: "Checkbox"
            };
            return map[tabType] || tabType;
        }

        function convertFieldType(type) {
            const map = {
                "Signature": "signature",
                "Full Name": "fullname",
                "Email": "email",
                "Date": "date",
                "Text": "text",
                "Checkbox": "checkbox"
            };
            return map[type] || "text";
        }

        function showLoading(show) {
            const overlay = document.getElementById("loadingOverlay");
            if (!overlay) return;
            if (show) overlay.classList.add("show");
            else overlay.classList.remove("show");
        }

        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // ------------------------------
        // Load Existing Document
        // ------------------------------
        async function loadExistingDocument(template_id) {
            showLoading(true);

            try {
                const res = await axios.post(`${BASE_URL}docusign/getTemplateWithFields`, {
                    template_id: template_id
                });

                if (!res.data.success) {
                    Swal.fire("Error", res.data.message || "Failed to load document", "error");
                    showLoading(false);
                    return false;
                }

                lastPdfBase64 = res.data.fileBase64;
                existingTemplateId = template_id;
                isEditMode = true;
                fileMimeType = 'application/pdf';
                fileName = 'existing-document.pdf';

                // Render PDF
                await renderPDF(lastPdfBase64);

                // Wait for pages to be ready
                await new Promise((resolve) => {
                    const checkPages = () => {
                        const allReady = Array.from(document.querySelectorAll(".pdf-page"))
                            .every(page => page.getBoundingClientRect().width > 0);
                        if (allReady) resolve();
                        else setTimeout(checkPages, 100);
                    };
                    checkPages();
                });

                // Load existing fields onto canvas
                for (const f of res.data.fields) {
                    const pageNum = parseInt(f.pageNumber);
                    const pageDiv = document.querySelector(`.pdf-page[data-page="${pageNum}"]`);
                    if (!pageDiv) continue;

                    const rect = pageDiv.getBoundingClientRect();
                    const pdfPage = await pdfDoc.getPage(pageNum);
                    const viewport = pdfPage.getViewport({
                        scale: 1
                    });

                    const pdfWidth = viewport.width;
                    const pdfHeight = viewport.height;

                    // Scale factors
                    const scaleX = rect.width / pdfWidth;
                    const scaleY = rect.height / pdfHeight;

                    // Convert DocuSign coordinates (bottom-left origin) to canvas (top-left origin)
                    const xPx = f.xPosition * scaleX;
                    const yPx = f.yPosition * scaleY;

                    const label = f.label || getFieldDisplayNameFromTabType(f.type);

                    addFieldToCanvas(
                        getFieldDisplayNameFromTabType(f.type),
                        xPx,
                        yPx,
                        pageNum,
                        rect.width,
                        rect.height,
                        pdfWidth,
                        pdfHeight,
                        label
                    );
                }

                // Hide upload zone and show canvas
                uploadZone.classList.add('hidden');
                documentUploaded = true;
                showLoading(false);

                Swal.fire({
                    icon: "success",
                    title: "Document Loaded",
                    text: "You can now edit the existing fields or add new ones",
                    timer: 2000,
                    showConfirmButton: false
                });

                return true;
            } catch (err) {
                console.error('Load error:', err);
                Swal.fire("Error", err.response?.data?.message || err.message, "error");
                showLoading(false);
                return false;
            }
        }

        // ------------------------------
        // Field Drag & Drop - FIXED FOR ANDROID TOUCH
        // ------------------------------
        function dragField(e, type) {
            e.dataTransfer.setData("fieldType", type);
            e.dataTransfer.effectAllowed = "copy";
        }

        // **ADDED/MODIFIED:** Add touch start event to set the dragged field type
        function touchStartField(e, type) {
            draggedFieldType = type;
            // Prevent scrolling on touch-drag for the button
            e.preventDefault();
        }

        // **ADDED/MODIFIED:** Add touch end event to clear the dragged field type (no-op here, used on document)
        function touchEndField(e) {
            // No operation, just preventing default tap behavior sometimes
        }

        document.getElementById("pdfWrapper").addEventListener("dragover", (e) => e.preventDefault());

        document.getElementById("pdfWrapper").addEventListener("drop", async (e) => {
            e.preventDefault();
            const fieldType = e.dataTransfer.getData("fieldType");
            if (!fieldType) return;
            await processDrop(fieldType, e.clientX, e.clientY);
        });

        // **ADDED/MODIFIED:** Listen for touchmove on the whole document to track position for drop
        document.addEventListener('touchmove', (e) => {
            if (e.touches.length === 1 && draggedFieldType) {
                lastTouchPosition.clientX = e.touches[0].clientX;
                lastTouchPosition.clientY = e.touches[0].clientY;
                // e.preventDefault(); // Might break scrolling, keep passive true
            }
        }, { passive: true });


        // **ADDED/MODIFIED:** Handle the drop on touchend for the entire document area
        document.addEventListener('touchend', async (e) => {
            if (!draggedFieldType) return;

            // Check if the touchend occurred over a PDF page
            const targetElement = document.elementFromPoint(lastTouchPosition.clientX, lastTouchPosition.clientY);
            const pageDiv = targetElement?.closest(".pdf-page");

            if (pageDiv) {
                // Simulate the drop using the last recorded touch position
                await processDrop(draggedFieldType, lastTouchPosition.clientX, lastTouchPosition.clientY);
            }

            // Clear the tracking variable
            draggedFieldType = null;
        });

        // **ADDED/MODIFIED:** Consolidate the drop logic into a reusable function
        async function processDrop(fieldType, clientX, clientY) {
            // If current uploaded is DOCX, disallow placement
            if (fileMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                Swal.fire("Info", "Field placement is only supported for PDF files in the browser. Upload a PDF to place fields.", "info");
                return;
            }

            const targetElement = document.elementFromPoint(clientX, clientY);
            const pageDiv = targetElement?.closest(".pdf-page");
            if (!pageDiv) return;

            const pageNum = Number(pageDiv.getAttribute("data-page"));
            const rect = pageDiv.getBoundingClientRect();

            // Calculate coordinates relative to the page div
            const xPx = clientX - rect.left;
            const yPx = clientY - rect.top;

            const pdfPage = await pdfDoc.getPage(pageNum);
            const viewport = pdfPage.getViewport({
                scale: 1
            });

            addFieldToCanvas(fieldType, xPx, yPx, pageNum, rect.width, rect.height, viewport.width, viewport.height);
        }

        // ------------------------------
        // Field Management - EXACTLY like working code
        // ------------------------------
        function addFieldToCanvas(fieldType, xPx, yPx, pageNum, pageWidth, pageHeight, pdfWidth, pdfHeight, existingLabel = null) {
            const page = document.querySelector(`.pdf-page[data-page="${pageNum}"]`);
            if (!page) return;

            const fieldId = `field_${++fieldCounter}`;

            let field = document.createElement("div");
            field.className = "field-overlay";
            field.id = fieldId;

            // Display label - EXACTLY like working code
            let displayLabel = existingLabel || fieldType;
            const labelSpan = document.createElement("span");
            labelSpan.textContent = displayLabel;
            labelSpan.className = "field-label";

            if (fieldType === "Text") {
                labelSpan.contentEditable = "true";
                labelSpan.setAttribute("role", "textbox");
                labelSpan.setAttribute("aria-label", "Edit field label");

                labelSpan.addEventListener("input", () => {
                    const f = fields.find(f => f.id === fieldId);
                    if (f) f.label = labelSpan.textContent;
                });

                labelSpan.addEventListener("blur", (e) => {
                    const f = fields.find(f => f.id === fieldId);
                    if (f) f.label = labelSpan.textContent.trim() || fieldType;
                });

                labelSpan.addEventListener("keydown", (ev) => {
                    if (ev.key === "Enter") {
                        ev.preventDefault();
                        labelSpan.blur();
                    }
                });
            }

            field.appendChild(labelSpan);

            // **Set canvas coordinates directly** - EXACTLY like working code
            field.style.left = xPx + "px";
            field.style.top = yPx + "px";

            const removeBtn = document.createElement("button");
            removeBtn.className = "remove-btn";
            removeBtn.textContent = "×";
            removeBtn.onclick = () => removeField(fieldId);
            field.appendChild(removeBtn);

            page.appendChild(field);

            makeDraggable(field, page, pdfWidth, pdfHeight);

            const fieldWidthPx = 120;
            const fieldHeightPx = 30;

            // Convert canvas pixels to PDF points - EXACTLY like working code
            const x = Math.round((xPx / pageWidth) * pdfWidth);
            const y = Math.round(pdfHeight - ((yPx + fieldHeightPx) / pageHeight) * pdfHeight);
            const width = Math.round((fieldWidthPx / pageWidth) * pdfWidth);
            const height = Math.round((fieldHeightPx / pageHeight) * pdfHeight);

            fields.push({
                id: fieldId,
                fieldType,
                label: displayLabel,
                x,
                y,
                pageNum,
                xPx,
                yPx,
                originalWidth: pageWidth,
                originalHeight: pageHeight,
                pdfWidth,
                pdfHeight,
                width,
                height
            });

            updateFieldCount();
        }

        function makeDraggable(element, container, originalWidth, originalHeight) {
            let isDragging = false,
                startX, startY, initialLeft, initialTop;

            const startDrag = (x, y) => {
                isDragging = true;
                startX = x;
                startY = y;
                initialLeft = element.offsetLeft;
                initialTop = element.offsetTop;
                element.style.cursor = "grabbing";
                element.style.zIndex = 1000;
            };

            const dragMove = (x, y) => {
                if (!isDragging) return;
                const dx = x - startX,
                    dy = y - startY;
                const newLeft = Math.max(0, Math.min(initialLeft + dx, container.clientWidth - element.offsetWidth));
                const newTop = Math.max(0, Math.min(initialTop + dy, container.clientHeight - element.offsetHeight));

                element.style.left = newLeft + "px";
                element.style.top = newTop + "px";

                // Update fields array with new PX and PDF coordinates
                const fieldData = fields.find(f => f.id === element.id);
                if (fieldData) {
                    fieldData.xPx = newLeft;
                    fieldData.yPx = newTop;
                    // Recalculate PDF points based on new canvas position
                    const fieldHeightPx = 30;
                    fieldData.x = Math.round((newLeft / container.clientWidth) * originalWidth);
                    fieldData.y = Math.round(originalHeight - ((newTop + fieldHeightPx) / container.clientHeight) * originalHeight);
                }
            };

            const endDrag = () => {
                if (!isDragging) return;
                isDragging = false;
                element.style.cursor = "move";
                element.style.zIndex = "";
            };

            // Mouse Events
            element.addEventListener("mousedown", e => {
                if (e.target.classList.contains("remove-btn") || e.target.classList.contains("field-label")) return;
                startDrag(e.clientX, e.clientY);
                e.preventDefault();
            });

            document.addEventListener("mousemove", e => dragMove(e.clientX, e.clientY));
            document.addEventListener("mouseup", endDrag);

            // Touch Events (For Android/Mobile) - **Kept from the previous fix for DRAGGING EXISTING FIELDS**
            element.addEventListener("touchstart", e => {
                if (e.target.classList.contains("remove-btn") || e.target.classList.contains("field-label")) return;
                const touch = e.touches[0];
                startDrag(touch.clientX, touch.clientY);
                e.stopPropagation();
            }, {
                passive: true
            });

            document.addEventListener("touchmove", e => {
                if (!isDragging || e.touches.length === 0) return;
                const touch = e.touches[0];
                dragMove(touch.clientX, touch.clientY);
                e.preventDefault();
            }, {
                passive: false
            });

            document.addEventListener("touchend", endDrag);
            document.addEventListener("touchcancel", endDrag);
        }

        function removeField(fieldId) {
            fields = fields.filter(f => f.id !== fieldId);
            document.getElementById(fieldId)?.remove();
            updateFieldCount();
        }

        function updateFieldCount() {
            document.getElementById("fieldCountNum").textContent = fields.length;
        }

        function validateRequiredFields() {
            if (lastPdfBase64 || lastDocxBase64) {
                saveBtn.removeAttribute("disabled");
            }

            if (lastPdfBase64 && fields.length > 0) {
                const hasSignature = fields.some(f => f.fieldType === "Signature");
                if (!hasSignature) {
                    Swal.fire('Signature Required', 'Please add a signature field before saving', 'warning');
                    return false;
                }
            }

            return true;
        }

        // ------------------------------
        // File Upload Handling
        // ------------------------------
        loadBtn?.addEventListener("click", (e) => {
            e.stopPropagation();
            fileInput.click();
        });

        uploadZone?.addEventListener("dragover", (e) => {
            e.preventDefault();
            uploadZone.classList.add("drag-over");
        });
        uploadZone?.addEventListener("dragleave", () => uploadZone.classList.remove("drag-over"));
        uploadZone?.addEventListener("drop", async (e) => {
            e.preventDefault();
            uploadZone.classList.remove("drag-over");
            const files = e.dataTransfer.files;
            if (!files || files.length === 0) return;
            await handleFileSelection(files[0]);
        });

        fileInput?.addEventListener("change", async (e) => {
            if (!e.target.files || e.target.files.length === 0) return;
            await handleFileSelection(e.target.files[0]);
        });

        async function handleFileSelection(file) {
            if (!file) return;

            // Warn if replacing in edit mode
            if (isEditMode) {
                const result = await Swal.fire({
                    title: 'Replace Document?',
                    text: 'This will replace the existing document. All current fields will be cleared.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, replace it',
                    cancelButtonText: 'Cancel'
                });

                if (!result.isConfirmed) return;
                                documentReplaced = true;
            } else if (documentUploaded) {
                const result = await Swal.fire({
                    title: 'Document Already Loaded',
                    text: 'A document is already loaded. Do you want to replace it?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, replace it',
                    cancelButtonText: 'Cancel'
                });

                if (!result.isConfirmed) return;

            }

            const allowed = [
                "application/pdf",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            ];
            if (!allowed.includes(file.type)) {
                Swal.fire("Invalid file type", "Please upload a PDF or DOCX file only!", "error");
                return;
            }

            const MAX_BYTES = 10 * 1024 * 1024;
            if (file.size > MAX_BYTES) {
                Swal.fire("File too large", "File size exceeds 10MB limit", "error");
                return;
            }

            // Reset state
            pdfPagesEl.innerHTML = '';
            fields = [];
            fieldCounter = 0;
            pdfDoc = null;
            lastPdfBase64 = null;
            lastDocxBase64 = null;
            fileMimeType = file.type;
            fileName = file.name;

            showLoading(true);

            const reader = new FileReader();
            reader.onload = async (evt) => {
                const base64 = evt.target.result.split(',')[1];

                if (file.type === 'application/pdf') {
                    lastPdfBase64 = base64;
                    lastDocxBase64 = null;
                    await renderPDF(lastPdfBase64);
                    uploadZone.classList.add('hidden');
                    documentUploaded = true;
                    showLoading(false);
                    // Swal.fire("Loaded", `${file.name} loaded for field placement`, "success");
                    Swal.fire({
  title: "Loaded",
  text: `${file.name} loaded for field placement`,
  icon: "success",
  showConfirmButton: false,
  timer: 2000
});

                } else {
                    lastDocxBase64 = base64;
                    lastPdfBase64 = null;
                    pdfPagesEl.innerHTML = `
                        <div class="pdf-page p-5 text-center">
                            <h4>📄 ${escapeHtml(file.name)}</h4>
                            <p>This is a DOCX file. Field placement is not available in the browser for DOCX files.</p>
                            <p>Click <strong>Save Fields</strong> to upload the DOCX to server for conversion/processing.</p>
                        </div>`;
                    uploadZone.classList.add('hidden');
                    documentUploaded = true;
                    showLoading(false);
                    Swal.fire("DOCX ready", `${file.name} is ready to upload to server.`, "info");
                }

                saveBtn.removeAttribute("disabled");
                updateFieldCount();
            };
            reader.readAsDataURL(file);
        }

        // ------------------------------
        // PDF Rendering - Use the SAME approach as working code
        // ------------------------------
        async function renderPDF(base64pdf) {
            const container = pdfPagesEl;
            container.innerHTML = "";
            fields = [];
            fieldCounter = 0;
            updateFieldCount();

            try {
                const pdfData = atob(base64pdf);
                pdfDoc = await pdfjsLib.getDocument({
                    data: pdfData
                }).promise;

                // Wait for all pages to render - LIKE WORKING CODE
                const pagePromises = [];
                for (let i = 1; i <= pdfDoc.numPages; i++) {
                    pagePromises.push(renderPage(i));
                }
                await Promise.all(pagePromises);
            } catch (err) {
                console.error('PDF render error:', err);
                Swal.fire("Error", "Failed to render PDF", "error");
            }
        }

        async function renderPage(num) {
            const page = await pdfDoc.getPage(num);
            const viewport = page.getViewport({
                scale
            });

            const pageDiv = document.createElement("div");
            pageDiv.className = "pdf-page";
            pageDiv.setAttribute("data-page", num);

            const canvas = document.createElement("canvas");
            canvas.className = "pdf-canvas";
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            // Add canvas to pageDiv and then pageDiv to container (pdfPagesEl)
            pageDiv.appendChild(canvas);
            pdfPagesEl.appendChild(pageDiv);

            const renderContext = {
                canvasContext: canvas.getContext('2d'),
                viewport: viewport
            };

            await page.render(renderContext).promise;

            // This is the end of the original file, need to close the function/script block.
        }

        // Replace the saveBtn.addEventListener("click", async () => { ... }) section in Fresh View
// with this corrected version:

saveBtn.addEventListener("click", async () => {
    // Basic checks
    if (!lastPdfBase64 && !lastDocxBase64) {
        Swal.fire("Error", "No file uploaded", "error");
        return;
    }

    // Simple validation check
    if (!validateRequiredFields()) {
        return;
    }

    // If PDF: must have at least one signature
    if (lastPdfBase64) {
        const hasSignature = fields.some(f => f.fieldType === "Signature");
        if (!hasSignature) {
            Swal.fire({
                title: "Add Signature Field",
                text: "At least one signature field is required to proceed.",
                icon: "warning",
                timer: 5000,
                showConfirmButton: false
            });
            return;
        }
    }

    showLoading(true);

    const payload = {
        filename: fileName,
        total_pages: pdfDoc ? pdfDoc.numPages : 0,
        pdf_base64: lastPdfBase64 || null,
        docx_base64: lastDocxBase64 || null,
        mime_type: fileMimeType,
        doc_id: docId,
        template_id: isEditMode ? existingTemplateId : null,
        is_edit: isEditMode,
        document_replaced: documentReplaced,
                myCaseLawId: myCaseLawId || null,
        fields: (fields || []).map(f => {
            // FIX: Calculate normalized positions from CANVAS pixels
            // (matching Index View's approach)
            const normalizedX = f.xPx / f.originalWidth;
            const normalizedY = f.yPx / f.originalHeight;
            const fieldWidthPx = 120;  // Must match your actual field width
            const fieldHeightPx = 30;  // Must match your actual field height
            const normalizedWidth = fieldWidthPx / f.originalWidth;
            const normalizedHeight = fieldHeightPx / f.originalHeight;

            // Apply the SAME scaling as Index View (multiply by 500 and 700)
            const docusignX = Math.round(normalizedX * 500);
            const docusignY = Math.round(normalizedY * 700);
            const docusignWidth = Math.round(normalizedWidth * 500);
            const docusignHeight = Math.round(normalizedHeight * 700);

            return {
                type: convertFieldType(f.fieldType),
                label: f.label || f.fieldType,
                page: f.pageNum,
                //  Send DocuSign coordinates directly (NOT normalized 0-1 values)
                x: docusignX / 500,     // Backend will multiply by 500
                y: docusignY / 700,     // Backend will multiply by 700
                width: docusignWidth / 500,
                height: docusignHeight / 700,
                value: f.fieldType === "Text" ? f.label : ''
            };
        })
    };

    try {
        const endpoint = isEditMode ?
            `${BASE_URL}docusign/updateTemplateFields` :
            `${BASE_URL}docusign/uploadTemplate`;

        const res = await axios.post(endpoint, payload);

        showLoading(false);
        if (res.data?.success) {
            const title = isEditMode ? "Document Updated!" : "Document Saved!";

                    await Swal.fire({
                        icon: "success",
                        title: title,
                        showConfirmButton: true
                    });


            if (isEditMode) {
                const result = await Swal.fire({
                    icon: "success",
                    title: "Success",
                    text: "Document saved successfully",
                    showCancelButton: false,
                    allowOutsideClick: false,
                    confirmButtonText: "OK",
                });

                if (!result.isConfirmed) {
                    window.close();
                }
            }
        } else {
            Swal.fire("Error", res.data?.message || "Failed to save document", "error");
        }
    } catch (err) {
        showLoading(false);
        console.error('Save error:', err);
        Swal.fire("Error", err.response?.data?.message || err.message, "error");
    }
});


        document.addEventListener('DOMContentLoaded', () => {
            if (template_id) {
                document.getElementById('editModeBadge').style.display = 'inline-block';
                loadExistingDocument(template_id);
            }
        });
    </script>
</body>

</html>
