/**
 * HR V1 — 정통 그리드 (정보 밀도 高)
 * Row1  6 KPI
 * Row2  인건비 트렌드 · 부서별 도넛 · 공지사항 등록
 * Row3  4개 알림 스택  (결근·지각 / 근무수정 / 공지 / 비품)
 * Row4  금일 배송 스케줄 — 기사별 노선 진행률
 */
const HrDashboardV1 = () => {
  const [branch, setBranch] = React.useState('all');
  const [target, setTarget] = React.useState('전사');
  const [noticeType, setNoticeType] = React.useState('공지');
  const [draft, setDraft] = React.useState('');
  const D = HR_DATA;
  const fmtMoney = n => '₩' + Math.round(n/10000).toLocaleString() + '만';

  return <HrShell
    headline="HR 대시보드"
    subtitle={`${D.asOf} 목요일 · 전체 ${D.total}명 · 처리할 일 ${D.pendingApprovals}건`}
    branch={branch} setBranch={setBranch}>
    <div style={{ padding:'18px 28px 28px', display:'flex', flexDirection:'column', gap:14 }}>

      {/* ── Row 1: 6 KPI ───────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(6,1fr)', gap:12 }}>
        <KpiCard label="전체 직원" value={D.total} unit="명" sub={{ text:'6개 지점 · 4개 직군', color:C.fg3 }} color={C.primary}/>
        <KpiCard label="오늘 출근율" value={D.todayRate} unit="%" sub={{ text:`출근 ${D.todayPresent} · 지각 ${D.todayLate} · 결근 ${D.todayAbsent}`, color: D.todayAbsent>1?C.danger:C.fg3 }} color={C.info}/>
        <KpiCard label="신규 입사" value={D.newJoinThisMonth} unit="명" sub={{ text:'5월 · 수습 2명', color:C.fg3 }} color={C.violet}/>
        <KpiCard label="퇴사" value={D.leaveThisMonth} unit="명" sub={{ text:'5월 · 안정적', color:C.primary }} color={C.fg3}/>
        <KpiCard label="미처리 승인" value={D.pendingApprovals} unit="건" sub={{ text:'근무수정·연차·비품', color:C.warning }} color={C.warning}/>
        <KpiCard label="이달 지각·결근" value={D.monthLateAbsent} unit="건" sub={{ text:'전월 12건', color:C.danger }} color={C.danger}/>
      </div>

      {/* ── Row 2: 인건비 트렌드 · 도넛 · 공지사항 등록 ─── */}
      <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr 1.4fr', gap:14 }}>

        {/* 인건비 트렌드 */}
        <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, padding:'18px 20px 14px' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12 }}>
            <div>
              <div style={{ fontSize:12, fontWeight:700, color:C.fg3 }}>이번달 인건비</div>
              <div style={{ display:'flex', alignItems:'baseline', gap:8, marginTop:4 }}>
                <span style={{ fontSize:22, fontWeight:900, color:C.fg1 }}>{fmtMoney(D.payroll.thisMonth)}</span>
                <TrendBadge value={D.payroll.diff}/>
              </div>
            </div>
            <span style={{ fontSize:10, color:C.fg4, fontWeight:600 }}>최근 15일 추이</span>
          </div>
          <LineChart data={D.payroll.daily} color={C.info}/>
        </div>

        {/* 부서별 인건비 도넛 */}
        <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, padding:'18px 20px' }}>
          <div style={{ fontSize:12, fontWeight:700, color:C.fg3, marginBottom:12 }}>부서별 인건비</div>
          <div style={{ display:'flex', alignItems:'center', gap:14 }}>
            <DonutChart data={D.payroll.byDept} size={120} thickness={20}/>
            <div style={{ flex:1, display:'flex', flexDirection:'column', gap:6 }}>
              {D.payroll.byDept.map((d,i)=>(
                <div key={i} style={{ display:'flex', alignItems:'center', gap:6 }}>
                  <span style={{ width:8, height:8, borderRadius:2, background:d.color }}/>
                  <span style={{ flex:1, fontSize:11, color:C.fg2, fontWeight:600 }}>{d.name}</span>
                  <span style={{ fontSize:11, color:C.fg1, fontWeight:800, fontVariantNumeric:'tabular-nums' }}>{d.ratio}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* 공지사항 등록 */}
        <NoticeComposer
          target={target} setTarget={setTarget}
          noticeType={noticeType} setNoticeType={setNoticeType}
          draft={draft} setDraft={setDraft}
          notices={D.notices}/>
      </div>

      {/* ── Row 3: 3개 알림 스택 ──────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12, height:280 }}>
        <HrAlertStack alertKey="absentLate"    items={D.alerts.absentLate}/>
        <HrAlertStack alertKey="scheduleEdit"  items={D.alerts.scheduleEdit}/>
        <HrAlertStack alertKey="supplyRequest" items={D.alerts.supplyRequest}/>
      </div>

      {/* ── Row 4: 금일 출근 스케줄 ──────────────── */}
      <TodayAttendancePanel data={D.todayAttendance}/>

    </div>
  </HrShell>;
};

/* ─── 공지사항 등록 패널 ───────────────────────── */
const NoticeComposer = ({ target, setTarget, noticeType, setNoticeType, draft, setDraft, notices }) => {
  const targets = ['전사','조리팀','배송팀','사무직','파트타임','강서점','강북점','마포점'];
  const types   = [
    { key:'공지', color:C.violet, bg:C.violet50 },
    { key:'안내', color:C.info,   bg:C.info50   },
    { key:'긴급', color:C.danger, bg:C.danger50 },
  ];
  const t = types.find(x=>x.key===noticeType) || types[0];

  return (
    <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, padding:'14px 16px', display:'flex', flexDirection:'column', gap:10 }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
          <span style={{ fontSize:13, fontWeight:800, color:C.fg1 }}>📢 공지사항 등록</span>
        </div>
        <div style={{ display:'flex', gap:4, background:'#f1f5f9', padding:2, borderRadius:7 }}>
          {types.map(x => (
            <button key={x.key} onClick={()=>setNoticeType(x.key)} style={{
              padding:'3px 10px', fontSize:10, fontWeight:800,
              color: noticeType===x.key ? x.color : C.fg3,
              background: noticeType===x.key ? '#fff' : 'transparent',
              border:'none', borderRadius:5,
              boxShadow: noticeType===x.key ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
              cursor:'pointer',
            }}>{x.key}</button>
          ))}
        </div>
      </div>

      {/* 대상 + 입력 */}
      <div style={{ display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
        <span style={{ fontSize:10, fontWeight:700, color:C.fg4 }}>대상</span>
        {targets.slice(0,5).map(g => (
          <button key={g} onClick={()=>setTarget(g)} style={{
            padding:'3px 9px', fontSize:10, fontWeight:700,
            color: target===g ? '#fff' : C.fg2,
            background: target===g ? C.fg1 : '#f8fafc',
            border:`1px solid ${target===g ? C.fg1 : C.border}`,
            borderRadius:10, cursor:'pointer',
          }}>{g}</button>
        ))}
        <select value={target} onChange={e=>setTarget(e.target.value)} style={{
          fontSize:10, padding:'3px 6px', border:`1px solid ${C.border}`, borderRadius:5,
          color:C.fg2, background:'#fff', fontWeight:600,
        }}>
          {targets.map(g => <option key={g} value={g}>{g}</option>)}
        </select>
      </div>

      <textarea
        value={draft} onChange={e=>setDraft(e.target.value)}
        placeholder={`${target}에게 보낼 ${noticeType} 내용을 입력하세요…  (예: 5/30 19:00 회식 안내)`}
        style={{
          flex:1, minHeight:64, resize:'none',
          fontSize:12, lineHeight:1.5, padding:'8px 10px',
          border:`1px solid ${C.border}`, borderRadius:8,
          color:C.fg1, background:'#fafbfc', fontFamily:'inherit', outline:'none',
        }}/>

      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div style={{ display:'flex', gap:8, fontSize:10, color:C.fg4 }}>
          <label style={{ display:'flex', alignItems:'center', gap:3, cursor:'pointer' }}>
            <input type="checkbox" defaultChecked style={{ accentColor:C.primary, transform:'scale(0.9)' }}/> 카카오톡 알림
          </label>
          <label style={{ display:'flex', alignItems:'center', gap:3, cursor:'pointer' }}>
            <input type="checkbox" style={{ accentColor:C.primary, transform:'scale(0.9)' }}/> 상단 고정
          </label>
        </div>
        <div style={{ display:'flex', gap:6 }}>
          <button style={{
            padding:'5px 10px', fontSize:11, fontWeight:700, color:C.fg3,
            background:'#fff', border:`1px solid ${C.border}`, borderRadius:6, cursor:'pointer',
          }}>예약</button>
          <button style={{
            padding:'5px 12px', fontSize:11, fontWeight:800, color:'#fff',
            background:t.color, border:`1px solid ${t.color}`, borderRadius:6, cursor:'pointer',
            boxShadow:`0 1px 0 ${t.color}33`,
          }}>등록</button>
        </div>
      </div>

      {/* 최근 공지 미리보기 */}
      <div style={{ borderTop:`1px dashed ${C.borderL}`, paddingTop:8, display:'flex', flexDirection:'column', gap:4 }}>
        <div style={{ fontSize:9, fontWeight:700, color:C.fg4, letterSpacing:0.4, textTransform:'uppercase', marginBottom:2 }}>RECENT</div>
        {notices.slice(0,2).map((n,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:6, fontSize:11 }}>
            <span style={{
              fontSize:9, fontWeight:800, padding:'1px 5px', borderRadius:3,
              color:C.violet, background:C.violet50,
            }}>{n.target}</span>
            <span style={{ flex:1, color:C.fg2, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{n.title}</span>
            <span style={{ fontSize:10, color:C.fg4 }}>{n.at}</span>
            <span style={{ fontSize:10, color:C.fg4, fontVariantNumeric:'tabular-nums' }}>👁 {n.views}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ─── 금일 출근 스케줄 패널 ─────────────────── */
const TodayAttendancePanel = ({ data }) => {
  const [filter, setFilter] = React.useState('all');

  const STATUS = {
    in:     { label:'근무중', color:C.info,    bg:C.info50,    barColor:C.info    },
    done:   { label:'퇴근',   color:C.primary, bg:C.primary50, barColor:C.primary },
    late:   { label:'지각',   color:C.warning, bg:C.warning50, barColor:C.warning },
    absent: { label:'결근',   color:C.danger,  bg:C.danger50,  barColor:C.danger  },
    leave:  { label:'연차',   color:C.violet,  bg:C.violet50,  barColor:C.violet  },
    off:    { label:'휴무',   color:C.fg4,     bg:'#f1f5f9',   barColor:C.fg4     },
    wait:   { label:'예정',   color:C.fg4,     bg:'#f1f5f9',   barColor:C.fg4     },
  };

  const counts = data.reduce((a,r)=>{ a[r.status]=(a[r.status]||0)+1; return a; }, {});

  const tabs = [
    { key:'all',   label:'전체',  count:data.length, color:C.fg1 },
    { key:'in',    label:'근무중', count:counts.in||0,    color:C.info },
    { key:'late',  label:'지각',  count:counts.late||0,  color:C.warning },
    { key:'absent',label:'결근',  count:counts.absent||0,color:C.danger },
    { key:'leave', label:'연차',  count:counts.leave||0, color:C.violet },
    { key:'done',  label:'퇴근',  count:counts.done||0,  color:C.primary },
  ];

  // 시프트("06:00 – 15:00") 파싱 → 분
  const parseShift = (s) => {
    const m = (s||'').match(/(\d{2}):(\d{2})\s*[–-]\s*(\d{2}):(\d{2})/);
    if (!m) return null;
    return { startMin:+m[1]*60 + +m[2], endMin:+m[3]*60 + +m[4] };
  };
  const NOW_MIN = 9*60 + 30; // 09:30 (asOf 기준)

  const filtered = filter==='all' ? data : data.filter(r => r.status===filter);

  return (
    <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, overflow:'hidden' }}>
      {/* 헤더 */}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 18px', borderBottom:`1px solid ${C.borderL}`, gap:12, flexWrap:'wrap' }}>
        <div style={{ display:'flex', alignItems:'baseline', gap:10 }}>
          <span style={{ fontSize:14, fontWeight:800, color:C.fg1 }}>🕘 금일 출근 스케줄</span>
          <span style={{ fontSize:11, color:C.fg4 }}>5/15 목요일 09:30 기준 · {data.length}명</span>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:4 }}>
          {tabs.map(t => {
            const on = filter===t.key;
            return (
              <button key={t.key} onClick={()=>setFilter(t.key)} style={{
                padding:'4px 10px', fontSize:11, fontWeight:on?800:700,
                color: on ? '#fff' : t.color,
                background: on ? t.color : (t.color==='#0f172a' ? '#fff' : '#fff'),
                border:`1px solid ${on?t.color:C.border}`,
                borderRadius:14, cursor:'pointer', display:'inline-flex', alignItems:'center', gap:5,
              }}>
                {t.label}
                <span style={{ fontSize:10, fontWeight:800, opacity: on?0.85:0.6 }}>{t.count}</span>
              </button>
            );
          })}
          <a style={{ fontSize:11, color:C.primary, fontWeight:700, textDecoration:'none', cursor:'pointer', marginLeft:6 }}>스케줄 관리 →</a>
        </div>
      </div>

      {/* 컬럼 헤더 */}
      <div style={{ display:'grid', gridTemplateColumns:'180px 60px 110px 130px 1fr 88px', gap:12, padding:'8px 18px', background:'#fafbfc', borderBottom:`1px solid ${C.borderL}`, fontSize:10, fontWeight:700, color:C.fg4, letterSpacing:0.3, textTransform:'uppercase' }}>
        <span>직원</span>
        <span>지점</span>
        <span>근무 시프트</span>
        <span>출근 / 퇴근</span>
        <span>진행 · 비고</span>
        <span style={{ textAlign:'right' }}>상태</span>
      </div>

      {/* 행 */}
      <div style={{ maxHeight:360, overflowY:'auto' }}>
        {filtered.map((r,i)=>{
          const s = STATUS[r.status];
          const sh = parseShift(r.shift);
          let pct = 0;
          if (sh) {
            if (r.status==='done')      pct = 100;
            else if (r.status==='in' || r.status==='late') {
              pct = Math.max(0, Math.min(100, Math.round((NOW_MIN - sh.startMin) / (sh.endMin - sh.startMin) * 100)));
            }
          }
          return (
            <div key={i} style={{
              display:'grid', gridTemplateColumns:'180px 60px 110px 130px 1fr 88px', gap:12,
              padding:'10px 18px', alignItems:'center',
              borderBottom: i<filtered.length-1 ? `1px solid ${C.borderL}` : 'none',
              background: (r.status==='absent' || r.status==='late') ? '#fffafa' : '#fff',
            }}>
              {/* 직원 */}
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <Avatar name={r.name} dept={r.dept} size={28}/>
                <div style={{ display:'flex', flexDirection:'column', gap:1 }}>
                  <span style={{ fontSize:12, fontWeight:800, color:C.fg1 }}>{r.name}</span>
                  <DeptBadge dept={r.dept} size="sm"/>
                </div>
              </div>

              {/* 지점 */}
              <span style={{ fontSize:11, color:C.fg2, fontWeight:600 }}>{r.branch}</span>

              {/* 시프트 */}
              <span style={{ fontSize:11, fontWeight:700, color: r.shift==='연차'?C.violet:C.fg2, fontVariantNumeric:'tabular-nums' }}>{r.shift}</span>

              {/* 출퇴근 */}
              <div style={{ display:'flex', flexDirection:'column', gap:1, fontVariantNumeric:'tabular-nums' }}>
                <span style={{ fontSize:11, color:C.fg2 }}>
                  <span style={{ color:C.fg4, fontSize:10 }}>IN </span>
                  <b style={{ color: r.status==='late'?C.warning : r.clockIn?C.fg1:C.fg4 }}>{r.clockIn || '—'}</b>
                </span>
                <span style={{ fontSize:11, color:C.fg2 }}>
                  <span style={{ color:C.fg4, fontSize:10 }}>OUT </span>
                  <b style={{ color: r.clockOut?C.fg1:C.fg4 }}>{r.clockOut || '—'}</b>
                </span>
              </div>

              {/* 진행 + 비고 */}
              <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
                <span style={{ fontSize:11, color: r.status==='absent'?C.danger : r.status==='late'?C.warning : C.fg3, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                  {r.note || (r.status==='in' ? '정상 근무 중' : r.status==='done' ? '정시 퇴근' : r.status==='leave' ? '연차 사용' : '—')}
                </span>
                {sh && (r.status==='in' || r.status==='late' || r.status==='done') && (
                  <div style={{ height:5, borderRadius:3, background:'#f1f5f9', overflow:'hidden' }}>
                    <div style={{ width:`${pct}%`, height:'100%', background:s.barColor, transition:'width 0.4s' }}/>
                  </div>
                )}
              </div>

              {/* 상태 */}
              <div style={{ display:'flex', justifyContent:'flex-end' }}>
                <span style={{
                  fontSize:11, fontWeight:800, padding:'3px 10px', borderRadius:11,
                  color:s.color, background:s.bg, display:'inline-flex', alignItems:'center', gap:5,
                }}>
                  {r.status==='in' && <span style={{ width:6, height:6, borderRadius:'50%', background:s.color, animation:'pulse 1.4s ease-in-out infinite' }}/>}
                  {s.label}
                </span>
              </div>
            </div>
          );
        })}
      </div>

      <style>{`@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.35} }`}</style>
    </div>
  );
};

window.HrDashboardV1 = HrDashboardV1;
