/**
 * HR V2 — 타임라인 중심 (시간의 흐름으로 사고)
 * 오늘 출근 타임라인(시간축) + 통합 알림 피드(시간순) + 7일 인건비 스파크
 */
const HrDashboardV2 = () => {
  const [branch, setBranch] = React.useState('all');
  const D = HR_DATA;
  const fmtMoney = n => '₩' + Math.round(n/10000).toLocaleString() + '만';

  // 시간축 (05시 ~ 11시 — 출근 시간대)
  const HOUR_START = 5, HOUR_END = 11;
  const arrivedToTime = (s) => { if (!s) return null; const [h,m] = s.split(':').map(Number); return h + m/60; };
  const xFor = (t) => ((t - HOUR_START) / (HOUR_END - HOUR_START)) * 100;

  // 직원별 출근 점 (출근/지각만)
  const arrivals = EMPLOYEES.filter(e => e.arrival).map(e => ({...e, t: arrivedToTime(e.arrival)}));
  const absents  = EMPLOYEES.filter(e => e.today === '결근');
  const leaves   = EMPLOYEES.filter(e => e.today === '연차');

  // 통합 시간순 피드 (모든 알림 + 출근 이벤트 일부)
  const feed = [
    ...D.alerts.absentLate.map(a=>({...a, type:'absentLate', time:'09:30'})),
    ...D.alerts.payrollMissing.map(a=>({...a, type:'payrollMissing', time:'09:15'})),
    ...D.alerts.scheduleEdit.map(a=>({...a, type:'scheduleEdit', time:'08:50'})),
    ...D.alerts.supplyRequest.map(a=>({...a, type:'supplyRequest', time:'08:30'})),
    ...D.alerts.notice.map(a=>({...a, type:'notice', time:'08:00'})),
  ].sort((a,b)=>a.time<b.time?1:-1);

  return <HrShell
    headline="오늘 흐름 한눈에"
    subtitle={`${D.asOf} 목요일 · 06:00~10:30 출근 시간대 모니터링`}
    branch={branch} setBranch={setBranch}>
    <div style={{ padding:'18px 28px 28px', display:'flex', flexDirection:'column', gap:14 }}>

      {/* 상단 KPI 4개 (컴팩트) */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
        <KpiCard label="전체 직원" value={D.total} unit="명" sub="6개 지점" color={C.primary}/>
        <KpiCard label="오늘 출근율" value={D.todayRate} unit="%" sub={{ text:`결근 ${D.todayAbsent}건`, color:C.danger }} color={C.info}/>
        <KpiCard label="미처리 승인" value={D.pendingApprovals} unit="건" sub={{ text:'근무·연차·비품', color:C.warning }} color={C.warning}/>
        <KpiCard label="이달 인건비" value={fmtMoney(D.payroll.thisMonth).replace('₩','').replace('만','')} unit="만원" sub={<><span style={{ color:C.primary, fontWeight:700 }}>▲ {D.payroll.diff}%</span> <span style={{ color:C.fg4 }}>전월</span></>} color={C.violet}/>
      </div>

      {/* 오늘 출근 타임라인 (HERO) */}
      <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, padding:'18px 22px 16px' }}>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:14 }}>
          <div>
            <div style={{ fontSize:13, fontWeight:800, color:C.fg1 }}>오늘 출근 타임라인</div>
            <div style={{ fontSize:11, color:C.fg4, marginTop:2 }}>점 위에 마우스 올리면 직원 이름 · 좌→우 시간 흐름</div>
          </div>
          <div style={{ display:'flex', gap:14, fontSize:10, color:C.fg3, fontWeight:600 }}>
            <span style={{ display:'flex', alignItems:'center', gap:4 }}><span style={{ width:8, height:8, background:'#16a34a', borderRadius:'50%' }}/>정시 {arrivals.filter(a=>a.today==='출근').length}</span>
            <span style={{ display:'flex', alignItems:'center', gap:4 }}><span style={{ width:8, height:8, background:'#f59e0b', borderRadius:'50%' }}/>지각 {arrivals.filter(a=>a.today==='지각').length}</span>
            <span style={{ display:'flex', alignItems:'center', gap:4 }}><span style={{ width:8, height:8, background:'#dc2626', borderRadius:'50%' }}/>결근 {absents.length}</span>
            <span style={{ display:'flex', alignItems:'center', gap:4 }}><span style={{ width:8, height:8, background:'#cbd5e1', borderRadius:'50%' }}/>연차 {leaves.length}</span>
          </div>
        </div>

        {/* 시간 축 */}
        <div style={{ position:'relative', height:120, marginBottom:8 }}>
          {/* 시간 그리드 */}
          {Array.from({length: HOUR_END - HOUR_START + 1}).map((_,i)=> {
            const h = HOUR_START + i;
            const isFocus = h===6 || h===9;
            return (
              <div key={i} style={{ position:'absolute', left:`${(i/(HOUR_END-HOUR_START))*100}%`, top:0, bottom:24, borderLeft: isFocus?'1px dashed #cbd5e1':'1px solid #f1f5f9' }}>
                <span style={{ position:'absolute', bottom:-22, left:-12, fontSize:10, color:C.fg4, fontWeight:600, fontVariantNumeric:'tabular-nums' }}>{String(h).padStart(2,'0')}:00</span>
              </div>
            );
          })}
          {/* 정시 출근 영역 (06-09 그린) */}
          <div style={{ position:'absolute', left:`${xFor(6)}%`, right:`${100-xFor(9)}%`, top:0, bottom:24, background:'rgba(22,163,74,0.04)', border:'1px dashed rgba(22,163,74,0.25)', borderRadius:4, pointerEvents:'none' }}>
            <span style={{ position:'absolute', top:6, right:6, fontSize:9, color:'#16a34a', fontWeight:700 }}>정시 출근 시간대</span>
          </div>

          {/* 직원 점 */}
          {arrivals.map((emp,i) => {
            const late = emp.today === '지각';
            const dept = DEPT[emp.dept];
            return (
              <div key={emp.id} title={`${emp.name} (${emp.arrival})`}
                style={{ position:'absolute', left:`${xFor(emp.t)}%`, top: 12 + (i % 6) * 14, transform:'translateX(-50%)', cursor:'pointer' }}>
                <div style={{ width:18, height:18, borderRadius:'50%', background:dept.bg, border:`2px solid ${late?'#f59e0b':dept.color}`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:9, fontWeight:800, color:dept.color }}>
                  {emp.name.slice(-1)}
                </div>
              </div>
            );
          })}
        </div>

        {/* 결근/연차 별도 행 */}
        <div style={{ display:'flex', gap:10, paddingTop:10, borderTop:'1px solid #f1f5f9' }}>
          <div style={{ flex:1, background:'#fef2f2', border:'1px solid #fecaca', borderRadius:6, padding:'8px 12px' }}>
            <div style={{ fontSize:10, color:'#dc2626', fontWeight:800, marginBottom:6, letterSpacing:'0.4px' }}>결근 {absents.length}명</div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              {absents.map(a=>(
                <div key={a.id} style={{ display:'flex', alignItems:'center', gap:5, padding:'3px 8px', background:'#fff', border:'1px solid #fecaca', borderRadius:12 }}>
                  <Avatar name={a.name} dept={a.dept} size={18}/>
                  <span style={{ fontSize:11, fontWeight:700, color:'#0f172a' }}>{a.name}</span>
                  <span style={{ fontSize:9, color:'#94a3b8' }}>{BRANCHES.find(b=>b.key===a.branch)?.label}</span>
                </div>
              ))}
              {absents.length===0 && <span style={{ fontSize:11, color:'#94a3b8' }}>없음</span>}
            </div>
          </div>
          <div style={{ flex:1, background:'#f8fafc', border:'1px solid #e2e8f0', borderRadius:6, padding:'8px 12px' }}>
            <div style={{ fontSize:10, color:'#64748b', fontWeight:800, marginBottom:6, letterSpacing:'0.4px' }}>연차/휴가 {leaves.length}명</div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              {leaves.map(a=>(
                <div key={a.id} style={{ display:'flex', alignItems:'center', gap:5, padding:'3px 8px', background:'#fff', border:'1px solid #e2e8f0', borderRadius:12 }}>
                  <Avatar name={a.name} dept={a.dept} size={18}/>
                  <span style={{ fontSize:11, fontWeight:700, color:'#0f172a' }}>{a.name}</span>
                </div>
              ))}
              {leaves.length===0 && <span style={{ fontSize:11, color:'#94a3b8' }}>없음</span>}
            </div>
          </div>
        </div>
      </div>

      {/* 하단 좌(통합 피드) + 우(인건비/지점 카드) */}
      <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:14 }}>
        {/* 통합 시간순 피드 */}
        <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, overflow:'hidden', display:'flex', flexDirection:'column' }}>
          <div style={{ padding:'14px 18px', borderBottom:`1px solid ${C.border}`, display:'flex', alignItems:'center', justifyContent:'space-between', background:'#fafbfc' }}>
            <div>
              <div style={{ fontSize:13, fontWeight:800, color:C.fg1 }}>오늘의 활동 피드</div>
              <div style={{ fontSize:11, color:C.fg4, marginTop:1 }}>모든 알림을 시간순으로</div>
            </div>
            <div style={{ display:'flex', gap:6 }}>
              {Object.entries(ALERT_META).map(([k,m]) => (
                <span key={k} style={{ display:'flex', alignItems:'center', gap:3, fontSize:9, color:C.fg3, fontWeight:600 }}>
                  <span style={{ width:6, height:6, borderRadius:'50%', background:m.color }}/>
                  {m.title.split('·')[0].split(' ')[0]}
                </span>
              ))}
            </div>
          </div>
          <div style={{ padding:'8px 0', maxHeight:380, overflow:'auto' }}>
            {feed.map((it,i) => {
              const meta = ALERT_META[it.type];
              return (
                <div key={i} style={{ display:'flex', gap:10, padding:'8px 18px', position:'relative' }}>
                  <div style={{ flexShrink:0, width:46, fontSize:11, fontWeight:800, color:C.fg2, fontVariantNumeric:'tabular-nums', paddingTop:6 }}>{it.time}</div>
                  <div style={{ position:'relative', flexShrink:0, paddingTop:6 }}>
                    <div style={{ width:9, height:9, borderRadius:'50%', background:meta.color, border:'2px solid #fff', boxShadow:`0 0 0 1.5px ${meta.color}`, position:'relative', zIndex:1 }}/>
                    {i<feed.length-1 && <div style={{ position:'absolute', left:4, top:18, bottom:-12, width:1, background:'#e2e8f0' }}/>}
                  </div>
                  <div style={{ flex:1, minWidth:0, paddingBottom:4 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:2 }}>
                      <span style={{ fontSize:11, fontWeight:800, color:meta.color }}>{meta.title}</span>
                      <span style={{ fontSize:11, fontWeight:700, color:C.fg1 }}>· {it.name}</span>
                      {it.dept && <DeptBadge dept={it.dept} size="sm"/>}
                      <span style={{ fontSize:9, color:C.fg4 }}>{it.branch}</span>
                    </div>
                    <div style={{ fontSize:11, color:C.fg2 }}>{it.text}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* 우측 카드 더미 */}
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {/* 인건비 추이 */}
          <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, padding:'14px 18px' }}>
            <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:8 }}>
              <span style={{ fontSize:12, fontWeight:700, color:C.fg3 }}>이달 인건비</span>
              <TrendBadge value={D.payroll.diff}/>
            </div>
            <div style={{ fontSize:24, fontWeight:900, color:C.fg1, marginBottom:6 }}>{fmtMoney(D.payroll.thisMonth)}</div>
            <Sparkline data={D.payroll.daily} color={C.violet} w={260} h={36}/>
          </div>

          {/* 지점별 출근 현황 */}
          <div style={{ background:'#fff', border:`1px solid ${C.border}`, borderRadius:12, padding:'14px 18px' }}>
            <div style={{ fontSize:12, fontWeight:700, color:C.fg3, marginBottom:10 }}>지점별 오늘 출근율</div>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {BRANCHES.filter(b=>b.key!=='all').map(b=>{
                const emps = EMPLOYEES.filter(e=>e.branch===b.key);
                const present = emps.filter(e=>e.today==='출근'||e.today==='지각').length;
                const rate = emps.length ? Math.round(present/emps.length*100) : 0;
                const color = rate>=95?C.primary : rate>=80?C.warning : C.danger;
                return (
                  <div key={b.key} style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <span style={{ width:54, fontSize:11, color:C.fg2, fontWeight:600 }}>{b.label}</span>
                    <div style={{ flex:1, height:6, background:'#f1f5f9', borderRadius:3, overflow:'hidden' }}>
                      <div style={{ height:'100%', width:`${rate}%`, background:color, borderRadius:3 }}/>
                    </div>
                    <span style={{ width:50, textAlign:'right', fontSize:11, fontWeight:800, color, fontVariantNumeric:'tabular-nums' }}>{present}/{emps.length}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>

    </div>
  </HrShell>;
};

window.HrDashboardV2 = HrDashboardV2;
