/* ─── 템플릿 렌더러 (라이브러리에서 추가되는 카드들) ─── */
const templateRenderers = {
  'hr-mini': {
    name:'최근 입사자', icon:'📋', badge:'ERP · 인사/급여',
    sourceTable:'USER_INFO',
    w:280, h:280,
    body:()=>`
      <div class="w-list">
        <div class="li"><div class="ic">👤</div><div><div class="tt">최예린</div><div class="ds">개발팀 · 사원</div></div><div class="ts">2일 전</div></div>
        <div class="li"><div class="ic">👤</div><div><div class="tt">한도윤</div><div class="ds">영업팀 · 대리</div></div><div class="ts">1주 전</div></div>
        <div class="li"><div class="ic">👤</div><div><div class="tt">서민재</div><div class="ds">생산팀 · 사원</div></div><div class="ts">2주 전</div></div>
        <div class="li"><div class="ic">👤</div><div><div class="tt">윤지호</div><div class="ds">경영지원 · 사원</div></div><div class="ts">3주 전</div></div>
        <div class="li"><div class="ic">👤</div><div><div class="tt">조하늘</div><div class="ds">개발팀 · 대리</div></div><div class="ts">1개월 전</div></div>
      </div>`
  },
  'attendance': {
    name:'출퇴근 현황', icon:'⏰', badge:'ERP · 인사/급여',
    sourceTable:'USER_INFO',
    w:300, h:340,
    body:()=>{
      const days=['일','월','화','수','목','금','토'];
      let html='<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.6rem;"><div style="font-size:.8rem;font-weight:700;">2026년 4월</div><div style="font-size:.55rem;color:var(--text-muted);">오늘 출근 <b style="color:var(--green);font-size:.75rem;">119</b> / 128</div></div><div class="w-cal">';
      days.forEach(d=>html+=`<div class="cal-h">${d}</div>`);
      const hasDays=[2,5,7,10,15,17,22,28];
      const today=8;
      for(let i=1;i<=30;i++){
        let cls='cal-d';
        if(i===today)cls+=' today';
        else if(hasDays.includes(i))cls+=' has';
        html+=`<div class="${cls}">${i}</div>`;
      }
      html+='</div>';
      return html;
    }
  },
  'sales-kpi': {
    name:'매출 KPI', icon:'💰', badge:'대시보드 · 영업/CRM',
    sourceTable:'ORDER_MASTER',
    w:320, h:240,
    body:()=>`
      <div class="w-kpi">
        <div class="k"><div class="k-label">이번달 매출</div><div class="k-val">₩48.2M</div><div class="k-delta">↑ 12.4%</div></div>
        <div class="k"><div class="k-label">이번달 이익</div><div class="k-val">₩9.8M</div><div class="k-delta">↑ 8.1%</div></div>
        <div class="k"><div class="k-label">신규 주문</div><div class="k-val">312</div><div class="k-delta">↑ 23</div></div>
        <div class="k"><div class="k-label">신규 고객</div><div class="k-val">28</div><div class="k-delta down">↓ -3</div></div>
      </div>`
  },
  'sales-chart': {
    name:'월별 매출', icon:'📊', badge:'대시보드 · 기획/보고',
    sourceTable:'ORDER_MASTER',
    w:380, h:260,
    body:()=>{
      const months=['11월','12월','1월','2월','3월','4월'];
      const vals=[42,38,55,48,62,48];
      const colors=['','','cyan','','','pink'];
      const max=Math.max(...vals);
      let html='<div class="w-chart">';
      vals.forEach((v,i)=>html+=`<div class="bar ${colors[i]}" data-label="${months[i]}" style="height:${(v/max)*100}%"></div>`);
      html+='</div><div class="w-chart-legend"><div class="lg"><div class="dot"></div>일반</div><div class="lg"><div class="dot cyan"></div>최저</div><div class="lg"><div class="dot pink"></div>최고</div></div>';
      return html;
    }
  },
  'notifications': {
    name:'알림 센터', icon:'🔔', badge:'관리자',
    sourceTable:'AUDIT_LOG',
    w:300, h:280,
    body:()=>`
      <div class="w-list">
        <div class="li"><div class="ic" style="background:linear-gradient(135deg,rgba(255,71,87,.18),rgba(255,71,87,.05));">⚠</div><div><div class="tt">DTG-078 통신 오류</div><div class="ds">긴급 · 시스템</div></div><div class="ts">2분</div></div>
        <div class="li"><div class="ic" style="background:linear-gradient(135deg,rgba(253,203,110,.2),rgba(253,203,110,.05));">📋</div><div><div class="tt">3월 정산 보고서 검토</div><div class="ds">박부장</div></div><div class="ts">14분</div></div>
        <div class="li"><div class="ic">✅</div><div><div class="tt">결재 3건 승인됨</div><div class="ds">최부장</div></div><div class="ts">2시간</div></div>
        <div class="li"><div class="ic">💾</div><div><div class="tt">자동 백업 완료 (2.3GB)</div><div class="ds">시스템</div></div><div class="ts">3시간</div></div>
      </div>`
  },
  'hr-employee-list': {
    name:'인사정보 (풀)', icon:'👥', badge:'ERP · 인사/급여',
    w:600, h:420,
    body:()=>'<div style="padding:1rem;text-align:center;color:var(--text-muted);font-size:.7rem;line-height:1.6;">📋 큰 인사정보 카드는<br>이미 캔버스에 1개 있습니다.<br><br>실제 빌더에서는 같은 템플릿을 여러 개 추가해<br>다른 부서/조건으로 분리 가능합니다.</div>'
  }
};

/* ─── 카드 DOM 빌더 (공용) ─── */
function buildCardEl(templateId, opts){
  const t = templateRenderers[templateId];
  if(!t)return null;
  const card=document.createElement('div');
  card.className='tpl-card'+(opts.collapsed?' collapsed':'');
  card.id = opts.id || nextId();
  card.dataset.template = templateId;
  if(t.sourceTable) card.dataset.sourceTable = t.sourceTable;
  card.style.left = opts.left+'px';
  card.style.top = opts.top+'px';
  card.style.width = (opts.width||t.w)+'px';
  card.style.height = (opts.height||t.h)+'px';
  card.innerHTML=`
    <div class="tpl-head">
      <div class="tpl-head-l">
        <div class="tpl-head-icon">${t.icon}</div>
        <div class="tpl-head-title">${t.name}</div>
        <div class="tpl-head-bdg">${t.badge}</div>
      </div>
      <div class="tpl-head-r">
        <button class="tpl-head-btn" title="새로고침" onclick="toast('데이터 새로고침','info')"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></button>
        <button class="tpl-head-btn" title="접기/펴기" onclick="toggleCollapse(this)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg></button>
        <button class="tpl-head-btn danger" title="카드 삭제" onclick="removeCard(this)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
      </div>
    </div>
    <div class="resize-handle"></div>
    <div class="tpl-body">${t.body()}</div>`;
  return card;
}

/* ─── 라이브러리에서 카드 추가 (★ random 위치 — 완전 자유 배치) ─── */
function addCardFromLib(templateId){
  const t = templateRenderers[templateId];
  if(!t){toast('템플릿 정의를 찾을 수 없습니다','warn');return;}
  const cv=document.getElementById('canvas');
  // 캔버스 빈 영역 random — snap 없음, 픽셀 단위
  const cw = cv.clientWidth || 1100;
  const ch = cv.clientHeight || 700;
  const maxL = Math.max(40, cw - t.w - 40);
  const maxT = Math.max(40, ch - t.h - 40);
  const left = Math.round(20 + Math.random() * (maxL - 20));
  const top  = Math.round(20 + Math.random() * (maxT - 20));
  const card = buildCardEl(templateId, {left,top});
  if(!card)return;
  // 빈 placeholder 가 있으면 제거 (이전 버전 호환)
  cv.querySelector('.canvas-empty')?.remove();
  cv.appendChild(card);
  makeDraggable(card);
  makeResizable(card);
  applyClamp(card);
  // 편집 모드 자동 켜기
  if(!cv.classList.contains('edit-mode')){
    cv.classList.add('edit-mode');
    document.getElementById('btn-edit-mode').classList.add('on');
  }
  closeLib();
  toast(t.name+' 카드를 추가했습니다','success');
}

/* ─── 윈도우 리사이즈 시 모든 카드 clamp (debounced) ─── */
let _resizeT=null;
window.addEventListener('resize',()=>{
  clearTimeout(_resizeT);
  _resizeT=setTimeout(()=>{
    document.querySelectorAll('#canvas .tpl-card').forEach(c=>applyClamp(c));
  },100);
});

/* ─── 인사정보 검색 필터 ─── */
function filterHr(){
  const q=(document.getElementById('hr-search').value||'').trim().toLowerCase();
  const dept=document.getElementById('hr-dept').value;
  const status=document.getElementById('hr-status').value;
  const card=document.getElementById('card-hr-main');
  if(!card)return;
  let shown=0;
  card.querySelectorAll('.hr-table tbody tr').forEach(tr=>{
    const text=tr.innerText.toLowerCase();
    const trDept=tr.querySelector('.hr-dept')?.textContent||'';
    const trStatus=tr.querySelector('.hr-bdg')?.textContent||'';
    let ok=true;
    if(q&&!text.includes(q))ok=false;
    if(dept&&trDept!==dept)ok=false;
    if(status&&trStatus!==status)ok=false;
    tr.classList.toggle('filtered-out',!ok);
    if(ok)shown++;
  });
  // 페이지네이션 정보 업데이트
  const info=card.querySelector('.hr-pagi-info');
  if(info)info.textContent=`총 128명 · ${shown}건 표시 중`;
}
