/* global React */
// ============================================
// PDF mockup component + Signature canvas
// ============================================

function PdfDocMockup({ doc, signatureDataUrl, showStamp = true, showReceivedStamp = true }) {
  const docDate = formatThaiDate(doc.docDate, { full: true });
  const recvDate = formatThaiDate(doc.receivedDate, { full: true });
  // shorten subject to one line if too long
  const subjectShort = doc.subject;

  return React.createElement('div', { className: 'pdf-doc' },
    showReceivedStamp && React.createElement('div', { className: 'pdf-doc__received-stamp' },
      React.createElement('div', { className: 'label' }, 'เลขรับ'),
      React.createElement('div', { className: 'num' }, doc.docNumber),
      React.createElement('div', { className: 'label' }, recvDate.replace('ที่ ', ''))
    ),

    // crest
    React.createElement('div', { className: 'pdf-doc__crest' },
      React.createElement('div', { className: 'seal' }, 'ตรา', React.createElement('br'), 'ครุฑ')
    ),

    // ref + date
    React.createElement('div', { className: 'pdf-doc__header' },
      React.createElement('div', { className: 'left' },
        React.createElement('div', null, 'ที่ ', React.createElement('strong', null, doc.refNumber)),
        React.createElement('div', { style: { marginTop: 4 } }, 'สำนักงานเขตพื้นที่การศึกษา'),
        React.createElement('div', null, 'มัธยมศึกษาอุบลราชธานี อำนาจเจริญ'),
        React.createElement('div', null, 'ถนนเลี่ยงเมือง อุบลฯ 34000'),
      ),
      React.createElement('div', { className: 'right', style: { textAlign: 'right' } },
        docDate
      )
    ),

    React.createElement('div', { className: 'pdf-doc__greeting' }, 'เรื่อง  ', subjectShort),
    React.createElement('div', { className: 'pdf-doc__greeting' }, 'เรียน  ผู้อำนวยการโรงเรียน'),
    React.createElement('div', { className: 'pdf-doc__greeting' }, 'สิ่งที่ส่งมาด้วย  รายละเอียดตามเอกสารแนบ จำนวน 1 ฉบับ'),

    React.createElement('div', { className: 'pdf-doc__body' },
      'ด้วย สำนักงานเขตพื้นที่การศึกษามัธยมศึกษาอุบลราชธานี อำนาจเจริญ ได้รับแจ้งจากสำนักงานคณะกรรมการการศึกษาขั้นพื้นฐาน เกี่ยวกับ',
      React.createElement('strong', null, ' ' + subjectShort + ' '),
      'จึงขอแจ้งให้สถานศึกษาในสังกัดดำเนินการตามแนวทางที่กำหนด พร้อมทั้งรายงานผลการดำเนินงานกลับ สพม. ภายในกำหนดเวลาที่แจ้งในเอกสารแนบ'
    ),
    React.createElement('div', { className: 'pdf-doc__body' },
      'ในการนี้ จึงขอความอนุเคราะห์มายังท่านพิจารณาดำเนินการในส่วนที่เกี่ยวข้อง และแจ้งผู้รับผิดชอบเข้าดำเนินการตามรายละเอียดที่กำหนดต่อไป'
    ),
    React.createElement('div', { className: 'pdf-doc__body' },
      'จึงเรียนมาเพื่อโปรดพิจารณาดำเนินการต่อไป จะขอบคุณยิ่ง'
    ),

    React.createElement('div', { className: 'pdf-doc__signoff' },
      React.createElement('div', null, 'ขอแสดงความนับถือ'),
      React.createElement('div', { style: { height: 56 } }),
      React.createElement('div', null, '(นายอภิชาติ พลอยแสง)'),
      React.createElement('div', null, 'ผู้อำนวยการสำนักงานเขตพื้นที่การศึกษา'),
      React.createElement('div', null, 'มัธยมศึกษาอุบลราชธานี อำนาจเจริญ'),
    ),

    // signature spot from director (overlaid)
    signatureDataUrl && React.createElement('div', {
      className: 'pdf-doc__signature-area',
      style: { bottom: 'auto', top: 280, right: 60, width: 200, height: 130 }
    },
      React.createElement('div', { style: { textAlign: 'center', fontSize: 11 } }, 'ลายเซ็น ผอ. โรงเรียน'),
      React.createElement('img', { src: signatureDataUrl, alt: 'ลายเซ็น', style: { maxHeight: 70, marginTop: 4 } }),
      React.createElement('div', { className: 'pdf-doc__sig-line', style: { marginTop: 4 } }, '(นายสมพงษ์ ไชยมงคล)'),
      React.createElement('div', { style: { fontSize: 11, textAlign: 'center' } }, 'ผู้อำนวยการโรงเรียน'),
    ),
  );
}

// ============================================
// Director's note (เกษียณ) box that gets stamped on the PDF
// ============================================
function DirectorNoteStamp({ note, signatureDataUrl, assignedTeacherNames }) {
  if (!note) return null;
  return React.createElement('div', {
    style: {
      position: 'absolute',
      top: 200,
      left: 40,
      width: 240,
      background: 'oklch(0.97 0.05 75 / 0.92)',
      border: '1.5px dashed oklch(0.5 0.13 60)',
      borderRadius: 6,
      padding: '10px 12px',
      fontSize: 12,
      lineHeight: 1.55,
      color: 'oklch(0.28 0.08 60)',
      transform: 'rotate(-1.5deg)',
      boxShadow: '2px 2px 0 oklch(0.5 0.13 60 / 0.15)',
    }
  },
    React.createElement('div', { style: { fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', opacity: 0.7 } }, 'บันทึกของ ผอ.'),
    React.createElement('div', { style: { marginTop: 4, fontFamily: 'Sarabun, sans-serif' } }, note),
    assignedTeacherNames && assignedTeacherNames.length ? React.createElement('div', {
      style: { marginTop: 6, paddingTop: 6, borderTop: '1px solid oklch(0.5 0.13 60 / 0.3)' }
    },
      React.createElement('div', { style: { fontSize: 10, fontWeight: 700 } }, 'มอบหมาย:'),
      assignedTeacherNames.map((n, i) => React.createElement('div', { key: i, style: { fontSize: 11 } }, '• ' + n))
    ) : null,
    signatureDataUrl ? React.createElement('div', { style: { marginTop: 6, textAlign: 'right' } },
      React.createElement('img', { src: signatureDataUrl, style: { maxHeight: 40 } })
    ) : null,
  );
}

// ============================================
// Signature Canvas — drawable pad
// ============================================
function SignaturePad({ onChange, height = 220 }) {
  const canvasRef = useRef(null);
  const [hasInk, setHasInk] = useState(false);
  const drawingRef = useRef(false);
  const lastRef = useRef(null);

  useEffect(() => {
    const cnv = canvasRef.current;
    if (!cnv) return;
    const rect = cnv.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    cnv.width = rect.width * dpr;
    cnv.height = rect.height * dpr;
    const ctx = cnv.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.strokeStyle = '#0e2747';
    ctx.lineWidth = 2.2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
  }, []);

  const getPos = (e) => {
    const cnv = canvasRef.current;
    const rect = cnv.getBoundingClientRect();
    const t = e.touches?.[0] || e;
    return { x: t.clientX - rect.left, y: t.clientY - rect.top };
  };

  const start = (e) => {
    e.preventDefault();
    drawingRef.current = true;
    lastRef.current = getPos(e);
  };
  const move = (e) => {
    if (!drawingRef.current) return;
    e.preventDefault();
    const p = getPos(e);
    const ctx = canvasRef.current.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(lastRef.current.x, lastRef.current.y);
    // smooth curve via mid point
    const mx = (lastRef.current.x + p.x) / 2;
    const my = (lastRef.current.y + p.y) / 2;
    ctx.quadraticCurveTo(lastRef.current.x, lastRef.current.y, mx, my);
    ctx.stroke();
    lastRef.current = p;
    if (!hasInk) setHasInk(true);
  };
  const end = () => {
    if (!drawingRef.current) return;
    drawingRef.current = false;
    if (onChange && canvasRef.current) {
      onChange(canvasRef.current.toDataURL('image/png'));
    }
  };

  const clear = () => {
    const cnv = canvasRef.current;
    const ctx = cnv.getContext('2d');
    ctx.clearRect(0, 0, cnv.width, cnv.height);
    setHasInk(false);
    onChange && onChange(null);
  };

  return React.createElement('div', null,
    React.createElement('div', { className: 'sig-pad', style: { height } },
      React.createElement('canvas', {
        ref: canvasRef,
        style: { width: '100%', height: '100%' },
        onMouseDown: start, onMouseMove: move, onMouseUp: end, onMouseLeave: end,
        onTouchStart: start, onTouchMove: move, onTouchEnd: end,
      }),
      React.createElement('div', { className: 'sig-pad__baseline' }),
      !hasInk && React.createElement('div', { className: 'sig-pad__hint' },
        '✎ วาดลายเซ็นด้วย Apple Pencil / เมาส์ / นิ้ว'
      ),
    ),
    React.createElement('div', {
      style: { display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 12, color: 'var(--ink-3)' }
    },
      React.createElement('span', null, hasInk ? '✓ มีลายเซ็นแล้ว' : 'ยังไม่ได้เซ็น'),
      React.createElement('button', {
        className: 'btn btn--ghost btn--sm',
        onClick: clear, disabled: !hasInk,
      },
        React.createElement(Icon, { name: 'refresh', size: 12 }),
        'เคลียร์ลายเซ็น'
      ),
    ),
  );
}

// ============================================
// RealPdfPane — shows the actually-uploaded PDF (signed URL via iframe)
// with a working download button. Falls back to the HTML mockup when the
// document has no real uploaded file (e.g. seed/sample docs or mockup mode).
// ============================================
function RealPdfPane({ doc, kind = 'original', showReceivedStamp = true, signatureDataUrl = null }) {
  const { getDocFileUrl } = useStore();
  const [url, setUrl] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let alive = true;
    setLoading(true);
    Promise.resolve(getDocFileUrl(doc, kind)).then(
      u => { if (alive) { setUrl(u); setLoading(false); } },
      () => { if (alive) { setUrl(null); setLoading(false); } }
    );
    return () => { alive = false; };
  }, [doc.id, kind]);

  const filename = `${doc.docNumber}_${kind}.pdf`;

  const header = React.createElement('div', { className: 'pdf-frame' },
    React.createElement('div', { className: 'filename' },
      React.createElement(Icon, { name: 'fileText', size: 14 }), filename),
    React.createElement('div', { className: 'row' },
      React.createElement('button', {
        className: 'btn btn--ghost btn--sm',
        disabled: !url,
        title: url ? 'เปิด/ดาวน์โหลดไฟล์จริง' : 'ยังไม่มีไฟล์จริง',
        onClick: () => { if (url) window.open(url, '_blank', 'noopener'); },
      }, React.createElement(Icon, { name: 'download', size: 12 }), 'ดาวน์โหลด'),
    ),
  );

  let body;
  if (loading) {
    body = React.createElement('div', {
      className: 'pdf-doc',
      style: { display: 'grid', placeItems: 'center', minHeight: 320, color: 'var(--ink-3)' }
    }, 'กำลังโหลดไฟล์…');
  } else if (url) {
    body = React.createElement('iframe', {
      src: url, title: filename,
      style: { width: '100%', height: 540, border: '1px solid var(--line)', borderRadius: 8, background: '#fff' },
    });
  } else {
    // no real file → keep the existing HTML mockup so older/seed docs still render
    body = React.createElement(PdfDocMockup, { doc, signatureDataUrl, showReceivedStamp });
  }

  return React.createElement(React.Fragment, null, header, body);
}

// ============================================
// generateEndorsedPdf — สร้าง "ใบเกษียณ" ภาษาไทยเป็นรูป (html2canvas)
// แล้วแนบเป็นหน้าใหม่ต่อท้าย PDF ต้นฉบับ (pdf-lib) → คืนเป็น File พร้อมอัปโหลด
// ============================================
async function generateEndorsedPdf({ doc, originalUrl, signatureDataUrl, note, assignedNames, dueDate, directorName, schoolName }) {
  if (typeof PDFLib === 'undefined' || typeof html2canvas === 'undefined') {
    throw new Error('ไลบรารีสร้าง PDF ยังโหลดไม่เสร็จ ลองรีเฟรชหน้าใหม่');
  }
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const today = (typeof formatThaiDate !== 'undefined')
    ? formatThaiDate(new Date().toISOString(), { full: true })
    : new Date().toLocaleDateString('th-TH');
  const names = (assignedNames || []).filter(Boolean);

  // 1) เรนเดอร์การ์ดใบเกษียณใน iframe แยก (ไม่มี CSS ธีม oklch ของแอป)
  //    เพื่อเลี่ยงบั๊ก html2canvas ที่ parse oklch ไม่ได้ — ฟอนต์ไทยยังถูกต้อง
  const cardHtml =
    '<div id="endorse" style="width:760px;padding:56px 48px;background:#ffffff;font-family:Sarabun,sans-serif;color:#16170f;line-height:1.6;box-sizing:border-box;">' +
      '<div style="text-align:center;border-bottom:2px solid #3a8054;padding-bottom:14px;margin-bottom:22px;">' +
        '<div style="font-size:24px;font-weight:800;color:#2a3b2f;">ใบเกษียณหนังสือ</div>' +
        '<div style="font-size:15px;color:#5a5a4a;margin-top:2px;">บันทึกการพิจารณาของผู้อำนวยการ' + (schoolName ? ' · ' + esc(schoolName) : '') + '</div>' +
      '</div>' +
      '<table style="width:100%;font-size:16px;border-collapse:collapse;margin-bottom:18px;">' +
        '<tr><td style="padding:4px 0;width:130px;color:#6b6b58;">เลขรับ</td><td style="font-weight:700;">' + esc(doc.docNumber) + '</td></tr>' +
        '<tr><td style="padding:4px 0;color:#6b6b58;">เลขที่หนังสือ</td><td>' + esc(doc.refNumber || '-') + '</td></tr>' +
        '<tr><td style="padding:4px 0;color:#6b6b58;vertical-align:top;">เรื่อง</td><td>' + esc(doc.subject) + '</td></tr>' +
        '<tr><td style="padding:4px 0;color:#6b6b58;">จาก</td><td>' + esc(doc.from || doc.fromShort || '-') + '</td></tr>' +
      '</table>' +
      '<div style="font-size:15px;color:#6b6b58;margin-bottom:6px;">บันทึกเกษียณของผู้อำนวยการ</div>' +
      '<div style="border:1.5px solid #d8d8c8;border-radius:8px;padding:16px;min-height:90px;font-size:17px;white-space:pre-wrap;margin-bottom:18px;background:#fcfcf7;">' + esc(note) + '</div>' +
      (names.length ? ('<div style="font-size:15px;color:#6b6b58;margin-bottom:6px;">มอบหมายผู้รับผิดชอบ</div><div style="font-size:16px;margin-bottom:18px;">' + names.map(n => '• ' + esc(n)).join('<br>') + '</div>') : '') +
      (dueDate ? ('<div style="font-size:16px;margin-bottom:18px;"><span style="color:#6b6b58;">กำหนดส่งภายใน: </span><strong>' + esc((typeof formatThaiDate !== 'undefined') ? formatThaiDate(dueDate, { full: true }) : dueDate) + '</strong></div>') : '') +
      '<div style="margin-top:30px;text-align:center;">' +
        (signatureDataUrl ? '<img src="' + signatureDataUrl + '" style="max-height:90px;display:block;margin:0 auto 4px;">' : '<div style="height:70px;"></div>') +
        '<div style="border-top:1px solid #16170f;display:inline-block;padding-top:4px;min-width:260px;font-size:16px;">( ' + esc(directorName || 'ผู้อำนวยการโรงเรียน') + ' )</div>' +
        '<div style="font-size:15px;margin-top:2px;">ผู้อำนวยการโรงเรียน</div>' +
        '<div style="font-size:14px;color:#6b6b58;margin-top:2px;">' + esc(today) + '</div>' +
      '</div>' +
    '</div>';

  const iframe = document.createElement('iframe');
  iframe.style.cssText = 'position:absolute;left:-10000px;top:0;width:800px;height:1400px;border:0;';
  document.body.appendChild(iframe);

  let pngDataUrl;
  try {
    const idoc = iframe.contentDocument || iframe.contentWindow.document;
    idoc.open();
    idoc.write('<!DOCTYPE html><html><head><meta charset="utf-8">' +
      '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>' +
      '<link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">' +
      '</head><body style="margin:0;background:#fff;">' + cardHtml + '</body></html>');
    idoc.close();
    // รอฟอนต์ไทยโหลด (มักมาจาก cache ของหน้าหลัก จึงเร็ว) + เผื่อเวลาเล็กน้อย
    try { if (idoc.fonts && idoc.fonts.ready) await idoc.fonts.ready; } catch (e) {}
    await new Promise(r => setTimeout(r, 150));
    const target = idoc.getElementById('endorse');
    const canvas = await html2canvas(target, { scale: 2, backgroundColor: '#ffffff', logging: false, useCORS: true });
    pngDataUrl = canvas.toDataURL('image/png');
  } finally {
    document.body.removeChild(iframe);
  }

  // 2) โหลดต้นฉบับ (ถ้ามี) แล้วเพิ่มหน้าใบเกษียณต่อท้าย
  const { PDFDocument } = PDFLib;
  let pdfDoc;
  if (originalUrl) {
    const bytes = await fetch(originalUrl).then(r => { if (!r.ok) throw new Error('โหลดไฟล์ต้นฉบับไม่สำเร็จ'); return r.arrayBuffer(); });
    pdfDoc = await PDFDocument.load(bytes, { ignoreEncryption: true });
  } else {
    pdfDoc = await PDFDocument.create();
  }
  const pngBytes = await fetch(pngDataUrl).then(r => r.arrayBuffer());
  const png = await pdfDoc.embedPng(pngBytes);
  const PAGE_W = 595.28, PAGE_H = 841.89, margin = 36;
  const page = pdfDoc.addPage([PAGE_W, PAGE_H]);
  const maxW = PAGE_W - margin * 2, maxH = PAGE_H - margin * 2;
  const scale = Math.min(maxW / png.width, maxH / png.height);
  const w = png.width * scale, h = png.height * scale;
  page.drawImage(png, { x: (PAGE_W - w) / 2, y: PAGE_H - margin - h, width: w, height: h });

  const out = await pdfDoc.save();
  const safeName = String(doc.docNumber).replace(/\//g, '-');
  return new File([out], safeName + '_signed.pdf', { type: 'application/pdf' });
}

Object.assign(window, { PdfDocMockup, DirectorNoteStamp, SignaturePad, RealPdfPane, generateEndorsedPdf });
