/* ===================== Sani locate — หาตำแหน่งกรอบ marker งานสุขาภิบาลแบบ 2 ขั้น =====================
   ทำไม: item_marks ที่ AI ใส่มาตอนถอด = กะด้วยตาจากทั้งชุดแบบ → เลื่อน 0.07–0.13 ของหน้า ไปเกาะป้ายข้อความ/ที่ว่าง
     (บ้านไทยร่วมสมัย2 หน้า 50–51 · fulltestบ้านดุง หน้า 2 · ตรวจ 5 พ.ย.) — จำนวนถูก ผิดแค่ตำแหน่ง
   วิธี: ใช้รายการเดิม (รหัส + จำนวนต่อหน้า จาก item_marks ตอนถอด) แล้วถาม AI ใหม่ทีละหน้า ผ่าน Edge Function (action locate_marks)
     ขั้น 1 "cells": ภาพทั้งหน้าตีตาราง (แนวนอน 20×14 · แนวตั้ง 14×20) → ช่องที่แต่ละตัวอยู่ เช่น WC.1 → F7
     ขั้น 2 "boxes": ตัดภาพ 3×3 ช่องรอบช่องนั้น (กันพลาด 1 ช่อง) ตีเส้น 0–100 → กรอบพอดีตัว
   ‼️ หาไม่เจอ (ขั้น 1 ไม่ตอบ / ขั้น 2 ได้ null หรือกรอบผิดรูป) = ไม่วาง marker ตัวนั้น (พิ้งกำหนด) — ไม่ใช้กรอบเดิมแทน
   พิกัด: เรนเดอร์ด้วย pdf.js viewport ปกติ (รวม /Rotate) = หน้าเดียวกับที่ PdfDrawing แสดง → b เป็นสัดส่วนหน้า (0–1) ใช้ได้ทันที ไม่ต้องแปลง up
   API:  window.sbLocateSaniMarks({ storagePath, itemMarks, rows, nameOf, accessToken, onProgress, projectId })
         rows = แถวตารางสุขาภิบาล ({code, count, page_num}) — รายการที่ไม่มีกรอบตอนถอดก็ถูกหาด้วย (ดู groupJobs)
         → { marks:[{code,page,b:[x0,y0,x1,y1]}], missing:[{code,page,n}], asked, found, thb } */
(function(){
  const PDFJS_SRC    = 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.min.js';
  const PDFJS_WORKER = 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.worker.min.js';
  const EDGE_URL = 'https://zokzcjbvjcxfjpcjsegx.supabase.co/functions/v1/analyze-drawing';
  const EDGE_PUB = 'sb_publishable_nL-wFMwEzKss2HZOylspIA_9ypFMEWv';
  const PAGE_PX = 2000;     // ด้านยาวของภาพทั้งหน้า (ขั้น 1) — ราว 3,900 token/หน้า ตามที่วัดจากสายไฟฟ้า
  const CROP_PX = 700;      // ด้านกว้างของภาพซูม (ขั้น 2)
  const CROP_MAX_SCALE = 8;
  const BOX_CHUNK = 16;     // ภาพซูมต่อ 1 ครั้งที่เรียก AI (edge รับ ≤ 20)
  const JPEG_Q = 0.85;
  const r4 = (v)=>Math.round(v * 10000) / 10000;

  const loadScript = (src)=> window.sbLoadScript ? window.sbLoadScript(src) : new Promise((res,rej)=>{
    const el=document.createElement('script'); el.src=src; el.async=true; el.onload=res; el.onerror=()=>rej(new Error('โหลดสคริปต์ไม่ได้: '+src)); document.head.appendChild(el);
  });

  /* ── เรขาคณิต (pure — ทดสอบแยกได้ผ่าน _internal) ── */
  // หน้าแนวนอน 20 คอลัมน์ × 14 แถว · แนวตั้งสลับกัน → ช่องเกือบจัตุรัสทั้งสองแบบ (A3/A1 อัตราส่วน √2)
  const gridDims = (w, h)=> w >= h ? { cols: 20, rows: 14 } : { cols: 14, rows: 20 };
  const colLabel = (c)=> String.fromCharCode(65 + c);
  // "F7" → { c:5, r:6 } (เริ่ม 0) · นอกตาราง/รูปแบบผิด = null
  function parseCell(cell, cols, rows){
    const m = String(cell || '').trim().toUpperCase().match(/^([A-Z])\s*-?\s*(\d{1,2})$/);
    if(!m) return null;
    const c = m[1].charCodeAt(0) - 65, r = Number(m[2]) - 1;
    return (c >= 0 && c < cols && r >= 0 && r < rows) ? { c, r } : null;
  }
  // ช่อง (c,r) ± pad ช่อง → [x0,y0,x1,y1] สัดส่วนหน้า (ชิดขอบหน้าแล้วเลื่อนเข้า ให้ได้ 3×3 ช่องเสมอ)
  function cellRect({ c, r }, cols, rows, pad = 1){
    const span = 2 * pad + 1;
    const c0 = Math.max(0, Math.min(cols - span, c - pad)), r0 = Math.max(0, Math.min(rows - span, r - pad));
    return [c0 / cols, r0 / rows, (c0 + span) / cols, (r0 + span) / rows];
  }
  // กรอบ 0–100 ของภาพซูม → สัดส่วนหน้า · ผิดรูป (ไม่ใช่ตัวเลข/กลับด้าน/เล็กจิ๋ว/เกือบเต็มภาพ) = null
  function boxToPage(b, rect){
    if(!Array.isArray(b) || b.length !== 4) return null;
    let [x0, y0, x1, y1] = b.map(Number);
    if(![x0, y0, x1, y1].every(Number.isFinite)) return null;
    [x0, x1] = [Math.min(x0, x1), Math.max(x0, x1)]; [y0, y1] = [Math.min(y0, y1), Math.max(y0, y1)];
    x0 = Math.max(0, x0); y0 = Math.max(0, y0); x1 = Math.min(100, x1); y1 = Math.min(100, y1);
    if(x1 - x0 < 1 || y1 - y0 < 1) return null;
    if(x1 - x0 > 90 && y1 - y0 > 90) return null;    // ครอบทั้งภาพ = AI ไม่ได้ชี้ตัวอุปกรณ์จริง
    const [rx0, ry0, rx1, ry1] = rect, rw = rx1 - rx0, rh = ry1 - ry0;
    return [rx0 + x0 / 100 * rw, ry0 + y0 / 100 * rh, rx0 + x1 / 100 * rw, ry0 + y1 / 100 * rh].map(r4);
  }
  const iou = (a, b)=>{
    const ix = Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0])), iy = Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
    const inter = ix * iy, ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter;
    return ua > 0 ? inter / ua : 0;
  };
  // งานต่อหน้า { page: [{code, n}] } จาก (1) item_marks ตอนถอด (หน้า + จำนวนที่ AI ตีกรอบไว้) + (2) แถวในตาราง (รหัส · จำนวน · page_num)
  //   ‼️ item_marks ตอนถอดมีแค่บางรายการ (ร่วมสมัย3: 8 กรอบ จาก 25 รหัสในตาราง · MH-1 1 กรอบ แต่ตาราง 4) → รายการที่ไม่มีกรอบไม่เคยถูกหา
  //   → จำนวนที่ขอต่อรหัส = max(จำนวนในตาราง, จำนวนกรอบเดิม) · ส่วนที่เกินกรอบเดิมไปหาที่หน้าของแถว (page_num) ก่อน ไม่มี = หน้ากรอบเดิมหน้าแรก
  //   AI "ห้ามเดา" อยู่แล้ว → หน้าไหนไม่มีของจริงก็ไม่วาง · rows ไม่ส่ง = แบบเดิม (item_marks อย่างเดียว)
  function groupJobs(itemMarks, rows){
    const byPage = new Map(), add = (pg, code, n)=>{
      if(!(pg >= 1) || !code || !(n > 0)) return;
      if(!byPage.has(pg)) byPage.set(pg, new Map());
      const cm = byPage.get(pg); cm.set(code, (cm.get(code) || 0) + n);
    };
    const imByCode = new Map();
    for(const m of (Array.isArray(itemMarks) ? itemMarks : [])){
      const pg = Number(m && m.page), code = m && m.code != null ? String(m.code) : '';
      if(!(pg >= 1) || !code) continue;
      add(pg, code, 1);
      if(!imByCode.has(code)) imByCode.set(code, []);
      imByCode.get(code).push(pg);
    }
    const rowByCode = new Map();
    for(const r of (Array.isArray(rows) ? rows : [])){
      const code = r && r.code != null ? String(r.code).trim() : '', n = Number(r && r.count), pg = Number(r && r.page_num);
      if(!code || !(n > 0) || !Number.isFinite(n)) continue;
      const o = rowByCode.get(code) || { n: 0, pages: [], sheet: r.sheet || '' }; o.n += Math.round(n); if(pg >= 1 && !o.pages.includes(pg)) o.pages.push(pg);
      rowByCode.set(code, o);
    }
    // หน้าผังของแต่ละชีต = หน้าที่ item_marks ตอนถอดตีกรอบรายการชีตนั้นไว้มากสุด (กรอบตอนถอดมาจากผังเสมอ)
    //   ‼️ page_num ของแถวมักชี้ "หน้าตารางสุขภัณฑ์" (รูปแค็ตตาล็อก ไม่ใช่ตำแหน่งติดตั้ง · ร่วมสมัย3 หน้า 17) → ใช้หน้าผังของชีตก่อน
    const planOf = new Map();
    for(const [code, pgs] of imByCode){ const sh = (rowByCode.get(code) || {}).sheet; if(!sh) continue;
      const m = planOf.get(sh) || new Map(); pgs.forEach((p)=>m.set(p, (m.get(p) || 0) + 1)); planOf.set(sh, m); }
    const planPage = (sh)=>{ const m = planOf.get(sh); return m ? [...m].sort((a, b)=>b[1] - a[1] || a[0] - b[0])[0][0] : 0; };
    for(const [code, o] of rowByCode){
      const had = (imByCode.get(code) || []).length, rest = Math.min(o.n, 50) - had;
      if(rest <= 0) continue;
      // หน้าของแถวที่มีกรอบตอนถอดอยู่แล้ว (= หน้าผัง) ใช้ได้ก่อน (SINK ร่วมสมัย3 → ผังสุขาภิบาลหน้า 50 ไม่ใช่ผังห้องน้ำ)
      const pg = (imByCode.get(code) || [])[0] || o.pages.find((p)=>byPage.has(p)) || planPage(o.sheet) || o.pages[0];
      add(pg, code, rest);
    }
    return [...byPage].sort((a, b)=>a[0] - b[0]).map(([page, cm])=>({ page, items: [...cm].map(([code, n])=>({ code, n })) }));
  }

  // แผนค้นหลายหน้า (ใช้จริง · groupJobs เก็บไว้ทดสอบ/เทียบ): ทุกรหัสมี "จำนวนที่ยังหาไม่เจอ" → ไล่หน้าผู้สมัครตามลำดับ เจอเท่าไรหักออก
  //   ‼️ ร่วมสมัย5 (7 พ.ย.): ของชิ้นเล็กในห้องน้ำ (F1 PH HS M TR SP SW K FD) ไม่ได้วาดในผังสุขาภิบาล 1:100 (หน้า 52)
  //      แต่วาดในผังขยายห้องน้ำ (หน้า 17-18) · page_num ของแถวปนกัน 16 (ตารางมาตรฐาน) / 17 / 18 → เดิมหาหน้าเดียว เจอ 20/53
  //   หน้าผู้สมัครของรหัส = หน้ากรอบตอนถอดของรหัสนั้น + หน้ากรอบตอนถอดของชีตเดียวกัน (ผัง) + ทุกหน้าที่แถวในชีตเดียวกันชี้ (ผังขยาย)
  //   ลำดับหน้า: หน้าที่มีกรอบตอนถอดก่อน (มากไปน้อย) → หน้าอื่นเลขหน้ามากไปน้อย (ผังขยายมักอยู่หลังหน้าตารางมาตรฐาน)
  function planSearch(itemMarks, rows){
    const imByCode = new Map(), imCount = new Map(), rowByCode = new Map();
    for(const m of (Array.isArray(itemMarks) ? itemMarks : [])){
      const pg = Number(m && m.page), code = m && m.code != null ? String(m.code) : '';
      if(!(pg >= 1) || !code) continue;
      if(!imByCode.has(code)) imByCode.set(code, []);
      imByCode.get(code).push(pg); imCount.set(pg, (imCount.get(pg) || 0) + 1);
    }
    for(const r of (Array.isArray(rows) ? rows : [])){
      const code = r && r.code != null ? String(r.code).trim() : '', n = Number(r && r.count), pg = Number(r && r.page_num);
      if(!code || !Number.isFinite(n)) continue;
      const o = rowByCode.get(code) || { n: 0, pages: [], sheet: r.sheet || '' }; o.n += Math.max(0, Math.round(n));
      if(pg >= 1 && !o.pages.includes(pg)) o.pages.push(pg);
      rowByCode.set(code, o);
    }
    const sheetIm = new Map(), sheetRows = new Map();
    for(const [code, pgs] of imByCode){ const sh = (rowByCode.get(code) || {}).sheet; if(sh){ if(!sheetIm.has(sh)) sheetIm.set(sh, new Set()); pgs.forEach((p)=>sheetIm.get(sh).add(p)); } }
    for(const o of rowByCode.values()){ if(!sheetRows.has(o.sheet)) sheetRows.set(o.sheet, new Set()); o.pages.forEach((p)=>sheetRows.get(o.sheet).add(p)); }
    const cand = new Map();
    for(const code of new Set([...imByCode.keys(), ...rowByCode.keys()])){
      const o = rowByCode.get(code), im = imByCode.get(code) || [];
      const n = Math.min(50, Math.max(o ? o.n : 0, im.length)); if(!(n > 0)) continue;
      const pages = new Set(im);
      if(o){ o.pages.forEach((p)=>pages.add(p)); [...(sheetIm.get(o.sheet) || [])].forEach((p)=>pages.add(p)); [...(sheetRows.get(o.sheet) || [])].forEach((p)=>pages.add(p)); }
      if(!pages.size) [...imCount.keys()].forEach((p)=>pages.add(p));   // ไม่รู้หน้าเลย → หน้าผังที่มีกรอบตอนถอด
      if(pages.size) cand.set(code, { n, pages });
    }
    const all = new Set(); cand.forEach((c)=>c.pages.forEach((p)=>all.add(p)));
    const order = [...all].sort((a, b)=>(imCount.get(b) || 0) - (imCount.get(a) || 0) || b - a);
    return { order, cand };
  }
  // หน้าตารางมาตรฐาน/แค็ตตาล็อก: รูปสุขภัณฑ์ทุกชนิดเรียงแถวเดียวพร้อมชื่อใต้รูป → AI ชี้ได้ทุกรหัสในแถวเดียวกัน แต่ไม่ใช่ตำแหน่งติดตั้ง
  //   ขั้น 1 ตอบรหัสต่างกัน ≥5 ตัว อยู่ในแถวตาราง ≤2 แถว = หน้าแค็ตตาล็อก → ไม่วาง (ร่วมสมัย3 หน้า 17 · ร่วมสมัย5 หน้า 16)
  function looksCatalog(spots){
    const codes = new Set(spots.map((s)=>s.code)), rowsUsed = new Set(spots.map((s)=>s.r));
    return codes.size >= 5 && rowsUsed.size <= 2;
  }

  /* ── ภาพ ── */
  async function renderRegion(pg, rect, targetW){
    const vp1 = pg.getViewport({ scale: 1 });
    const rw = (rect[2] - rect[0]) * vp1.width;
    const s = Math.min(CROP_MAX_SCALE, targetW / rw);
    const vp = pg.getViewport({ scale: s, offsetX: -rect[0] * vp1.width * s, offsetY: -rect[1] * vp1.height * s });
    const c = document.createElement('canvas');
    c.width = Math.max(1, Math.round(rw * s)); c.height = Math.max(1, Math.round((rect[3] - rect[1]) * vp1.height * s));
    const x = c.getContext('2d'); x.fillStyle = '#fff'; x.fillRect(0, 0, c.width, c.height);
    await pg.render({ canvasContext: x, viewport: vp }).promise;
    return c;
  }
  const label = (x, text, px, py, color)=>{
    const w = x.measureText(text).width + 6, h = parseInt(x.font, 10) + 4;
    x.fillStyle = 'rgba(255,255,255,.85)'; x.fillRect(px - w / 2, py - h / 2, w, h);
    x.fillStyle = color; x.fillText(text, px, py);
  };
  // ขั้น 1: ทั้งหน้า + ตาราง A.. × 1.. (ป้ายที่ขอบทั้ง 4 ด้าน)
  function drawPageGrid(c, cols, rows){
    const x = c.getContext('2d'), cw = c.width / cols, ch = c.height / rows;
    x.lineWidth = 1.5;
    for(let i = 1; i < cols; i++){ x.strokeStyle = 'rgba(0,110,255,.55)'; x.beginPath(); x.moveTo(i * cw, 0); x.lineTo(i * cw, c.height); x.stroke(); }
    for(let j = 1; j < rows; j++){ x.strokeStyle = 'rgba(255,80,0,.55)'; x.beginPath(); x.moveTo(0, j * ch); x.lineTo(c.width, j * ch); x.stroke(); }
    x.font = `bold ${Math.round(Math.min(cw, ch) * 0.28)}px sans-serif`; x.textAlign = 'center'; x.textBaseline = 'middle';
    const m = Math.min(cw, ch) * 0.22;
    for(let i = 0; i < cols; i++){ label(x, colLabel(i), (i + 0.5) * cw, m, '#0057d9'); label(x, colLabel(i), (i + 0.5) * cw, c.height - m, '#0057d9'); }
    for(let j = 0; j < rows; j++){ label(x, String(j + 1), m * 1.3, (j + 0.5) * ch, '#d94a00'); label(x, String(j + 1), c.width - m * 1.3, (j + 0.5) * ch, '#d94a00'); }
  }
  // ขั้น 2: ภาพซูม + เส้น 0–100 (ทุก 5 จาง · ทุก 10 เข้ม + ตัวเลขบน/ซ้าย)
  function drawCropGrid(c){
    const x = c.getContext('2d');
    x.font = `bold ${Math.round(c.width * 0.026)}px sans-serif`; x.textAlign = 'center'; x.textBaseline = 'middle';
    for(let v = 5; v < 100; v += 5){
      const major = v % 10 === 0, px = v / 100 * c.width, py = v / 100 * c.height;
      x.lineWidth = major ? 1.4 : 0.8;
      x.strokeStyle = major ? 'rgba(0,110,255,.55)' : 'rgba(0,110,255,.25)'; x.beginPath(); x.moveTo(px, 0); x.lineTo(px, c.height); x.stroke();
      x.strokeStyle = major ? 'rgba(255,80,0,.55)' : 'rgba(255,80,0,.25)'; x.beginPath(); x.moveTo(0, py); x.lineTo(c.width, py); x.stroke();
      if(major){ label(x, String(v), px, c.width * 0.02, '#0057d9'); label(x, String(v), c.width * 0.03, py, '#d94a00'); }
    }
  }
  const toJpeg = (c)=> c.toDataURL('image/jpeg', JPEG_Q).split(',')[1];

  async function callEdge(payload, token, projectId){
    const res = await fetch(EDGE_URL, { method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token, 'apikey': EDGE_PUB },
      body: JSON.stringify({ action: 'locate_marks', projectId, ...payload }) });   // projectId: Edge เช็กเจ้าของ + เพดาน (migration 0007)
    if(!res.ok){ let d = ''; try{ d = (await res.json()).error || ''; }catch(e){} throw new Error('locate_marks ' + res.status + (d ? (' · ' + d) : '')); }
    const j = await res.json();
    return { result: Array.isArray(j.result) ? j.result : [], thb: Number(j.usage && j.usage.thb) || 0 };
  }

  /* ══════════ main ══════════ */
  async function sbLocateSaniMarks({ storagePath, itemMarks, rows, nameOf, accessToken, onProgress, projectId }){
    const prog = (msg)=>{ try{ onProgress && onProgress({ msg }); }catch(e){} };
    if(!storagePath) throw new Error('ไม่มีไฟล์แบบ');
    if(!accessToken) throw new Error('ไม่พบการเข้าสู่ระบบ — ล็อกอินใหม่แล้วลองอีกครั้ง');
    const jobs = planSearch(itemMarks, rows).order;
    if(!jobs.length) throw new Error('ผลถอดนี้ไม่มีรายการสุขาภิบาลที่รู้หน้า (item_marks / page_num)');
    if(!window.fetchSignedUrl) throw new Error('ยังโหลดตัวช่วยแบบไม่ครบ (fetchSignedUrl)');
    prog('โหลดแบบ…');
    if(!window.pdfjsLib) await loadScript(PDFJS_SRC);
    if(!window.pdfjsLib) throw new Error('โหลดตัวอ่าน PDF (pdf.js) ไม่ได้');
    window.pdfjsLib.GlobalWorkerOptions.workerSrc = PDFJS_WORKER;
    const doc = await window.pdfjsLib.getDocument({ url: await window.fetchSignedUrl(storagePath), isEvalSupported: false }).promise; // isEvalSupported:false = ปิดช่องโหว่ CVE-2024-4367 ของ pdf.js 3.x (ฟอนต์ใน PDF สั่งรันโค้ดได้)
    const name = (code)=>{ try{ return String((nameOf && nameOf(code)) || '').slice(0, 60); }catch(e){ return ''; } };
    const marks = [], missing = [];
    let asked = 0, thb = 0;
    const plan = planSearch(itemMarks, rows);
    const remain = new Map([...plan.cand].map(([code, c])=>[code, c.n]));
    asked = [...remain.values()].reduce((a, n)=>a + n, 0);
    try{
      for(let k = 0; k < plan.order.length; k++){
        const page = plan.order[k];
        if(page > doc.numPages) continue;
        const items = [...plan.cand].filter(([code, c])=>c.pages.has(page) && remain.get(code) > 0).map(([code])=>({ code, n: remain.get(code) }));
        if(!items.length) continue;
        const tag = `หน้า ${page} (${k + 1}/${plan.order.length})`;
        const pg = await doc.getPage(page);
        const vp1 = pg.getViewport({ scale: 1 });
        const { cols, rows } = gridDims(vp1.width, vp1.height);
        const want = new Map(items.map((it)=>[it.code, it.n]));

        // ขั้น 1 — ช่องคร่าว ๆ
        prog(`${tag} — หาช่องคร่าว ๆ…`);
        const full = await renderRegion(pg, [0, 0, 1, 1], PAGE_PX);
        drawPageGrid(full, cols, rows);
        const s1 = await callEdge({ stage: 'cells', image: toJpeg(full), cols, rows,
          items: items.map((it)=>({ code: it.code, name: name(it.code), n: it.n })) }, accessToken, projectId);
        thb += s1.thb;
        const left = new Map(want), spots = [];
        for(const o of s1.result){
          const code = o && o.code != null ? String(o.code) : '', cell = parseCell(o && o.cell, cols, rows);
          if(!cell || !(left.get(code) > 0)) continue;    // รหัสนอกรายการ / ตอบเกินจำนวน = ทิ้ง
          left.set(code, left.get(code) - 1);
          spots.push({ code, r: cell.r, rect: cellRect(cell, cols, rows) });
        }
        if(looksCatalog(spots)){ try{ pg.cleanup && pg.cleanup(); }catch(e){} continue; }

        // ขั้น 2 — ซูมทีละจุดแล้วชี้กรอบ
        const placed = [];
        for(let s = 0; s < spots.length; s += BOX_CHUNK){
          const grp = spots.slice(s, s + BOX_CHUNK);
          prog(`${tag} — ซูมชี้กรอบ ${Math.min(s + BOX_CHUNK, spots.length)}/${spots.length}…`);
          const images = [];
          for(const sp of grp){ const c = await renderRegion(pg, sp.rect, CROP_PX); drawCropGrid(c); images.push(toJpeg(c)); }
          const s2 = await callEdge({ stage: 'boxes', images,
            items: grp.map((sp, j)=>({ i: j + 1, code: sp.code, name: name(sp.code) })) }, accessToken, projectId);
          thb += s2.thb;
          const byI = new Map(s2.result.map((o)=>[Number(o && o.i), o && o.b]));
          grp.forEach((sp, j)=>{
            const b = boxToPage(byI.get(j + 1), sp.rect);
            // ช่องติดกัน 2 ช่องอาจชี้ตัวเดียวกัน → กรอบซ้อนกันเกินครึ่ง = นับเป็นตัวเดียว
            if(b && !placed.some((p)=>p.code === sp.code && iou(p.b, b) > 0.4)) placed.push({ code: sp.code, page, b });
          });
        }
        marks.push(...placed);
        placed.forEach((p)=>remain.set(p.code, Math.max(0, (remain.get(p.code) || 0) - 1)));
        try{ pg.cleanup && pg.cleanup(); }catch(e){}
      }
    } finally { try{ doc.destroy && doc.destroy(); }catch(e){} }
    // หาไม่เจอ = ที่ยังเหลือหลังไล่ทุกหน้าผู้สมัคร (บอกหน้าแรกของรหัสนั้น)
    for(const [code, n] of remain) if(n > 0) missing.push({ code, page: plan.order.find((p)=>plan.cand.get(code).pages.has(p)), n });
    return { marks, missing, asked, found: marks.length, thb: Math.round(thb * 100) / 100 };
  }

  window.sbLocateSaniMarks = sbLocateSaniMarks;
  window.sbLocateSaniMarks._internal = { gridDims, parseCell, cellRect, boxToPage, iou, groupJobs, planSearch, looksCatalog, drawPageGrid, drawCropGrid, renderRegion };
})();
