// ====== إعدادات عامة ======
const H2C_SCALE = 2;
const PX2PT_GENERAL = 1.35;
const PX2PT_DATE = 1.35;
const DATE_Y_FACTOR = 1;
const DATE_X_MARGIN = 2;
const FONT_PATH = "fonts/NotoSansArabic-Regular.ttf";

const GLOBAL_Y_FIX = 15;
const GLOBAL_X_FIX = -15;

const TEXT_SELECTORS_P1 = [
  "#workerNameLabel",
  "#workerName",
  "#receiverNumber",
  "#providerNumber",
  "#workerJobLabel",
  "#workerSectionTitle",
  "#providerSectionTitle",
  "#receiverSectionTitle",
  "#permitSectionTitle",
  "#workerJob",
  "#workerNationalityLabel",
  "#workerNationality",
  "#providerNameLabel",
  "#providerName",
  "#providerNumberLabel",
  "#receiverNameLabel",
  "#receiverName",
  "#contractSummaryLabel",
  "#contractSummary",
  "#workLocationLabel",
  "#workLocation",
  "#decTitle",
  "#decIntro",
  "#decItem1",
  "#decItem2",
  "#decItem3",
  "#decItem4",
  "#decItem5",
  "#verifyLine",
  "#footerNote",
  "#workerIdLabel",
  "#workerId",
  "#receiverNumberLabel",
  "#permitStartLabel",
  "#permitEndLabel",
  "#permitStart",
  "#permitEnd",
];

const CENTER_FIELDS = [
  "#workerSectionTitle",
  "#providerSectionTitle",
  "#receiverSectionTitle",
  "#permitSectionTitle",
  "#decTitle",
];

function toPt(px, px2pt) {
  return px * H2C_SCALE * px2pt;
}

function abToBase64(buf) {
  let s = "",
    b = new Uint8Array(buf);
  for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);
  return btoa(s);
}

async function embedArabicFont(doc) {
  try {
    const ab = await (await fetch(FONT_PATH)).arrayBuffer();
    doc.addFileToVFS("NotoSansArabic-Regular.ttf", abToBase64(ab));
    doc.addFont("NotoSansArabic-Regular.ttf", "NotoSansArabic", "normal");
    doc.setFont("NotoSansArabic", "normal");
  } catch (e) {
    console.warn("تعذّر تضمين الخط:", e);
  }
}

function rectInPage(el, pageEl) {
  const e = el.getBoundingClientRect();
  const p = pageEl.getBoundingClientRect();
  return {
    x: e.left - p.left,
    y: e.top - p.top,
    w: e.width,
    h: e.height,
  };
}

function isRightAligned(el) {
  const cs = getComputedStyle(el);
  return cs.direction === "rtl" || cs.textAlign === "right";
}

function setInvisibleText(doc) {
  try {
    const gs = new doc.GState({ opacity: 0 });
    doc.setGState(gs);
  } catch {
    doc.setTextColor(255, 255, 255);
  }
}

function isDateLike(s) {
  return (
    /^\s*\d{2,4}\s*\/\s*\d{1,2}\s*\/\s*\d{1,2}\s*$/.test(s) ||
    /^\d{4}-\d{2}-\d{2}$/.test(s)
  );
}

async function nodeToCanvas(node) {
  return await html2canvas(node, {
    scale: H2C_SCALE,
    useCORS: true,
    backgroundColor: null,
  });
}

function getCharWidth(doc, ch) {
  const save = doc.getFont();
  let width;
  if (ch === "/") {
    doc.setFont("helvetica", "normal");
    width = doc.getTextDimensions(ch).w;
    doc.setFont(save.fontName, save.fontStyle);
  } else {
    width = doc.getTextDimensions(ch).w;
  }
  return width;
}

function drawPlainLTRByChars(doc, text, rightEdgePx, baselinePx, xMargin) {
  doc.setR2L(false);
  const chars = [...text];
  const save = doc.getFont();

  let totalW = 0;
  for (const ch of chars) totalW += getCharWidth(doc, ch);

  let x = rightEdgePx - totalW - (xMargin ?? 2);

  for (const ch of chars) {
    if (ch === "/") {
      doc.setFont("helvetica", "normal");
      doc.text("/", x, baselinePx, { align: "left" });
      x += doc.getTextDimensions("/").w;
      doc.setFont(save.fontName, save.fontStyle);
    } else {
      doc.text(ch, x, baselinePx, { align: "left" });
      x += doc.getTextDimensions(ch).w;
    }
  }

  doc.setR2L(true);
}

// ====== أهم دالة: اقرأ اللفّ الحقيقي من الـDOM ======
function getVisualLines(el) {
  if (el.childNodes.length > 1) {
    return [(el.innerText || "").trim()];
  }

  const textNode = el.firstChild;
  if (!textNode || textNode.nodeType !== Node.TEXT_NODE) {
    return [(el.innerText || "").trim()];
  }

  const fullText = textNode.textContent;
  if (!fullText.trim()) return [];

  const parts = fullText.split(/(\s+)/);
  const range = document.createRange();
  range.selectNodeContents(textNode);

  const lines = [];
  let currentTop = null;
  let currentLine = "";
  let offset = 0;

  for (let i = 0; i < parts.length; i++) {
    const part = parts[i];
    const end = offset + part.length;

    range.setStart(textNode, 0);
    range.setEnd(textNode, end);

    const rects = range.getClientRects();
    if (!rects.length) {
      offset = end;
      continue;
    }
    const top = rects[rects.length - 1].top;

    if (currentTop === null) {
      currentTop = top;
    }

    if (top > currentTop + 2) {
      lines.push(currentLine.trim());
      currentLine = part;
      currentTop = top;
    } else {
      currentLine += part;
    }

    offset = end;
  }

  if (currentLine.trim()) {
    lines.push(currentLine.trim());
  }

  return lines;
}

// ====== الدالة الرئيسية ======
async function downloadPDF() {
  const { jsPDF } = window.jspdf || {};
  if (!jsPDF) {
    alert("jsPDF غير محمّل");
    return;
  }

  const page1 =
    document.querySelector(".container.top") ||
    document.querySelector("#permitPage");
  if (!page1) {
    alert("تأكد من وجود .container.top أو #permitPage");
    return;
  }

  const oldTransform = page1.style.transform;
  const oldTransformOrigin = page1.style.transformOrigin;
  page1.style.transform = "none";
  page1.style.transformOrigin = "top center";

  const workerName =
    document.getElementById("workerName")?.innerText?.trim() || "";
  const docTitle = document.getElementById("docTitle")?.innerText?.trim() || "";
  const filename = (workerName || docTitle || "تصريح-أجير") + ".pdf";

  const c1 = await nodeToCanvas(page1);
  const [w1, h1] = [c1.width, c1.height];

    // ----------------------------------------------------------------
    // ✨ المنطقة المتحكمة في الأبعاد والتناسب ✨
    
    const PDF_EXPORT_WIDTH = 750; 
    const ratio = PDF_EXPORT_WIDTH / w1; // عامل التناسب
    const PDF_EXPORT_HEIGHT = h1 * ratio;
    
    // ----------------------------------------------------------------

  const pdf = new jsPDF({
    unit: "px",
    format: [PDF_EXPORT_WIDTH, PDF_EXPORT_HEIGHT], 
    orientation: PDF_EXPORT_WIDTH > PDF_EXPORT_HEIGHT ? "landscape" : "portrait", 
    compress: true,
  });

  pdf.addImage(
    c1.toDataURL("image/jpeg", 0.98), 
    "JPEG", 
    0, 
    0, 
    PDF_EXPORT_WIDTH, 
    PDF_EXPORT_HEIGHT
);

  const qrEl =
    page1.querySelector(".qr") ||
    page1.querySelector("#qr") ||
    page1.querySelector(".qr-box img");
  if (qrEl) {
    const qrBox = rectInPage(qrEl, page1);
    
    // ✨ تطبيق عامل التناسب على إحداثيات QR
    const linkX = qrBox.x * H2C_SCALE * ratio;
    const linkY = qrBox.y * H2C_SCALE * ratio;
    const linkW = qrBox.w * H2C_SCALE * ratio;
    const linkH = qrBox.h * H2C_SCALE * ratio;

    
  }

  const clickableLink =
    page1.querySelector(".clickable-link") ||
    page1.querySelector("#clickable-link");
  if (clickableLink) {
    const linkBox = rectInPage(clickableLink, page1);
    
    // ✨ تطبيق عامل التناسب على إحداثيات الرابط القابل للضغط
    const linkX = linkBox.x * H2C_SCALE * ratio; 
    const linkY = linkBox.y * H2C_SCALE * ratio;
    const linkW = linkBox.w * H2C_SCALE * ratio;
    const linkH = linkBox.h * H2C_SCALE * ratio;

    let link = document.getElementById("clickable-link");

    pdf.link(linkX, linkY, linkW, linkH, {
      url: link.href,
    });
  }

  await embedArabicFont(pdf);
  setInvisibleText(pdf);

  for (const sel of TEXT_SELECTORS_P1) {
    const el = page1.querySelector(sel);
    if (!el) continue;

    const box = rectInPage(el, page1);
    const cs = getComputedStyle(el);
    const fontSizePx = parseFloat(cs.fontSize) || 14;
    const rawText = el.innerText || el.textContent || "";
    const txt = rawText.trim();
    if (!txt) continue;

    const isDate = isDateLike(txt);
    pdf.setFont("NotoSansArabic", "normal");
    pdf.setFontSize(toPt(fontSizePx, isDate ? PX2PT_DATE : PX2PT_GENERAL));

    if (isDate) {
      const yBase = (box.y + box.h * DATE_Y_FACTOR) * H2C_SCALE - 30;
      const rightEdge = (box.x + box.w) * H2C_SCALE + GLOBAL_X_FIX;
      drawPlainLTRByChars(pdf, txt, rightEdge, yBase, DATE_X_MARGIN);
      continue;
    }

    const lines = getVisualLines(el);
    if (!lines.length) continue;

    const padTop = parseFloat(cs.paddingTop) || 0;
    let lineHeightPx = parseFloat(cs.lineHeight);
    if (isNaN(lineHeightPx)) {
      lineHeightPx = fontSizePx * 1.2;
    }
    const lineStep = lineHeightPx * H2C_SCALE;

    const firstBaseline =
      (box.y + padTop) * H2C_SCALE + lineStep * 0.78 + GLOBAL_Y_FIX;

    if (CENTER_FIELDS.includes(sel)) {
      const centerX = (box.x + box.w / 2) * H2C_SCALE + GLOBAL_X_FIX;
      lines.forEach((line, i) => {
        pdf.text(line, centerX, firstBaseline + i * lineStep, {
          align: "center",
        });
      });
    } else if (isRightAligned(el)) {
      const rightX = (box.x + box.w) * H2C_SCALE + GLOBAL_X_FIX;
      lines.forEach((line, i) => {
        pdf.text(line, rightX, firstBaseline + i * lineStep, {
          align: "right",
        });
      });
    } else {
      const leftX = box.x * H2C_SCALE + 2 + GLOBAL_X_FIX;
      lines.forEach((line, i) => {
        pdf.text(line, leftX, firstBaseline + i * lineStep, {
          align: "left",
        });
      });
    }
  }

  page1.style.transform = oldTransform;
  page1.style.transformOrigin = oldTransformOrigin;

  pdf.save(filename);
}

window.downloadPDF = downloadPDF;