find and fix issues with this code, pdf not loading, dragging is not working as expected, fields not sticking to mouse cursor and interface does not look or feel like pandadoc and cannot see page thumbnails etc fix every issue <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PandaDoc Clone - PDF Editor & E-Signature Tool</title>

  <!-- PDF Libraries -->
  <script src="https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/4.1.5/signature_pad.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>

  <!-- Styling -->
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      color: #333;
    }

    .container {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }

    .toolbar {
      display: flex;
      padding: 10px;
      justify-content: space-between;
      gap: 10px;
      background-color: #0071f2;
      border-bottom: 1px solid #ddd;
    }

    .toolbar button, 
    .toolbar input[type="file"], 
    .toolbar select {
      padding: 8px 12px;
      font-size: 14px;
      border: none;
      background: white;
      color: #0071f2;
      border-radius: 5px;
      cursor: pointer;
      transition: background 0.3s;
    }

    .toolbar button:hover, 
    .toolbar input[type="file"]:hover {
      background: #f4f4f8;
      color: #005bb5;
    }

    #pdfViewer {
      flex: 1;
      display: flex;
      overflow: hidden;
    }

    #pageThumbnails {
      width: 150px;
      overflow-y: auto;
      padding: 10px;
      border-right: 1px solid #ddd;
      background: #fff;
    }

    #pageThumbnails img {
      display: block;
      width: 100%;
      margin-bottom: 10px;
      cursor: pointer;
    }

    #pageThumbnails img.active {
      border: 2px solid #0071f2;
    }

    .pdfCanvasWrapper {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      background: #f4f4f8;
    }

    canvas {
      border: 1px solid #ddd;
    }

    /* Editable Fields */
    .field {
      position: absolute;
      border: 1px dashed gray;
      padding: 5px;
      background-color: white;
      cursor: move;
      min-width: 100px;
      min-height: 20px;
      box-sizing: border-box;
    }

    .field.highlight {
      border-color: blue;
    }

    /* Field Resizer */
    .field .resizer {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 10px;
      height: 10px;
      background: #ccc;
      cursor: nwse-resize;
    }

    /* Modal Styling */
    #modalOverlay {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
    }

    #propertiesModal {
      display: none;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 20px;
      background: white;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
      border-radius: 8px;
      width: 350px;
      z-index: 1000;
    }

    .footer {
      padding: 10px;
      text-align: center;
      background: #0071f2;
      color: white;
    }

    button.modal-btn {
      display: inline-block;
      padding: 8px 16px;
      margin-left: 5px;
      border: none;
      cursor: pointer;
    }

    button.modal-btn.delete {
      color: red;
      background: #ffe8e8;
    }

    button.modal-btn.save {
      color: green;
      background: #e8ffe8;
    }
  </style>
</head>
<body>
  <div class="container">
    <!-- Toolbar -->
    <div class="toolbar">
      <input type="file" id="uploadPDF" accept=".pdf">
      <button id="addTextField">Add Text</button>
      <button id="addSignatureField">Add Signature</button>
      <button id="finalizePDF">Finalize PDF</button>
      <input type="file" id="loadDraft" style="display:none;"/>
      <button id="saveDraft">Save Draft</button>
      <select id="activeSigner">
        <option value="signer1">Signer 1</option>
        <option value="signer2">Signer 2</option>
      </select>
    </div>
    
    <!-- PDF Viewer -->
    <div id="pdfViewer">
      <div id="pageThumbnails"></div>
      <div class="pdfCanvasWrapper">
        <canvas id="pdfCanvas"></canvas>
      </div>
    </div>
    
    <!-- Footer -->
    <div class="footer">
      Certificate ID: <span id="certificateId"></span>
    </div>
  </div>

  <!-- Field Properties Modal -->
  <div id="modalOverlay"></div>
  <div id="propertiesModal">
    <h3>Field Properties</h3>
    <input type="text" id="fieldName" placeholder="Field Name">
    <input type="text" id="fieldValue" placeholder="Default Value">
    <button class="modal-btn save" id="saveProperties">Save</button>
    <button class="modal-btn delete" id="deleteField">Delete</button>
  </div>

<script>
  // State Variables
  let pdfDoc = null;
  let canvas = document.getElementById("pdfCanvas");
  let ctx = canvas.getContext("2d");
  let currentPage = 1;
  let scale = 1.5;
  let fields = [];
  let activeSigner = "signer1";
  let certificateId = `CERT-${Math.random().toString(36).substring(2, 10).toUpperCase()}`;
  document.getElementById("certificateId").innerText = certificateId;

  // Load PDF
  document.getElementById("uploadPDF").addEventListener("change", async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async function () {
      const pdfBytes = new Uint8Array(reader.result);
      pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
      currentPage = 1;
      renderPDF();
    };
    reader.readAsArrayBuffer(file);
  });

  async function renderPDF() {
    const page = pdfDoc.getPages()[currentPage - 1];
    const viewportWidth = page.getWidth() * scale;
    const viewportHeight = page.getHeight() * scale;

    canvas.width = viewportWidth;
    canvas.height = viewportHeight;

    const pageImage = await page.render({
      scale: scale,
    });
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(pageImage.imageData, 0, 0, viewportWidth, viewportHeight);

    renderThumbnails();
    renderFields();
  }

  async function renderThumbnails() {
    const thumbnailContainer = document.getElementById("pageThumbnails");
    thumbnailContainer.innerHTML = ""; // Clear previous thumbnails

    for (let i = 0; i < pdfDoc.getPageCount(); i++) {
      const page = pdfDoc.getPages()[i];
      const scale = 0.25;
      const thumbnailCanvas = document.createElement("canvas");
      thumbnailCanvas.width = page.getWidth() * scale;
      thumbnailCanvas.height = page.getHeight() * scale;

      const ctx = thumbnailCanvas.getContext("2d");
      const pageImage = await page.render({
        scale: scale,
      });
      ctx.drawImage(pageImage.imageData, 0, 0, thumbnailCanvas.width, thumbnailCanvas.height);

      thumbnailCanvas.addEventListener("click", () => {
        currentPage = i + 1;
        renderPDF();
      });

      thumbnailContainer.appendChild(thumbnailCanvas);
    }
  }

  // Add Fields
  document.getElementById("addTextField").addEventListener("click", () => addField("text"));
  document.getElementById("addSignatureField").addEventListener("click", () => addField("signature"));

  function addField(type) {
    fields.push({
      id: `field-${Date.now()}`,
      type,
      page: currentPage,
      x: 100,
      y: 100,
      value: "",
      required: false,
      signer: activeSigner,
    });
    renderFields();
  }

  function renderFields() {
    const wrapper = document.querySelector(".pdfCanvasWrapper");
    wrapper.querySelectorAll(".field").forEach(field => field.remove());

    fields.forEach((field) => {
      if (field.page !== currentPage) return;

      const div = document.createElement("div");
      div.className = `field ${field.type === "text" ? "text-field" : "signature-field"}`;
      div.style.left = `${field.x}px`;
      div.style.top = `${field.y}px`;
      div.innerText = field.type === "text" ? "Text Field" : "Signature";
      div.setAttribute("data-id", field.id);

      // Dragging functionality
      div.addEventListener("mousedown", (e) => startDragging(e, field, div));

      // Open the field configuration modal
      div.addEventListener("dblclick", () => openPropertiesModal(field));
      makeResizable(div);

      wrapper.appendChild(div);
    });
  }

  // Dragging functionality
  let dragField = null;
  function startDragging(event, field, div) {
    dragField = field;
    const shiftX = event.clientX - div.getBoundingClientRect().left;
    const shiftY = event.clientY - div.getBoundingClientRect().top;

    function moveAt(pageX, pageY) {
      field.x = Math.max(pageX - shiftX, 0);
      field.y = Math.max(pageY - shiftY, 0);
      div.style.left = `${field.x}px`;
      div.style.top = `${field.y}px`;
    }

    function onMouseMove(event) {
      moveAt(event.pageX, event.pageY);
    }

    document.addEventListener("mousemove", onMouseMove);

    div.onmouseup = () => {
      document.removeEventListener("mousemove", onMouseMove);
      dragField = null;
      div.onmouseup = null;
    };
  }

  // Resizable fields
  function makeResizable(fieldElement) {
    const resizer = document.createElement("div");
    resizer.className = "resizer";
    fieldElement.appendChild(resizer);
    resizer.addEventListener("mousedown", function (e) {
      const startX = e.clientX;
      const startY = e.clientY;
      const startWidth = parseInt(window.getComputedStyle(fieldElement).width);
      const startHeight = parseInt(window.getComputedStyle(fieldElement).height);

      function resize(e) {
        const newWidth = startWidth + e.clientX - startX;
        const newHeight = startHeight + e.clientY - startY;
        fieldElement.style.width = `${Math.max(50, newWidth)}px`;
        fieldElement.style.height = `${Math.max(20, newHeight)}px`;
      }

      function stopResize() {
        document.removeEventListener("mousemove", resize);
        document.removeEventListener("mouseup", stopResize);
      }

      document.addEventListener("mousemove", resize);
      document.addEventListener("mouseup", stopResize);
    });
  }

  // Open/Close Field Properties Modal
  function openPropertiesModal(field) {
    document.getElementById("modalOverlay").style.display = "block";
    document.getElementById("propertiesModal").style.display = "block";

    document.getElementById("fieldName").value = field.type;
    document.getElementById("fieldValue").value = field.value || "";

    document.getElementById("saveProperties").onclick = () => {
      field.value = document.getElementById("fieldValue").value;
      closePropertiesModal();
    };

    document.getElementById("deleteField").onclick = () => {
      fields = fields.filter(f => f !== field);
      closePropertiesModal();
      renderFields();
    };
  }

  function closePropertiesModal() {
    document.getElementById("modalOverlay").style.display = "none";
    document.getElementById("propertiesModal").style.display = "none";
  }

  // Finalize PDF
  async function finalizePDF() {
    const updatedPdfDoc = await PDFLib.PDFDocument.create();
    const pages = pdfDoc.getPages();

    for (let i = 0; i < pages.length; i++) {
      const copiedPages = await updatedPdfDoc.copyPages(pdfDoc, [i]);
      const page = copiedPages[0];

      // Draw all fields for the current page
      fields.filter(f => f.page === i + 1).forEach((field) => {
        page.drawText(field.value || field.type, {
          x: field.x,
          y: page.getHeight() - field.y - 20,
          size: 12,
        });
      });

      updatedPdfDoc.addPage(page);
    }

    const pdfBytes = await updatedPdfDoc.save();
    const blob = new Blob([pdfBytes], { type: "application/pdf" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = `finalized-${certificateId}.pdf`;
    link.click();
  }

  // Save Draft
  document.getElementById("saveDraft").addEventListener("click", () => {
    const draft = JSON.stringify({ fields, currentPage, certificateId });
    const blob = new Blob([draft], { type: "application/json" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "draft.json";
    link.click();
  });

  // Load Draft
  document.getElementById("loadDraft").addEventListener("change", (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = () => {
      const { fields: loadedFields, currentPage: loadedPage } = JSON.parse(reader.result);
      fields = loadedFields;
      currentPage = loadedPage;
      renderPDF();
      renderFields();
    };
    reader.readAsText(file);
  });
</script>
</body>
</html>