/* ===================== Structural drawing placeholder ===================== */
function DrawingPlan({ page, highlightCode, highlightCat }){
  // SVG coordinate grid
  const cols = [120, 300, 480, 600];   // x grid lines (1..4)
  const ry   = [120, 250, 400];        // y grid lines (A..C)
  const gx = ['1','2','3','4'], gy = ['A','B','C'];

  // ── Highlight map: รหัสโครงสร้าง → ตำแหน่งบน SVG ──────────────────
  // pts = จุดกึ่งกลางของ element นั้น (เสา/ฐานราก)
  // segs = เส้นคาน [{x1,y1,x2,y2}]
  // rect = พื้นที่เต็ม (พื้น/หลังคา/บันได) {x,y,w,h}
  const HL = {
    // ── ฐานราก ──
    F1: { type:'footing', pts:[{x:120,y:120},{x:600,y:120},{x:120,y:400},{x:600,y:400}] },
    F2: { type:'footing', pts:[{x:300,y:120},{x:480,y:120},{x:300,y:400},{x:480,y:400}] },
    // ── เสา ──
    C1: { type:'column', pts:[
      {x:120,y:120},{x:300,y:120},{x:480,y:120},{x:600,y:120},
      {x:120,y:250},{x:600,y:250},
      {x:120,y:400},{x:300,y:400},{x:480,y:400},{x:600,y:400}
    ]},
    C2: { type:'column', pts:[{x:300,y:250},{x:480,y:250}] },
    // ── คาน ──
    GB1: { type:'beam', segs:[
      {x1:120,y1:250,x2:600,y2:250},
      {x1:120,y1:400,x2:600,y2:400},
    ]},
    B2: { type:'beam', segs:[
      {x1:120,y1:120,x2:600,y2:120},
      {x1:120,y1:250,x2:600,y2:250},
    ]},
    RB3: { type:'beam', segs:[
      {x1:120,y1:120,x2:600,y2:120},
    ]},
    // ── พื้น ──
    S1: { type:'slab', rect:{x:120,y:255,w:480,h:145} },
    S2: { type:'slab', rect:{x:120,y:125,w:480,h:125} },
    // ── บันได ──
    ST1: { type:'stair', rect:{x:355,y:190,w:95,h:160} },
    // ── หลังคา ──
    RF1: { type:'roof', rect:{x:115,y:115,w:490,h:295} },
  };

  // แปลงรหัสจาก row (เช่น "C1-CON", "C1-RB") → base code ใน HL (เช่น "C1")
  const base = highlightCode
    ? (Object.keys(HL)
        .sort((a,b) => b.length - a.length)   // match longest key first (e.g. "GB1" before "B1")
        .find(k =>
          highlightCode === k ||
          (highlightCode.startsWith(k) && highlightCode[k.length] === '-')
        ) || null)
    : null;
  // ── Fallback ตามหมวดงาน ────────────────────────────────────────
  // ถ้าหารหัสตรงใน HL ไม่เจอ (เช่น AI ส่งรหัส F3/C5/B7 ที่ไม่มีในแบบสาธิต)
  // ให้ไฮไลท์ "สมาชิกทั้งหมวด" แทน เพื่อให้ผู้ใช้เห็นตำแหน่งโดยประมาณเสมอ
  const CAT_FALLBACK = {
    'ฐานราก': { type:'footing', pts:[
      {x:120,y:120},{x:300,y:120},{x:480,y:120},{x:600,y:120},
      {x:120,y:250},{x:600,y:250},
      {x:120,y:400},{x:300,y:400},{x:480,y:400},{x:600,y:400},
    ]},
    'เสา': { type:'column', pts:[
      {x:120,y:120},{x:300,y:120},{x:480,y:120},{x:600,y:120},
      {x:120,y:250},{x:300,y:250},{x:480,y:250},{x:600,y:250},
      {x:120,y:400},{x:300,y:400},{x:480,y:400},{x:600,y:400},
    ]},
    'คาน': { type:'beam', segs:[
      {x1:120,y1:120,x2:600,y2:120},
      {x1:120,y1:250,x2:600,y2:250},
      {x1:120,y1:400,x2:600,y2:400},
    ]},
    'พื้น':   { type:'slab',  rect:{x:120,y:125,w:480,h:275} },
    'บันได':  { type:'stair', rect:{x:355,y:190,w:95,h:160} },
    'หลังคา': { type:'roof',  rect:{x:115,y:115,w:490,h:295} },
  };
  // approx = true เมื่อใช้ fallback (จะแสดง badge "≈ ตำแหน่งโดยประมาณ")
  const baseHl = base ? HL[base] : null;
  const approx = !baseHl && !!highlightCat && !!CAT_FALLBACK[highlightCat];
  const hl = baseHl || (approx ? CAT_FALLBACK[highlightCat] : null);
  // ป้ายโค้ดที่มุมซ้ายบน: ใช้ base ถ้าเจอ ไม่งั้นใช้รหัสดิบที่คลิก (highlightCode)
  const badgeCode = base || (hl ? highlightCode : null);

  const OG  = '#f97316';        // orange-500
  const OGA = '#f9731628';      // orange transparent fill

  return (
    <svg width="720" height="540" viewBox="0 0 720 540" style={{display:'block'}}>
      <defs>
        {/* glow filter สำหรับ highlight */}
        <filter id="og-glow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="4" result="b"/>
          <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
        <pattern id="eg" width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M20 0H0V20" fill="none" stroke="#eef2f7" strokeWidth="1"/>
        </pattern>
      </defs>

      {/* พื้นหลัง */}
      <rect width="720" height="540" fill="#ffffff"/>
      <rect x="60" y="60" width="600" height="400" fill="url(#eg)"/>
      <rect x="60" y="60" width="600" height="400" fill="none" stroke="#cfd8e6" strokeWidth="1.5"/>

      {/* ── highlight: พื้น / หลังคา / บันได (วาดใต้ grid lines) ── */}
      {hl && (hl.type==='slab' || hl.type==='roof' || hl.type==='stair') && (
        <rect className="svg-hl"
          x={hl.rect.x} y={hl.rect.y} width={hl.rect.w} height={hl.rect.h}
          fill={OGA} stroke={OG} strokeWidth="2.5"
          strokeDasharray={hl.type==='stair' ? '0' : '8 4'} rx="3"/>
      )}

      {/* ── grid lines (vertical) ── */}
      {cols.map((x,i)=>(
        <g key={'c'+i}>
          <line x1={x} y1="42" x2={x} y2="470" stroke="#c2ccdb" strokeWidth="1" strokeDasharray="5 4"/>
          <circle cx={x} cy="34" r="13" fill="#fff" stroke="#9aa7bd" strokeWidth="1.3"/>
          <text x={x} y="39" textAnchor="middle" fontSize="13" fill="#5b6b80" fontFamily="monospace">{gx[i]}</text>
        </g>
      ))}
      {/* ── grid lines (horizontal) ── */}
      {ry.map((y,i)=>(
        <g key={'r'+i}>
          <line x1="48" y1={y} x2="652" y2={y} stroke="#c2ccdb" strokeWidth="1" strokeDasharray="5 4"/>
          <circle cx="40" cy={y} r="13" fill="#fff" stroke="#9aa7bd" strokeWidth="1.3"/>
          <text x="40" y={y+5} textAnchor="middle" fontSize="13" fill="#5b6b80" fontFamily="monospace">{gy[i]}</text>
        </g>
      ))}

      {/* ── beams ── */}
      {ry.map((y,ri)=> cols.slice(0,-1).map((x,ci)=>(
        <line key={'bh'+ri+ci} x1={x} y1={y} x2={cols[ci+1]} y2={y} stroke="#7c8aa3" strokeWidth="3"/>
      )))}
      {cols.map((x,ci)=> ry.slice(0,-1).map((y,ri)=>(
        <line key={'bv'+ci+ri} x1={x} y1={y} x2={x} y2={ry[ri+1]} stroke="#7c8aa3" strokeWidth="3"/>
      )))}

      {/* ── columns (สี่เหลี่ยมดำ ที่ทุก grid intersection) ── */}
      {cols.map((x)=> ry.map((y)=>(
        <rect key={'col'+x+y} x={x-9} y={y-9} width="18" height="18" fill="#0f1b2d"/>
      )))}

      {/* ── highlight: เสา (orange ring รอบ column square) ── */}
      {hl?.type==='column' && hl.pts.map((p,i)=>(
        <rect key={'hc'+i} className="svg-hl"
          x={p.x-18} y={p.y-18} width="36" height="36"
          fill={OGA} stroke={OG} strokeWidth="2.5" rx="5" filter="url(#og-glow)"/>
      ))}

      {/* ── highlight: ฐานราก (orange circle) ── */}
      {hl?.type==='footing' && hl.pts.map((p,i)=>(
        <circle key={'hf'+i} className="svg-hl"
          cx={p.x} cy={p.y} r="24"
          fill={OGA} stroke={OG} strokeWidth="2.5" filter="url(#og-glow)"/>
      ))}

      {/* ── highlight: คาน (วาดทับ beam จริงเพื่อให้เห็นชัด) ── */}
      {hl?.type==='beam' && hl.segs.map((s,i)=>(
        <line key={'hb'+i} className="svg-hl"
          x1={s.x1} y1={s.y1} x2={s.x2} y2={s.y2}
          stroke={OG} strokeWidth="12" strokeLinecap="round" filter="url(#og-glow)"/>
      ))}

      {/* ── code badge ที่มุมซ้ายบนของ drawing เมื่อมี highlight ── */}
      {badgeCode && (
        <g>
          <rect x="66" y="66" width={badgeCode.length*8+22} height="22" rx="4" fill={OG}/>
          <text x="77" y="81.5" fontSize="12" fill="#fff" fontFamily="monospace" fontWeight="bold">{badgeCode}</text>
          {approx && (
            <g>
              <rect x={66+badgeCode.length*8+28} y="66" width="118" height="22" rx="4" fill="#fff" stroke={OG} strokeWidth="1.3"/>
              <text x={66+badgeCode.length*8+36} y="81.5" fontSize="11" fill={OG} fontFamily="monospace">≈ ตำแหน่งโดยประมาณ</text>
            </g>
          )}
        </g>
      )}

      {/* ── dimension line ── */}
      <line x1="60" y1="495" x2="660" y2="495" stroke="#9aa7bd" strokeWidth="1"/>
      <text x="360" y="512" textAnchor="middle" fontSize="12" fill="#8a97a8" fontFamily="monospace">18.00 m</text>

      {/* ── title block ── */}
      <g>
        <rect x="470" y="468" width="190" height="62" fill="#f8fafc" stroke="#cfd8e6"/>
        <line x1="470" y1="490" x2="660" y2="490" stroke="#cfd8e6"/>
        <text x="480" y="483" fontSize="11" fill="#475569" fontFamily="monospace">โครงการ: อาคารพาณิชย์ 4 ชั้น</text>
        <text x="480" y="506" fontSize="10" fill="#8a97a8" fontFamily="monospace">แผ่น S-0{page}</text>
        <text x="480" y="521" fontSize="10" fill="#8a97a8" fontFamily="monospace">มาตราส่วน 1:100</text>
      </g>
    </svg>
  );
}
window.DrawingPlan = DrawingPlan;

/* ===================== Real PDF drawing viewer ===================== */
// แสดง "แบบจริง" ที่ผู้ใช้อัปโหลด (อยู่ใน Supabase Storage bucket `drawings`)
// ‼️ stored PDF = หน้าที่ Claude เห็นเป๊ะ → page (จาก page_num ของ AI) map ตรงกับหน้าใน PDF นี้
// ‼️ zoom = re-render จาก pdf.js ตามระดับซูม (vector re-rasterize = คมทุกระดับ ไม่แตก) +
//    canvas ขนาดจริง (displayW × zoom) → กล่อง layout โต → .viewer-stage เลื่อน pan ได้ (เลิกใช้ CSS transform)
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 SIGN_EDGE = 'https://zokzcjbvjcxfjpcjsegx.supabase.co/functions/v1/analyze-drawing';
const SIGN_PUB  = 'sb_publishable_nL-wFMwEzKss2HZOylspIA_9ypFMEWv';

// ขอ signed URL ของแบบ: ผ่าน Edge เป็นหลัก · พลาดค่อย fallback client
//   ถัง drawings เป็น private (migration 0005) → ทั้งสองทางได้ลิงก์เฉพาะไฟล์ของบัญชีนี้ (หรือ admin)
async function fetchSignedUrl(storagePath){
  // 0) แบบของโปรเจกต์ตัวอย่าง (data.jsx DEMO_PROJECT) = ไฟล์สาธารณะในเว็บ (demo/…) ไม่ได้อยู่ในถัง → ใช้ลิงก์ตรง
  //    ไฟล์ในถังเป็น "<projectId>/<เวลา>_<ชื่อ>" หรือ "<เวลา>_<ชื่อ>" เสมอ → ไม่ชนกับ demo/
  if(/^demo\/[\w.-]+\.pdf$/.test(String(storagePath||''))) return new URL(storagePath, document.baseURI).href;
  // 1) Edge endpoint action=sign_url (เซ็นในนามผู้ใช้ · RLS ของถังตัดสินสิทธิ์)
  try{
    const token = window.getAccessTokenFast ? await window.getAccessTokenFast() : null;
    if(token){
      const res = await fetch(SIGN_EDGE, {
        method:'POST',
        headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer '+token, 'apikey':SIGN_PUB },
        body: JSON.stringify({ action:'sign_url', storagePath })
      });
      if(res.ok){ const j = await res.json(); if(j && j.signedUrl) return j.signedUrl; }
    }
  }catch(e){ /* ตกไป fallback ด้านล่าง */ }
  // 2) fallback: client createSignedUrl (policy drawings_obj_select ให้เจ้าของไฟล์/admin อ่าน)
  if(window.supabase && window.supabase.storage){
    const { data, error } = await window.supabase.storage.from('drawings').createSignedUrl(storagePath, 3600);
    if(!error && data && data.signedUrl) return data.signedUrl;
    throw new Error('ขอลิงก์ไฟล์แบบไม่ได้ ('+((error&&error.message)||'endpoint+RLS ไม่ผ่าน')+')');
  }
  throw new Error('ขอลิงก์ไฟล์แบบไม่ได้');
}

// โหลดสคริปต์ครั้งเดียว (loadScript ใน screen_upload เป็น local ของคอมโพเนนต์นั้น — ตัวนี้ใช้ในหน้าผลลัพธ์)
const _sbScriptCache = {};
function sbLoadScript(src){
  if(_sbScriptCache[src]) return _sbScriptCache[src];
  _sbScriptCache[src] = new Promise((resolve,reject)=>{
    const el = document.createElement('script');
    el.src = src; el.async = true;
    el.onload = ()=>resolve();
    el.onerror = ()=>{ delete _sbScriptCache[src]; reject(new Error('โหลดสคริปต์ไม่ได้: '+src)); };
    document.head.appendChild(el);
  });
  return _sbScriptCache[src];
}

function PdfDrawing({ storagePath, page, zoom, stageRef, onNumPages, onError, marks, highlightCode, onMarkClick }){
  const canvasRef = useRef(null);
  const docRef    = useRef(null);
  const taskRef   = useRef(null);
  const [status,setStatus] = useState('loading');   // loading | ready | error
  const [errMsg,setErrMsg] = useState('');
  const [dispSize,setDispSize] = useState({w:0,h:0});   // ขนาดที่แสดงจริง (px) → ใช้วาง overlay marker (พิกัด normalize × ขนาดนี้)

  // ── โหลดเอกสาร: signed URL → pdf.js getDocument (เมื่อ storagePath เปลี่ยน) ──
  useEffect(()=>{
    let cancelled = false;
    docRef.current = null;
    setStatus('loading'); setErrMsg('');
    (async()=>{
      try{
        if(!storagePath) throw new Error('ไม่มีไฟล์แบบสำหรับโปรเจกต์นี้');
        // 1) ขอลิงก์ชั่วคราว (Edge service role → ข้าม RLS · fallback client)
        const signedUrl = await fetchSignedUrl(storagePath);
        // 2) โหลด pdf.js (ถ้ายังไม่มี)
        if(!window.pdfjsLib) await sbLoadScript(PDFJS_SRC);
        const pdfjsLib = window.pdfjsLib;
        if(!pdfjsLib) throw new Error('โหลดตัวอ่าน PDF (pdf.js) ไม่ได้');
        pdfjsLib.GlobalWorkerOptions.workerSrc = PDFJS_WORKER;
        // 3) เปิดเอกสาร
        const doc = await pdfjsLib.getDocument({ url: signedUrl, isEvalSupported: false }).promise; // isEvalSupported:false = ปิดช่องโหว่ CVE-2024-4367 ของ pdf.js 3.x (ฟอนต์ใน PDF สั่งรันโค้ดได้)
        if(cancelled){ try{ doc.destroy&&doc.destroy(); }catch(e){} return; }
        docRef.current = doc;
        onNumPages && onNumPages(doc.numPages);
        setStatus('ready');
      }catch(e){
        if(cancelled) return;
        setStatus('error'); setErrMsg(e.message||String(e));
        onError && onError(e);
      }
    })();
    return ()=>{ cancelled = true; };
  },[storagePath]);

  // ── ความกว้าง stage (px) — เปลี่ยนเมื่อสลับโหมดแบบ/ตาราง · ลากเส้นกลาง · ย่อขยายหน้าต่าง ──
  // ‼️ เดิมอ่าน clientWidth เฉพาะตอน "เปลี่ยนหน้า/ซูม" → สลับเป็นโหมดแบบเต็มจอแล้วแบบยังเป็นขนาดเก่า (ไม่เติมกรอบ)
  const [stageW,setStageW] = useState(0);
  React.useLayoutEffect(()=>{
    const el = (stageRef && stageRef.current) || (canvasRef.current && canvasRef.current.closest('.viewer-stage'));
    if(!el) return;
    setStageW(el.clientWidth);
    if(typeof ResizeObserver==='undefined') return;
    const ro = new ResizeObserver(()=>setStageW(el.clientWidth));
    ro.observe(el);
    return ()=>ro.disconnect();
  },[]);
  // ความกว้างที่แสดงจริง = (ความกว้าง stage − padding 60) × zoom (กล่องโตจริง → เลื่อน pan ได้)
  const displayW = Math.max(320, (stageW || 760) - 60) * (Number(zoom)||1);

  // ── ซูมแล้ว "ยืดภาพเดิมทันที" (ขนาด CSS) → รู้สึกว่าตอบสนองเลย · ค่อยเรนเดอร์ใหม่ให้คมตามหลัง (ด้านล่าง) ──
  React.useLayoutEffect(()=>{
    const canvas = canvasRef.current;
    if(status!=='ready' || !canvas) return;
    canvas.style.width  = Math.round(displayW) + 'px';
    canvas.style.height = 'auto';
    if(canvas.width>0) setDispSize({ w: Math.round(displayW), h: Math.round(displayW * canvas.height / canvas.width) });
  },[status, displayW]);

  // ── เรนเดอร์หน้า (ความละเอียดตามระดับซูม) เมื่อพร้อม / เปลี่ยนหน้า / เปลี่ยนซูม / ความกว้างเปลี่ยน ──
  // ‼️ วาดลง canvas นอกจอก่อน แล้วค่อย copy ลง canvas จริงทีเดียว — เดิมตั้ง canvas.width ก่อนวาด = ล้างภาพว่างทุกครั้งที่ซูม (กะพริบ/หาย)
  useEffect(()=>{
    if(status!=='ready' || !docRef.current) return;
    let cancelled = false;
    const t = setTimeout(async ()=>{      // debounce กันเรนเดอร์ถี่ตอนกดซูมรัว/ลากเส้นกลาง
      const doc = docRef.current;
      const pnum = Math.min(Math.max(1, Number(page)||1), doc.numPages);
      let pdfPage;
      try{ pdfPage = await doc.getPage(pnum); }catch(e){ return; }
      if(cancelled) return;
      const canvas = canvasRef.current; if(!canvas) return;
      const vp1 = pdfPage.getViewport({scale:1});
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      let renderScale = (displayW / vp1.width) * dpr;      // internal res = คมตามระดับซูม
      const MAX_CW = 6000;                                  // เพดาน canvas กันหน่วยความจำบานตอนซูมสูง
      if(displayW * dpr > MAX_CW) renderScale = MAX_CW / vp1.width;
      const vp = pdfPage.getViewport({scale:renderScale});
      const off = document.createElement('canvas');
      off.width  = Math.floor(vp.width);
      off.height = Math.floor(vp.height);
      if(taskRef.current){ try{ taskRef.current.cancel(); }catch(e){} }
      const task = pdfPage.render({ canvasContext: off.getContext('2d'), viewport: vp });
      taskRef.current = task;
      try{ await task.promise; }catch(e){ return; /* ถูก cancel = ปกติ */ }
      if(cancelled) return;
      const cv = canvasRef.current; if(!cv) return;
      cv.width = off.width; cv.height = off.height;          // ตั้งขนาด+วาดต่อกันใน task เดียว → ไม่มีเฟรมว่างคั่น
      cv.getContext('2d').drawImage(off, 0, 0);
      cv.style.width  = Math.round(displayW) + 'px';
      cv.style.height = 'auto';
      // บอกขนาดจริงที่แสดงให้ชั้น overlay (สูง = กว้าง × อัตราส่วนหน้า) → marker ตามซูมเป๊ะ
      setDispSize({ w: Math.round(displayW), h: Math.round(displayW * off.height / off.width) });
    }, 110);
    return ()=>{ cancelled = true; clearTimeout(t); if(taskRef.current){ try{ taskRef.current.cancel(); }catch(e){} } };
  },[status, page, displayW]);

  if(status==='error'){
    return (
      <div style={{width:360,padding:'44px 24px',textAlign:'center',color:'var(--ink-3)'}}>
        <div style={{fontSize:15,fontWeight:600,marginBottom:8,color:'var(--ink-2)'}}>แสดงแบบจริงไม่ได้</div>
        <div style={{fontSize:13,lineHeight:1.6}}>{errMsg}</div>
      </div>
    );
  }
  return (
    <div style={{position:'relative',minWidth:320}}>
      {status==='loading' && (
        <div style={{width:360,padding:'44px 24px',textAlign:'center',color:'var(--ink-3)',fontSize:13}}>กำลังโหลดแบบจริง…</div>
      )}
      <canvas ref={canvasRef} style={{display:status==='ready'?'block':'none',background:'#fff'}}/>
      {status==='ready' && dispSize.w>0 && marks && marks.length>0 && (
        <svg className="pdf-ov" width={dispSize.w} height={dispSize.h} viewBox={`0 0 ${dispSize.w} ${dispSize.h}`}
          style={{position:'absolute',left:0,top:0}}>
          {marks.map((mk,i)=>{
            const x = (Number(mk.nx)||0)*dispSize.w, y = (Number(mk.ny)||0)*dispSize.h;
            const hl = highlightCode && (String(mk.code)===String(highlightCode) || (Array.isArray(mk.codes) && mk.codes.map(String).includes(String(highlightCode))));
            const fs = Math.max(10, dispSize.w/140);
            const click = onMarkClick ? (e)=>{ e.stopPropagation(); onMarkClick(mk); } : undefined;
            if(mk.type==='text'){
              const w=(Number(mk.w)||0)*dispSize.w, h=(Number(mk.h)||0)*dispSize.h;
              return (
                <g key={i} className={'ov-mark ov-text'+(hl?' hl':'')} onClick={click}>
                  <rect x={x} y={y} width={w} height={h} rx={3}/>
                  <text x={x+w+3} y={y+h/2+fs*0.35} fontSize={fs}>{mk.code}</text>
                </g>
              );
            }
            // กรอบขนาดเท่าของจริงที่ AI นับ (งานสุขาภิบาล · item_marks): nx/ny = มุมซ้ายบน · nw/nh = กว้าง/สูง (สัดส่วนหน้า)
            if(mk.type==='box'){
              const w=Math.max(4,(Number(mk.nw)||0)*dispSize.w), h=Math.max(4,(Number(mk.nh)||0)*dispSize.h);
              // mk.dash = ช่องที่ควรดูซ้ำ (grid-marks.jsx: ไม่มีป้าย/หลายป้ายในช่อง)
              // mk.fillOpacity = ทึบกว่าปกติ (grid-marks: พื้น/ฐานราก 0.35 ตามภาพตัวอย่างเจ้าของ)
              const bst = (mk.color && !hl) ? { stroke: mk.color, fill: mk.color, fillOpacity: mk.fillOpacity ?? 0.14, strokeDasharray: mk.dash ? '6 4' : undefined }
                : (mk.dash ? { strokeDasharray: '6 4' } : undefined);
              const tst = (mk.color && !hl) ? { fill: mk.color } : undefined;
              return (
                <g key={i} className={'ov-mark ov-box'+(hl?' hl':'')+(mk.quiet?' quiet':'')} onClick={click}>
                  {mk.quiet && <title>{mk.label || mk.code}</title>}
                  <rect x={x} y={y} width={w} height={h} rx={2} style={bst}/>
                  <text x={x} y={y-4} fontSize={fs} style={tst}>{mk.label || mk.code}</text>
                </g>
              );
            }
            // mk.nr = รัศมีเป็นสัดส่วนความกว้างหน้า (grid-marks: วงรอบป้ายเสาในแบบ ขนาดตามตัวอักษร)
            const r = mk.nr ? Math.max(5, mk.nr*dispSize.w) : Math.max(7, dispSize.w/150);
            // mk.color / mk.label (ไม่บังคับ): marker งานไฟฟ้าแยกสีตามแถว Legend (elec-marks.jsx) · ไม่มี = สไตล์เดิมจาก CSS
            const cst = (mk.color && !hl) ? { stroke: mk.color, fill: mk.color, fillOpacity: mk.fillOpacity ?? 0.16 } : undefined;
            const tst = (mk.color && !hl) ? { fill: mk.color } : undefined;
            return (
              <g key={i} className={'ov-mark ov-circle'+(hl?' hl':'')+(mk.quiet?' quiet':'')} onClick={click}>
                {mk.quiet && <title>{mk.label || mk.code}</title>}
                <circle cx={x} cy={y} r={r} style={cst}/>
                <text x={x+r+3} y={y+r*0.6} fontSize={fs} style={tst}>{mk.label || mk.code}</text>
              </g>
            );
          })}
        </svg>
      )}
    </div>
  );
}
window.PdfDrawing = PdfDrawing;
// export helper ให้โมดูลอื่น (ocr-overlay.jsx) reuse — ขอ signed URL + โหลดสคริปต์ครั้งเดียว
window.fetchSignedUrl = window.fetchSignedUrl || fetchSignedUrl;
window.sbLoadScript   = window.sbLoadScript   || sbLoadScript;
