addStyle(`

    .upload-footer-btn, .btn-secondary{
    padding: 4px 4px;
        background-color: rgba(100,100,100,.5);
        color: rgba(2200,250,250,1);
        border-radius: 4px;
border: 0px solid #ddd;
margin:2px;
    }
  #uploadbtn {
    height: 36px; /* Fixed height */
    display: flex;
    align-items: center;
    gap: 8px;
}

#uploadbtn .btn {
    border: none;
    padding: 4px 8px;
    transition: background-color 0.2s;
}

#uploadbtn .btn:hover {
    background-color: rgba(0,0,0,0.1);
}
    /* File list items */
.file-item {
    height: 40px;
    display: flex;
    align-items: center;
    padding: 4px 8px;
    background-color: white;
    border-radius: 6px;
    margin-bottom: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    cursor: pointer;
}

/* Upload button area */
#uploadbtn {
    height: 36px;
    margin-top: 10px;
    display: flex;
    align-items: center;
    gap: 8px;
}

#uploadbtn .btn {
    border: none;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;
}

#uploadbtn .btn:hover {
    background-color: rgba(0,0,0,0.1);
}

/* Status indicators */
.status-indicator {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 6px;
    display:none;
}

.status-uploading {
    background-color: #2196F3;
}

.status-success {
    background-color: #4CAF50;
}

.status-error {
    background-color: #f44336;
}

/* Panel footer */
.panel-footer {
    height: 40px;
    padding: 4px 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Compact file info */
.file-info {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    font-size: 13px;
}

.file-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-right: 5px;
}

.file-size {
    font-size: 11px;
    color: #777;
    white-space: nowrap;
}
`);
// File upload and preview logic
let filesToUpload = [];
let currentUploads = [];
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
const MAX_TOTAL_SIZE = 200 * 1024 * 1024; // 200MB
const MAX_FILE_COUNT = 4;
const SERVER_BASE = "https://q.kunok.com/s9/s/y225e1/project1/user1/";
window.debug = true;

let isUploadPanelOpen = false;
function toggleUploadPanel() {
  if (isUploadPanelOpen) {
    closePanel("uploadPanel");
    isUploadPanelOpen = false;
  } else {
    createUploadPanel();
    isUploadPanelOpen = true;
  }
}

function toggleUploadPanel() {
  createUploadPanel();
}
function createUploadPanel() {
  const uploadContent = `
                   <div id="debugInfo" style="display: ${window.debug ? "block" : "none"}; margin-bottom: 10px; border: 1px dashed #999; padding: 8px;">
                       <div><strong>window.qin</strong>: <span id="qinvalue">n/a</span></div>
                       <label for="qinInput"><strong>window.qin</strong>: </label>
                       <input type="text" id="qinInput" style="width: 150px" placeholder="input-q1_1" />
                       <button onclick="setQinManual()">Set qin</button>
                   </div>
                   <div id="uploadArea" class="upload-area">
                       <p>Drag & drop files here or</p>
                       <input type="file" id="fileInput" multiple style="display: none" />
                       <button class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                           Select Files
                       </button>
                   </div>
                   <div id="fileList" class="file-list"></div>
                   <div class="upload-stats">
                       <div>Total files: <span id="totalFiles">0</span></div>
                       <div>Total size: <span id="totalSize">0 B</span></div>
                       <div>Uploaded: <span id="uploadedSize">0 B</span></div>
                   </div>
                   <div "uploadbtn" style="margin-top: 10px; display: flex; gap: 10px;">
                   <span class="status-indicator status-uploading" id="uploadStatus"></span>
                       <button class="btn" id="uploadBtn" onclick="startUpload()">Upload</button>
                       <button class="btn" onclick="clearFiles()">Cls</button>
                       <button class="btn" onclick="copyFromStringOutput()">Attach</button>


                   </div>
                   <div class="output-format" style="display: ${window.debug ? "block" : "none"};">
                       <h3>JSON Output:</h3>
                       <div id="jsonOutput"></div>
                       <h3>String Output:</h3>
                       <div id="stringOutput"></div>
                   </div>
               `;
  createPanel("uploadPanel", "CR", "rtl", 400, window.innerHeight, {
    noHeader: true,
    headerTitle: "Upload Files",
    bodyContent: uploadContent,
    bodyCloseButton: true,
    footerCloseBtn: true,
    noDrag: false,
    overflow: true,
    radius: "8px",
  });
  initDragAndDrop();
  updateFileList();
  updateStats();
  updateOutputFormats();
  addFooterButton("uploadPanel", "Upload", {
    className: "upload-footer-btn",
    onclick: function () {
      startUpload();
    },
  });

  addFooterButton("uploadPanel", "+Logo User", {
    className: "upload-footer-btn",
    onclick: function () {
      applyLogoToForm();
    },
  });
  addFooterButton("uploadPanel", "User Logo", {
    className: "upload-footer-btn",
    onclick: function () {
      loadCurrentUserImage();
    },
  });
  setContent("uploadPanel", "footer", "");
}
function initDragAndDrop() {
  const uploadArea = document.getElementById("uploadArea");
  const fileInput = document.getElementById("fileInput");
  if (!uploadArea || !fileInput) return;

  uploadArea.addEventListener("dragover", (e) => {
    e.preventDefault();
    uploadArea.classList.add("highlight");
  });

  uploadArea.addEventListener("dragleave", () => {
    uploadArea.classList.remove("highlight");
  });

  uploadArea.addEventListener("drop", (e) => {
    e.preventDefault();
    uploadArea.classList.remove("highlight");
    if (e.dataTransfer.files.length) {
      handleFiles(e.dataTransfer.files);
    }
  });

  fileInput.addEventListener("change", () => {
    if (fileInput.files.length) {
      handleFiles(fileInput.files);
    }
  });
}
function updateFileList() {
  const fileList = document.getElementById("fileList");
  if (!fileList) return;
  fileList.innerHTML = "";

  filesToUpload.forEach((file, index) => {
    const fileItem = document.createElement("div");
    fileItem.className = file.uploaded ? "file-item uploaded" : "file-item";
    fileItem.id = `file-${index}`;

    const previewContainer = document.createElement("div");
    previewContainer.className = "file-preview";

    const ext = file.name.split(".").pop().toLowerCase();
    const isImage = ["jpg", "jpeg", "png", "gif"].includes(ext);

    if (isImage) {
      const img = document.createElement("img");

      imgsrc = file.serverPath || URL.createObjectURL(file);
      window.imgsrc = imgsrc;
      console.log(`Image source: ${imgsrc}`);
      img.src = imgsrc;
      img.onerror = function () {
        previewContainer.textContent = "🖼️";
      };
      previewContainer.appendChild(img);
    } else {
      let icon = "📄";
      if (ext === "pdf") icon = "📕";
      else if (["doc", "docx"].includes(ext)) icon = "📝";
      else if (["xls", "xlsx"].includes(ext)) icon = "📊";
      else if (["ppt", "pptx"].includes(ext)) icon = "📑";
      else if (["mp4", "mov"].includes(ext)) icon = "🎥";
      else if (["zip", "rar", "7z"].includes(ext)) icon = "🗄️";
      previewContainer.textContent = icon;
    }

    const fileInfo = document.createElement("div");
    fileInfo.className = "file-info";
    fileInfo.innerHTML = `
                       <div class="file-name" title="${file.originalName || file.name}">${file.originalName || file.name}</div>
                       <div class="file-size">(${formatBytes(file.size)})</div>
                   `;

    const progressContainer = document.createElement("div");
    progressContainer.className = "file-progress";
    progressContainer.innerHTML = `<div class="progress-bar" id="progress-${index}"></div>`;

    const statusElement = document.createElement("div");
    statusElement.className = "file-status";
    statusElement.id = `status-${index}`;
    statusElement.textContent = file.uploaded ? "Available" : "Pending";

    const removeBtn = document.createElement("button");
    removeBtn.className = "remove-btn";
    removeBtn.innerHTML = "×";
    removeBtn.onclick = function (e) {
      e.stopPropagation();
      removeFile(index);
    };

    fileItem.appendChild(previewContainer);
    fileItem.appendChild(fileInfo);
    fileItem.appendChild(progressContainer);
    fileItem.appendChild(statusElement);
    fileItem.appendChild(removeBtn);

    fileItem.onclick = function () {
      previewFile(file);
    };

    fileList.appendChild(fileItem);
  });
}
function updateStats() {
  const totalFiles = filesToUpload.length;
  const pendingFiles = filesToUpload.filter((f) => !f.uploaded).length;
  const totalSize = filesToUpload.reduce((sum, file) => sum + file.size, 0);
  const uploadedSize = filesToUpload.reduce(
    (sum, file) => sum + (file.uploaded ? file.size : 0),
    0,
  );
  const percent = totalSize > 0 ? (uploadedSize / totalSize) * 100 : 0;

  const statsContainer = document.querySelector(".upload-stats");
  if (!statsContainer) return;

  document.getElementById("totalFiles").textContent =
    `${totalFiles} (${pendingFiles} pending)`;
  document.getElementById("totalSize").textContent = formatBytes(totalSize);
  document.getElementById("uploadedSize").textContent =
    formatBytes(uploadedSize);

  let progressText = document.getElementById("overallProgressText");
  if (!progressText) {
    progressText = document.createElement("div");
    progressText.id = "overallProgressText";
    progressText.style.marginTop = "8px";
    statsContainer.appendChild(progressText);
  }
  progressText.textContent = `Progress: ${formatBytes(uploadedSize)} of ${formatBytes(totalSize)} (${percent.toFixed(1)}%)`;

  let progressBar = document.getElementById("overallProgressBar");
  if (!progressBar) {
    progressBar = document.createElement("div");
    progressBar.id = "overallProgressBar";
    progressBar.style.height = "8px";
    progressBar.style.marginTop = "4px";
    progressBar.style.background = "#ddd";
    progressBar.style.borderRadius = "4px";
    progressBar.innerHTML = `<div id="overallProgressFill" style="width: 0%; height: 100%; background: #4CAF50; border-radius: 4px;"></div>`;
    statsContainer.appendChild(progressBar);
  }
  document.getElementById("overallProgressFill").style.width =
    `${percent.toFixed(1)}%`;

  const limitInfoIds = [
    "fileSizeLimitInfo",
    "fileCountLimitInfo",
    "totalSizeLimitInfo",
    "limitWarnings",
  ];
  const [fileSizeInfo, fileCountInfo, totalSizeInfo, limitWarnings] =
    limitInfoIds.map((id) => {
      let el = document.getElementById(id);
      if (!el) {
        el = document.createElement("div");
        el.id = id;
        if (id === "limitWarnings") {
          el.style.color = "red";
          el.style.fontWeight = "bold";
          el.style.marginTop = "8px";
        } else {
          el.style.fontSize = "12px";
          el.style.color = "#555";
        }
        statsContainer.appendChild(el);
      }
      return el;
    });

  fileSizeInfo.textContent = `Max file size: ${formatBytes(MAX_FILE_SIZE)}`;
  fileCountInfo.textContent = `Max file count: ${MAX_FILE_COUNT}`;
  totalSizeInfo.textContent = `Max total size: ${formatBytes(MAX_TOTAL_SIZE)}`;

  const oversized = filesToUpload.filter((f) => f.size > MAX_FILE_SIZE);
  const warnings = [];
  if (filesToUpload.length > MAX_FILE_COUNT) {
    warnings.push(
      `📦 ❌ Too many files: ${filesToUpload.length} > ${MAX_FILE_COUNT}`,
    );
  }
  if (totalSize > MAX_TOTAL_SIZE) {
    warnings.push(
      `🚫 ❌ Total size exceeded: ${formatBytes(totalSize)} > ${formatBytes(MAX_TOTAL_SIZE)}`,
    );
  }
  if (oversized.length > 0) {
    warnings.push(`🧱 ❌ ${oversized.length} file(s) exceed max file size`);
  }

  limitWarnings.innerHTML = warnings.length ? warnings.join("<br>") : "";

  const uploadBtn = document.getElementById("uploadBtn");
  if (warnings.length > 0) {
    uploadBtn.disabled = true;
    uploadBtn.style.opacity = 0.6;
    uploadBtn.title = "Fix file limit issues before uploading.";
  } else {
    uploadBtn.disabled = false;
    uploadBtn.style.opacity = 1;
    uploadBtn.title = "";
  }
  uploadBtn.textContent =
    pendingFiles > 0
      ? `🔴 Upload ${pendingFiles} Pending Files`
      : "🟢 Uploaded";
}
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}
function updateOutputFormats() {
  const jsonOutput = document.getElementById("jsonOutput");
  const stringOutput = document.getElementById("stringOutput");
  if (!jsonOutput || !stringOutput) return;

  const jsonArray = filesToUpload
    .filter((file) => file.uploaded)
    .map((file) => ({
      name: file.originalName || file.name,
      url: file.serverPath
        ? file.serverPath.replace(SERVER_BASE, "")
        : file.name,
      size: file.size,
    }));
  jsonOutput.innerHTML = JSON.stringify(jsonArray, null, 2)
    .replace(/\n/g, "<br>")
    .replace(/ /g, " ");
  const stringArray = filesToUpload
    .filter((file) => file.uploaded)
    .map(
      (file) => `${file.originalName || file.name} (${formatBytes(file.size)})`,
    );
  stringOutput.textContent = stringArray.join(", ");
  if (window.debug === true) {
    const outputFormat = document.querySelector(".output-format");
    if (outputFormat) outputFormat.style.display = "block";
  }
}

function sanitizeFilename(filename) {
  let sanitized = filename.trim();
  sanitized = sanitized.replace(/[<>:"/\\|?*]/g, "_");
  sanitized = sanitized.replace(/[\x00-\x1F\x7F]/g, "");
  sanitized = sanitized.replace(/^[.]+/, "");
  return sanitized || "unnamed_file";
}

function handleFiles(files) {
  let validFiles = [];
  let invalidFiles = [];
  let totalSize = filesToUpload.reduce((sum, file) => sum + file.size, 0);

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    if (
      filesToUpload.some((f) => f.name === file.name && f.size === file.size)
    ) {
      continue;
    }
    if (file.size > MAX_FILE_SIZE) {
      invalidFiles.push(file);
      continue;
    }
    if (totalSize + file.size > MAX_TOTAL_SIZE) {
      invalidFiles.push(file);
      continue;
    }
    file.sanitizedName = sanitizeFilename(file.name);
    file.originalName = file.name;
    validFiles.push(file);
    totalSize += file.size;
  }

  if (validFiles.length) {
    filesToUpload = [...filesToUpload, ...validFiles];
    updateFileList();
    updateStats();
  }

  if (invalidFiles.length) {
    showWarning(
      `Some files were not added because they exceed size limits (max ${formatBytes(MAX_FILE_SIZE)} per file, ${formatBytes(MAX_TOTAL_SIZE)} total).`,
    );
  }
}

function previewFile(file) {
  panelId = "previewDialog";
  createPanel(
    panelId,
    "CC",
    "ttb", // Slide from right
    window.innerWidth, // Width: 300px
    window.innerHeight, // Height: 400px
    {
      resizeAble: false,
      noFooter: true,
      bodyCloseButton: false,

      overflow: true,
    },
  );

  // Customize panel body for upload functionality
  const previewContent = document.querySelector(`#${panelId} .panel-body`);
  //if (panelBody)

  const previewDialog = document.getElementById("previewDialog");
  //const previewContent =
  document.getElementById("previewContent");
  const ext = file.name.split(".").pop().toLowerCase();

  if (file.serverPath && file.serverPath.includes("ERROR")) {
    showWarning("This file cannot be previewed due to an upload error");
    return;
  }

  const fileUrl = file.serverPath || URL.createObjectURL(file);

  // Clear previous content
  previewContent.innerHTML = "";
  // Style previewContent with backdrop filter

  // Create close button (positioned at screen top-right)

  // Create content container
  const contentContainer = document.createElement("div");
  contentContainer.style.position = "relative";
  //contentContainer.style.width = "100%";
  //contentContainer.style.height = "100%";

  // Add title
  const title = document.createElement("h3");
  title.textContent = file.originalName || file.name;
  title.style.marginTop = "0";
  title.className = "previewTitle";

  // Add preview content based on file type
  let previewElement;
  if (["jpg", "jpeg", "png", "gif"].includes(ext)) {
    previewElement = document.createElement("img");
    previewElement.src = fileUrl;
    previewElement.style.maxWidth = "100%";
    previewElement.style.maxHeight = "100%";
    previewElement.style.Height = "100%";
    previewElement.style.cursor = "zoom-in";
    previewElement.style.transition = "transform 0.25s ease"; // Add transition
    previewElement.classList.add("img-zoom-out");

    previewElement.onclick = function (e) {
      e.stopPropagation();
      if (this.classList.contains("img-zoom-out")) {
        this.style.width = "auto";
        this.style.height = "auto";
        this.style.maxWidth = "auto";
        this.style.maxHeight = "auto";
        this.style.objectFit = "contain";
        this.style.cursor = "zoom-out";
        this.style.transform = "scale(1)"; // Zoom 2x
        this.classList.remove("img-zoom-out");
        this.classList.add("img-zoom-in");
      } else {
        this.style.width = "none";
        this.style.height = "100%";
        this.style.maxWidth = "100%";
        this.style.maxHeight = "100%";

        //this.style.transform = "translate(-50%, 0%)";
        this.style.objectFit = "contain";

        this.style.transform = "scale(.8)"; // Reset zoom
        this.style.cursor = "zoom-in";
        this.classList.remove("img-zoom-in");
        this.classList.add("img-zoom-out");
      }
    };

    previewElement.onerror = function () {
      contentContainer.innerHTML = "<p>Unable to load preview</p>";
    };
  } else if (ext === "txt" && !file.serverPath) {
    const reader = new FileReader();
    reader.onload = function (e) {
      const pre = document.createElement("pre");
      pre.style.margin = "0";
      pre.style.fontFamily = "Arial";
      pre.textContent = e.target.result;
      contentContainer.appendChild(pre);
    };
    reader.readAsText(file);
  } else if (["xls", "xlsx", "doc", "docx", "ppt", "pptx"].includes(ext)) {
    previewElement = document.createElement("iframe");
    previewElement.src = `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}`;
    previewElement.style.width = "80vw";
    previewElement.style.height = "80vh";
    previewElement.style.border = "none";
  } else if (ext === "pdf") {
    previewElement = document.createElement("iframe");
    previewElement.src = fileUrl;
    previewElement.style.width = "80vw";
    previewElement.style.height = "80vh";
    previewElement.style.border = "none";
  } else if (ext === "mp4" || ext === "mov") {
    previewElement = document.createElement("video");
    previewElement.controls = true;
    previewElement.style.maxWidth = "100%";
    previewElement.style.maxHeight = "80vh";
    const source = document.createElement("source");
    source.src = fileUrl;
    source.type = "video/mp4";
    previewElement.appendChild(source);
  } else {
    previewElement = document.createElement("p");
    previewElement.innerHTML = `Preview not available. <a href="${fileUrl}" target="_blank">Open file</a>`;
  }

  // Assemble the content

  setContent("previewDialog", "header", file.originalName || file.name);

  if (previewElement) {
    previewContent.appendChild(previewElement);
  }
  //previewContent.appendChild(contentContainer);
  addStyle(`
                  #previewDialog .panel-body {
                      display: flex;
                      justify-content: center; /* Horizontally center */
                      align-items: center;     /* Vertically center */
                      flex-direction: column;  /* Stack child elements vertically */
                      padding: 20px;
                      box-sizing: border-box;
                      overflow: auto;
                      position: relative; /* Ensure that absolutely positioned elements are relative to this container */
                  }
                  /* Styles for the content container */
                  #previewDialog .content-container {
                      max-width: 90%;
                      width: 800px; /* Adjust as needed */
                      /* Optional: Add a background or border for better visibility */
                      background-color: rgba(255, 255, 255, 0.9);
                      padding: 20px;
                      border-radius: 8px;
                      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                  }

                  `);
}
function ZZpreviewFile(file) {
  const ext = file.name.split(".").pop().toLowerCase();
  if (file.serverPath && file.serverPath.includes("ERROR")) {
    showWarning("This file cannot be previewed due to an upload error");
    return;
  }

  const fileUrl = file.serverPath || URL.createObjectURL(file);
  let previewContent = `
                   <h3 class="preview-title">${file.originalName || file.name}</h3>
                   <div class="preview-content">
               `;

  if (["jpg", "jpeg", "png", "gif"].includes(ext)) {
    previewContent += `
                       <img src="${fileUrl}" style="max-width: 100%; max-height: 100%; cursor: zoom-in; transition: transform 0.25s ease;" class="img-zoom-out" onclick="this.classList.toggle('img-zoom-out'); this.classList.toggle('img-zoom-in'); this.style.transform = this.classList.contains('img-zoom-in') ? 'scale(1)' : 'scale(1.5)'; this.style.cursor = this.classList.contains('img-zoom-in') ? 'zoom-out' : 'zoom-in';">
                   `;
  } else if (ext === "txt" && !file.serverPath) {
    const reader = new FileReader();
    reader.onload = function (e) {
      setContent(
        "previewPanel",
        "body",
        `<h3 class="preview-title">${file.originalName || file.name}</h3><div class="preview-content"><pre style="margin: 0; font-family: Arial;">${e.target.result}</pre></div>`,
      );
    };
    reader.readAsText(file);
    previewContent += `<pre style="margin: 0; font-family: Arial;">Loading...</pre>`;
  } else if (["xls", "xlsx", "doc", "docx", "ppt", "pptx"].includes(ext)) {
    previewContent += `<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}" style="width: 80vw; height: 80vh; border: none;"></iframe>`;
  } else if (ext === "pdf") {
    previewContent += `<iframe src="${fileUrl}" style="width: 80vw; height: 80vh; border: none;"></iframe>`;
  } else if (ext === "mp4" || ext === "mov") {
    previewContent += `
                       <video controls style="max-width: 100%; max-height: 80vh;">
                           <source src="${fileUrl}" type="video/mp4">
                       </video>
                   `;
  } else {
    previewContent += `<p>Preview not available. <a href="${fileUrl}" target="_blank">Open file</a></p>`;
  }

  previewContent += `</div>`;

  createPanel(
    "previewPanel",
    "CC",
    "ctc",
    (80 * window.innerWidth) / 100,
    (80 * window.innerHeight) / 100,
    {
      noHeader: true,
      bodyContent: previewContent,
      bodyCloseButton: true,
      noDrag: false,
      overflow: true,
      radius: "8px",
    },
  );

  document.addEventListener("keydown", function handleKeyDown(e) {
    if (e.key === "Escape") {
      closePanel("previewPanel");
      document.removeEventListener("keydown", handleKeyDown);
    }
  });
}

function removeFile(index) {
  if (currentUploads[index]) {
    currentUploads[index].abort();
  }
  filesToUpload.splice(index, 1);
  currentUploads.splice(index, 1);
  updateFileList();
  updateStats();
  updateOutputFormats();
}

function clearFiles() {
  currentUploads.forEach((upload) => {
    if (upload) upload.abort();
  });
  filesToUpload = [];
  currentUploads = [];
  updateFileList();
  updateStats();
  updateOutputFormats();
}

function updateStats() {
  const totalFiles = filesToUpload.length;
  const pendingFiles = filesToUpload.filter((f) => !f.uploaded).length;
  const totalSize = filesToUpload.reduce((sum, file) => sum + file.size, 0);
  const uploadedSize = filesToUpload.reduce(
    (sum, file) => sum + (file.uploaded ? file.size : 0),
    0,
  );
  const percent = totalSize > 0 ? (uploadedSize / totalSize) * 100 : 0;

  const statsContainer = document.querySelector(".upload-stats");
  if (!statsContainer) return;

  document.getElementById("totalFiles").textContent =
    `${totalFiles} (${pendingFiles} pending)`;
  document.getElementById("totalSize").textContent = formatBytes(totalSize);
  document.getElementById("uploadedSize").textContent =
    formatBytes(uploadedSize);

  let progressText = document.getElementById("overallProgressText");
  if (!progressText) {
    progressText = document.createElement("div");
    progressText.id = "overallProgressText";
    progressText.style.marginTop = "8px";
    statsContainer.appendChild(progressText);
  }
  progressText.textContent = `Progress: ${formatBytes(uploadedSize)} of ${formatBytes(totalSize)} (${percent.toFixed(1)}%)`;

  let progressBar = document.getElementById("overallProgressBar");
  if (!progressBar) {
    progressBar = document.createElement("div");
    progressBar.id = "overallProgressBar";
    progressBar.style.height = "8px";
    progressBar.style.marginTop = "4px";
    progressBar.style.background = "#ddd";
    progressBar.style.borderRadius = "4px";
    progressBar.innerHTML = `<div id="overallProgressFill" style="width: 0%; height: 100%; background: #4CAF50; border-radius: 4px;"></div>`;
    statsContainer.appendChild(progressBar);
  }
  document.getElementById("overallProgressFill").style.width =
    `${percent.toFixed(1)}%`;

  const limitInfoIds = [
    "fileSizeLimitInfo",
    "fileCountLimitInfo",
    "totalSizeLimitInfo",
    "limitWarnings",
  ];
  const [fileSizeInfo, fileCountInfo, totalSizeInfo, limitWarnings] =
    limitInfoIds.map((id) => {
      let el = document.getElementById(id);
      if (!el) {
        el = document.createElement("div");
        el.id = id;
        if (id === "limitWarnings") {
          el.style.color = "red";
          el.style.fontWeight = "bold";
          el.style.marginTop = "8px";
        } else {
          el.style.fontSize = "12px";
          el.style.color = "#555";
        }
        statsContainer.appendChild(el);
      }
      return el;
    });

  fileSizeInfo.textContent = `Max file size: ${formatBytes(MAX_FILE_SIZE)}`;
  fileCountInfo.textContent = `Max file count: ${MAX_FILE_COUNT}`;
  totalSizeInfo.textContent = `Max total size: ${formatBytes(MAX_TOTAL_SIZE)}`;

  const oversized = filesToUpload.filter((f) => f.size > MAX_FILE_SIZE);
  const warnings = [];
  if (filesToUpload.length > MAX_FILE_COUNT) {
    warnings.push(
      `📦 ❌ Too many files: ${filesToUpload.length} > ${MAX_FILE_COUNT}`,
    );
  }
  if (totalSize > MAX_TOTAL_SIZE) {
    warnings.push(
      `🚫 ❌ Total size exceeded: ${formatBytes(totalSize)} > ${formatBytes(MAX_TOTAL_SIZE)}`,
    );
  }
  if (oversized.length > 0) {
    warnings.push(`🧱 ❌ ${oversized.length} file(s) exceed max file size`);
  }

  limitWarnings.innerHTML = warnings.length ? warnings.join("<br>") : "";

  const uploadBtn = document.getElementById("uploadBtn");
  if (warnings.length > 0) {
    uploadBtn.disabled = true;
    uploadBtn.style.opacity = 0.6;
    uploadBtn.title = "Fix file limit issues before uploading.";
  } else {
    uploadBtn.disabled = false;
    uploadBtn.style.opacity = 1;
    uploadBtn.title = "";
  }
  uploadBtn.textContent =
    pendingFiles > 0
      ? `🔴 Upload ${pendingFiles} Pending Files`
      : "🟢 Uploaded";
}

function updateOutputFormats() {
  const jsonOutput = document.getElementById("jsonOutput");
  const stringOutput = document.getElementById("stringOutput");
  if (!jsonOutput || !stringOutput) return;

  const jsonArray = filesToUpload
    .filter((file) => file.uploaded)
    .map((file) => ({
      name: file.originalName || file.name,
      url: file.serverPath
        ? file.serverPath.replace(SERVER_BASE, "")
        : file.name,
      size: file.size,
    }));
  jsonOutput.innerHTML = JSON.stringify(jsonArray, null, 2)
    .replace(/\n/g, "<br>")
    .replace(/ /g, " ");
  const stringArray = filesToUpload
    .filter((file) => file.uploaded)
    .map(
      (file) => `${file.originalName || file.name} (${formatBytes(file.size)})`,
    );
  stringOutput.textContent = stringArray.join(", ");
  if (window.debug === true) {
    const outputFormat = document.querySelector(".output-format");
    if (outputFormat) outputFormat.style.display = "block";
  }
}

function startUpload() {
  const pendingFiles = filesToUpload
    .map((file, index) => ({ file, originalIndex: index }))
    .filter(({ file }) => !file.uploaded);
  if (pendingFiles.length === 0) {
    showWarning("All files have already been uploaded");
    const statusIndicator = document.getElementById("uploadStatus");
    statusIndicator.className = "status-indicator status-success";
    return;
  }
  const statusIndicator = document.getElementById("uploadStatus");
  statusIndicator.className = "status-indicator status-uploading";
  statusIndicator.style.display = "block";
  const uploadBtn = document.getElementById("uploadBtn");
  uploadBtn.disabled = true;
  uploadBtn.textContent = `Uploading ${pendingFiles.length} files...`;
  currentUploads = new Array(filesToUpload.length).fill(null);

  uploadFilesSequentially(pendingFiles, 0);
}

function uploadFilesSequentially(filesWithIndexes, currentPosition) {
  if (currentPosition >= filesWithIndexes.length) {
    const uploadBtn = document.getElementById("uploadBtn");
    uploadBtn.textContent = "🟢Upload Complete ✓ ";
    const statusIndicator = document.getElementById("uploadStatus");
    statusIndicator.className = "status-indicator status-success";
    setTimeout(() => {
      uploadBtn.textContent = "Upload All";
      uploadBtn.disabled = false;
      statusIndicator.style.display = "none";
    }, 3000);
    return Promise.resolve();
  }

  const { file, originalIndex } = filesWithIndexes[currentPosition];
  const statusElement = document.getElementById(`status-${originalIndex}`);
  const progressBar = document.getElementById(`progress-${originalIndex}`);

  return new Promise((resolve, reject) => {
    statusElement.textContent = "Uploading";
    statusElement.style.color = "#2196F3";

    const formData = new FormData();
    formData.append("fileUpload", file);
    formData.append(
      "filename",
      encodeURIComponent(file.sanitizedName || file.name),
    );
    formData.append("folder", "y225e1");
    formData.append("foldergroup", "project1");
    formData.append("folderuser", "user1");

    const xhr = new XMLHttpRequest();
    currentUploads[originalIndex] = xhr;

    xhr.upload.addEventListener("progress", (e) => {
      if (e.lengthComputable) {
        const percent = Math.round((e.loaded / e.total) * 100);
        progressBar.style.width = `${percent}%`;
        updateStats();
      }
    });

    xhr.addEventListener("load", () => {
      if (xhr.status === 200) {
        statusElement.textContent = "Done";
        statusElement.style.color = "#4CAF50";
        progressBar.style.backgroundColor = "#4CAF50";

        let filePath = xhr.responseText.trim();
        if (!filePath.startsWith("http") && !filePath.startsWith("/")) {
          filePath = `${SERVER_BASE}${encodeURIComponent(file.sanitizedName || file.name)}`;
        }

        filesToUpload[originalIndex].serverPath = filePath;
        filesToUpload[originalIndex].uploaded = true;
        updateStats();
        updateFileList();
        updateOutputFormats();
        uploadFilesSequentially(filesWithIndexes, currentPosition + 1)
          .then(resolve)
          .catch(reject);
      } else {
        statusElement.textContent = "Error";
        statusElement.style.color = "#f44336";
        progressBar.style.backgroundColor = "#f44336";
        showWarning(`Upload failed for ${file.originalName || file.name}`);
        reject(new Error(`Upload failed for ${file.name}`));
      }
    });

    xhr.addEventListener("error", () => {
      statusElement.textContent = "Error";
      statusElement.style.color = "#f44336";
      progressBar.style.backgroundColor = "#f44336";
      showWarning(`Upload error for ${file.originalName || file.name}`);
      reject(new Error(`Upload error for ${file.name}`));
    });

    xhr.addEventListener("abort", () => {
      statusElement.textContent = "Cancelled";
      statusElement.style.color = "#FF9800";
      progressBar.style.backgroundColor = "#FF9800";
    });

    xhr.open("POST", "https://q.kunok.com/s9/upg.php", true);
    xhr.send(formData);
  });
}
function updateFileListFromInput(inputText = null, skipExisting = true) {
  const inputElement = document.getElementById(inputText);
  const fileListElement = document.getElementById("fileList");

  // Get the value from the input element
  const value =
    inputText !== null
      ? document.getElementById(inputText).value
      : inputElement.value;

  window.qin = inputText;

  const qinDisplay = document.getElementById("qinvalue");
  if (qinDisplay) qinDisplay.textContent = window.qin;
  console.log(value);

  // Split the input into file entries
  const fileEntries = value.split(", ").filter((entry) => entry.trim());

  // If not skipping existing, reset the filesToUpload and currentUploads
  if (!skipExisting) {
    filesToUpload = [];
    currentUploads = [];
  }

  // Create a set of new file entries for quick lookup
  const newFileSet = new Set(
    fileEntries.map((entry) => {
      const match = entry.match(/^(.*?)\s*\(([\d.,]+)\s*([KMGT]?B)\)$/i);
      const name = match ? match[1].trim() : entry;
      const size = match
        ? parseFloat(match[2].replace(",", "")) *
          (match[3].toUpperCase() === "KB"
            ? 1024
            : match[3].toUpperCase() === "MB"
              ? 1024 * 1024
              : match[3].toUpperCase() === "GB"
                ? 1024 * 1024 * 1024
                : 1)
        : 0;
      return `${name}_${size}`;
    }),
  );

  // Identify files to remove
  const filesToRemove = filesToUpload.filter((file) => {
    return !newFileSet.has(`${file.originalName}_${file.size}`);
  });

  // Remove the identified files from filesToUpload
  filesToRemove.forEach((file) => {
    const index = filesToUpload.indexOf(file);
    if (index > -1) {
      filesToUpload.splice(index, 1);
    }
  });

  // Update the file list in the DOM
  if (fileListElement) fileListElement.innerHTML = "";

  const existingFiles = filesToUpload.map((f) => `${f.originalName}_${f.size}`);

  fileEntries.forEach((entry) => {
    const match = entry.match(/^(.*?)\s*\(([\d.,]+)\s*([KMGT]?B)\)$/i);
    const name = match ? match[1].trim() : entry;
    const size = match
      ? parseFloat(match[2].replace(",", "")) *
        (match[3].toUpperCase() === "KB"
          ? 1024
          : match[3].toUpperCase() === "MB"
            ? 1024 * 1024
            : match[3].toUpperCase() === "GB"
              ? 1024 * 1024 * 1024
              : 1)
      : 0;

    const alreadyExists = existingFiles.includes(`${name}_${size}`);

    if (skipExisting && alreadyExists) {
      const file = filesToUpload.find(
        (f) => f.originalName === name && f.size === size,
      );
      if (file) updateFileList(file, fileListElement);
      return;
    }

    const ext = name.split(".").pop().toLowerCase();
    const isImage = ["jpg", "jpeg", "png", "gif"].includes(ext);
    const sanitizedName = sanitizeFilename(name);
    const file = {
      name: sanitizedName,
      originalName: name,
      size: size,
      type: isImage ? `image/${ext}` : ext === "pdf" ? "application/pdf" : "",
      serverPath: `${SERVER_BASE}${encodeURIComponent(sanitizedName)}`,
      uploaded: true,
      index: filesToUpload.length,
    };

    filesToUpload.push(file);

    // Create the file item as before
    const fileItem = document.createElement("div");
    fileItem.className = "file-item uploaded";
    fileItem.id = `file-${file.index}`;

    const previewContainer = document.createElement("div");
    previewContainer.className = "file-preview";

    if (isImage) {
      const img = document.createElement("img");
      img.src = file.serverPath;
      img.onerror = () => {
        previewContainer.textContent = "🖼️";
      };
      previewContainer.appendChild(img);
    } else {
      let icon = "📄";
      if (ext === "pdf") icon = "📕";
      else if (["doc", "docx"].includes(ext)) icon = "📝";
      else if (["xls", "xlsx"].includes(ext)) icon = "📊";
      else if (["ppt", "pptx"].includes(ext)) icon = "📑";
      else if (["mp4", "mov"].includes(ext)) icon = "🎥";
      else if (["zip", "rar", "7z"].includes(ext)) icon = "🗄️";
      previewContainer.textContent = icon;
    }

    const fileInfo = document.createElement("div");
    fileInfo.className = "file-info";
    fileInfo.innerHTML = `
<div class="file-name" title="${name}">${name}</div>
<div class="file-size">(${formatBytes(size)})</div>
`;

    const progressContainer = document.createElement("div");
    progressContainer.className = "file-progress";
    progressContainer.innerHTML = `<div class="progress-bar" id="progress-${file.index}"></div>`;

    const statusElement = document.createElement("div");
    statusElement.className = "file-status";
    statusElement.id = `status-${file.index}`;
    statusElement.textContent = "Available";
    statusElement.style.color = "#4CAF50";

    const removeBtn = document.createElement("button");
    removeBtn.className = "remove-btn";
    removeBtn.innerHTML = "×";
    removeBtn.onclick = (e) => {
      e.stopPropagation();
      removeFile(file.index);
    };

    fileItem.appendChild(previewContainer);
    fileItem.appendChild(fileInfo);
    fileItem.appendChild(progressContainer);
    fileItem.appendChild(statusElement);
    fileItem.appendChild(removeBtn);

    fileItem.onclick = () => {
      previewFile(file);
    };

    fileListElement.appendChild(fileItem);
  });

  // Remove the files that are no longer in the input
  filesToRemove.forEach((file) => {
    const fileItem = document.getElementById(`file-${file.index}`);
    if (fileItem) {
      fileItem.remove();
    }
  });

  updateStats();
  updateOutputFormats();
}
function AAupdateFileListFromInput(inputText = null, skipExisting = true) {
  const inputElement = document.getElementById(inputText);

  const fileListElement = document.getElementById("fileList");

  const value =
    inputText !== null
      ? document.getElementById(inputText).value
      : inputElement.value;
  window.qin = inputText;

  const qinDisplay = document.getElementById("qinvalue");
  if (qinDisplay) qinDisplay.textContent = window.qin;
  console.log(value);

  //return;
  const fileEntries = value.split(", ").filter((entry) => entry.trim());
  if (!skipExisting) {
    filesToUpload = [];
    currentUploads = [];
  }
  fileListElement.innerHTML = "";

  const existingFiles = filesToUpload.map((f) => `${f.originalName}_${f.size}`);

  fileEntries.forEach((entry) => {
    const match = entry.match(/^(.*?)\s*\(([\d.,]+)\s*([KMGT]?B)\)$/i);
    const name = match ? match[1].trim() : entry;
    const size = match
      ? parseFloat(match[2].replace(",", "")) *
        (match[3] === "KB"
          ? 1024
          : match[3] === "MB"
            ? 1024 * 1024
            : match[3] === "GB"
              ? 1024 * 1024 * 1024
              : 1)
      : 0;

    const alreadyExists = existingFiles.includes(`${name}_${size}`);

    if (skipExisting && alreadyExists) {
      const file = filesToUpload.find(
        (f) => f.originalName === name && f.size === size,
      );
      if (file) updateFileList(file, fileListElement);
      return;
    }

    const ext = name.split(".").pop().toLowerCase();
    const isImage = ["jpg", "jpeg", "png", "gif"].includes(ext);
    const sanitizedName = sanitizeFilename(name);
    const file = {
      name: sanitizedName,
      originalName: name,
      size: size,
      type: isImage ? `image/${ext}` : ext === "pdf" ? "application/pdf" : "",
      serverPath: `${SERVER_BASE}${encodeURIComponent(sanitizedName)}`,
      uploaded: true,
      index: filesToUpload.length,
    };

    filesToUpload.push(file);

    const fileItem = document.createElement("div");
    fileItem.className = "file-item uploaded";
    fileItem.id = `file-${file.index}`;

    const previewContainer = document.createElement("div");
    previewContainer.className = "file-preview";

    if (isImage) {
      const img = document.createElement("img");
      img.src = file.serverPath;
      img.onerror = () => {
        previewContainer.textContent = "🖼️";
      };
      previewContainer.appendChild(img);
    } else {
      let icon = "📄";
      if (ext === "pdf") icon = "📕";
      else if (["doc", "docx"].includes(ext)) icon = "📝";
      else if (["xls", "xlsx"].includes(ext)) icon = "📊";
      else if (["ppt", "pptx"].includes(ext)) icon = "📑";
      else if (["mp4", "mov"].includes(ext)) icon = "🎥";
      else if (["zip", "rar", "7z"].includes(ext)) icon = "🗄️";
      previewContainer.textContent = icon;
    }

    const fileInfo = document.createElement("div");
    fileInfo.className = "file-info";
    fileInfo.innerHTML = `
                       <div class="file-name" title="${name}">${name}</div>
                       <div class="file-size">(${formatBytes(size)})</div>
                   `;

    const progressContainer = document.createElement("div");
    progressContainer.className = "file-progress";
    progressContainer.innerHTML = `<div class="progress-bar" id="progress-${file.index}"></div>`;

    const statusElement = document.createElement("div");
    statusElement.className = "file-status";
    statusElement.id = `status-${file.index}`;
    statusElement.textContent = "Available";
    statusElement.style.color = "#4CAF50";

    const removeBtn = document.createElement("button");
    removeBtn.className = "remove-btn";
    removeBtn.innerHTML = "×";
    removeBtn.onclick = (e) => {
      e.stopPropagation();
      removeFile(file.index);
    };

    fileItem.appendChild(previewContainer);
    fileItem.appendChild(fileInfo);
    fileItem.appendChild(progressContainer);
    fileItem.appendChild(statusElement);
    fileItem.appendChild(removeBtn);

    fileItem.onclick = () => {
      previewFile(file);
    };

    fileListElement.appendChild(fileItem);
  });

  updateStats();
  updateOutputFormats();
}

function copyFromStringOutput() {
  const stringText = document.getElementById("stringOutput").textContent.trim();
  const sendback = window.qin || "input-q1_1";
  const targetInput = document.getElementById(sendback);
  if (targetInput) {
    //add new auto pushing
    targetInput.value = stringText;

    //
    updateFileListFromInput(sendback, false);
    showWarning(`Input element with ID ${sendback}  found.`);
  } else {
    showWarning(`Input element with ID ${sendback} not found.`);
  }
}

function setQinManual() {
  const input = document.getElementById("qinInput");
  const val = input.value.trim();
  if (val && document.getElementById(val)) {
    window.qin = val;
    showWarning(`window.qin is now set to: ${window.qin}`);
  } else {
    showWarning("Invalid input ID!");
  }
}

function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}

function showWarning(
  message,
  backgroundColor = "rgba(255, 87, 51, 0.9)",
  textColor = "white",
) {
  // Update the CSS variable for the toast
  const root = document.documentElement;
  root.style.setProperty("--toast-background-color", backgroundColor);
  root.style.setProperty("--toast-text-color", textColor);

  createPanel("⚠️ warningToast", "BC", "btt", 320, 100, {
    toast: true,
    bodyContent: `<div style="padding: 10px;">⚠️ ${message}</div>`,
    timeClose: 3000,
  });
  addStyle(`/* Toast Panel Styles */
.panel.toast {
position: fixed;
bottom: 20px;
right: 20px;
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 10px 20px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
z-index: 1000;
animation: fadeInOut 3s forwards;
font-size: 16px;
border: 1px solid #ff0000;
}

@keyframes fadeInOut {
0% { opacity: 0; transform: translateY(20px); }
10% { opacity: 1; transform: translateY(0); }
90% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(20px); }
}`);
}

// Initialize the application
document.addEventListener("DOMContentLoaded", () => {
  if (window.debug === true) {
    const outputFormat = document.querySelector(".output-format");
    if (outputFormat) outputFormat.style.display = "block";
    if (window.qin) {
      const qinInput = document.getElementById("qinInput");
      if (qinInput) qinInput.value = window.qin;
    }
  }
});

addStyle(`
             .upload-area {
        border: 2px dashed #aaa;
        border-radius: 8px;
        padding: 10px;
        text-align: center;
        margin-bottom: 10px;
        background-color: rgba(255, 255, 255, 0.5);
        transition: all 0.3s;
    }
    .upload-area.highlight {
        border-color: #4caf50;
        background-color: rgba(76, 175, 80, 0.1);
    }
    .upload-area p {
        margin: 10px 0;
        color: #666;
    }
    .file-list {
        margin-top: 20px;
    }
    .file-item {
        display: flex;
        align-items: center;
        padding:1px 8px;
        background-color: white;
        border-radius: 6px;
        margin-bottom: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        cursor: pointer;
    }
    .file-item.uploaded {
        opacity: 0.7;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    .file-preview {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        overflow: hidden;
        flex-shrink: 0;
    }
    .file-preview img {
        max-width: 100%;
        max-height: 100%;
        object-fit: cover;
    }
    .file-info {
        flex: 1;
        min-width: 0;
        display: flex;
        align-items: center;
    }
    .file-name {
        //font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 5px;
    }
    .file-size {
        font-size: 12px;
        color: #777;
        white-space: nowrap;
    }
    .file-progress {
        width: 10%;
        height: 4px;
        background-color: #eee;
        border-radius: 2px;
        margin-top: 5px;
        margin-left: 15px;
        overflow: hidden;
    }
    .progress-bar {
        height: 100%;
        background-color:rgb(67, 191, 71);
        width: 0%;
        transition: width 0.3s;
    }
    .file-status {
        margin-left: 10px;
        font-size: 12px;
        min-width: 60px;
        text-align: right;
    }
    .remove-btn {
        background: none;
        border: none;
        color: #ff5252;
        cursor: pointer;
        font-size: 15px;
    }
    .btn {
        padding: 4px 8px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        //font-weight: bold;
        transition: background-color 0.3s;
    }

    .upload-stats {
        margin-top: 20px;
        padding: 10px;
        background-color: white;
        border-radius: 6px;
        font-size: 14px;
    }
    .output-format {
        margin-top: 20px;
        padding: 10px;
        background-color: #f9f9f9;
        border-radius: 6px;
        font-family: monospace;
        white-space: pre-wrap;
        word-wrap: break-word;
        display: none;
    }
    .preview-content {
        max-width: 95%;
        max-height: 95%;
        overflow: auto;
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-shadow: 0 8px 32px 0 rgba(31, 38, 35, 0.87);
        border-radius: 8px;
        padding: 10px;
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
    }
    .preview-title {
        margin-top: 0;
        padding: 5px 10px;
        background-color: rgba(250, 250, 250, 0.2);
        border-radius: 8px;
        backdrop-filter: blur(20px);
    }
    .img-zoom-in {
        transform: scale(1);
        transition: transform 0.3s ease;
        cursor: zoom-out;
    }
    .img-zoom-out {
        transform: scale(1.5);
        transition: transform 0.3s ease;
        cursor: zoom-in;
    }
    @media (max-width: 500px) {
        .panel.upload-panel {
            width: 100%;
        }
    }
    #form-container {
    overflow:auto;
height:400px;
    }
#uploadbtn {
    height: 36px; /* Fixed height */
    display: flex;
    align-items: center;
    gap: 8px;
}

#uploadbtn .btn {
    border: none;
    padding: 4px 8px;
    transition: background-color 0.2s;
}

#uploadbtn .btn:hover {
    background-color: rgba(0,0,0,0.1);
}
             `);
function applyLogoToForm() {
  if (filesToUpload.length > 0 && filesToUpload[0].serverPath) {
    const stringText = filesToUpload[0].serverPath;
    window.imgsrc = stringText;

    const addImgInput = document.getElementById("addImg");
    const updateImgInput = document.getElementById("updateImg");

    const targetInput = addImgInput || updateImgInput;
    const previewDiv =
      document.getElementById("addImgPreview") ||
      document.getElementById("updateImgPreview");

    if (targetInput) {
      targetInput.value = stringText;
    }
    if (previewDiv) {
      previewDiv.innerHTML = `<img src="${stringText}" alt="preview">`;
    }

    showWarning("Logo applied to user form from upload panel");
  } else if (typeof window.imgsrc !== "undefined") {
    const addImgInput = document.getElementById("addImg");
    const updateImgInput = document.getElementById("updateImg");

    const targetInput = addImgInput || updateImgInput;
    const previewDiv =
      document.getElementById("addImgPreview") ||
      document.getElementById("updateImgPreview");

    if (targetInput) {
      targetInput.value = window.imgsrc;
    }
    if (previewDiv) {
      previewDiv.innerHTML = `<img src="${window.imgsrc}" alt="preview">`;
    }

    showWarning("Logo applied to user form");
  } else {
    showWarning("No image available to apply");
  }
}

function applyLogoToFormORG() {
  // If we have files in upload panel, use the first image
  if (filesToUpload.length > 0 && filesToUpload[0].serverPath) {
    const stringText = filesToUpload[0].serverPath;
    window.imgsrc = stringText; // Update global reference
    const updateImgInput = document.getElementById("updateImg");
    if (updateImgInput) {
      updateImgInput.value = stringText;
      const previewDiv = document.getElementById("updateImgPreview");
      if (previewDiv) {
        previewDiv.innerHTML = `<img src="${stringText}" alt="preview">`;
      }
      showWarning("Logo applied to user form from upload panel");
    }
  }
  // Fallback to existing imgsrc if no files in panel
  else if (typeof window.imgsrc !== "undefined") {
    const updateImgInput = document.getElementById("updateImg");
    if (updateImgInput) {
      updateImgInput.value = window.imgsrc;
      const previewDiv = document.getElementById("updateImgPreview");
      if (previewDiv) {
        previewDiv.innerHTML = `<img src="${window.imgsrc}" alt="preview">`;
      }
      showWarning("Logo applied to user form");
    }
  } else {
    showWarning("No image available to apply");
  }
}
function loadCurrentUserImage() {
  const updateImgInput = document.getElementById("updateImg");
  if (!updateImgInput || !updateImgInput.value) {
    showWarning("No image URL found in user form");
    return;
  }

  const imgUrl = updateImgInput.value;
  const fileName = imgUrl.split("/").pop() || "user-image.jpg";
  const fileSize = 0; // Unknown size for external URLs

  // Create a file object for the existing image
  const file = {
    name: fileName,
    originalName: fileName,
    size: fileSize,
    type: "image/" + (fileName.split(".").pop() || "jpg"),
    serverPath: imgUrl,
    uploaded: true,
    index: filesToUpload.length,
  };

  // Add to files list
  filesToUpload.push(file);
  updateFileList();
  updateStats();
  updateOutputFormats();

  showWarning("Current user image loaded to upload panel");
}
