// Layout shell for PT Bumi Niaga HR & Payroll
const { useState, useEffect, useRef } = React;

const NAV = [
  { group: 'Operasional HR', items: [
    { id: 'dashboard', label: 'Dashboard',       icon: 'home' },
    { id: 'karyawan',   label: 'Karyawan',        icon: 'users' },
    { id: 'absensi',    label: 'Absensi',         icon: 'clock' },
    { id: 'cuti',       label: 'Cuti & Lembur',   icon: 'calendar' },
  ]},
  { group: 'Payroll', items: [
    { id: 'payroll',   label: 'Payroll Run',     icon: 'creditCard' },
    { id: 'slip',      label: 'Slip Gaji',       icon: 'receipt' },
  ]},
  { group: 'Analitik', items: [
    { id: 'laporan',   label: 'Laporan',         icon: 'trending' },
  ]},
];

const PAGE_TITLES = {
  dashboard: { t: 'Dashboard HR',    s: 'Ringkasan headcount, absensi, cuti, dan payroll bulan berjalan' },
  karyawan:  { t: 'Karyawan',        s: 'Master data pegawai, departemen, status kerja, dan data bank/BPJS' },
  absensi:   { t: 'Absensi',         s: 'Clock-in hari ini, rekap kehadiran periode berjalan, telat dan alpha' },
  cuti:      { t: 'Cuti & Lembur',   s: 'Approval cuti, saldo cuti, dan lembur yang masuk payroll' },
  payroll:   { t: 'Payroll Run',     s: 'Draft payroll, validasi komponen gaji, potongan, dan approval pembayaran' },
  slip:      { t: 'Slip Gaji',       s: 'Slip gaji per karyawan dalam format dokumen siap cetak' },
  laporan:   { t: 'Laporan',         s: 'Analitik biaya SDM, distribusi departemen, PPh 21, BPJS, dan payroll trend' },
};

function Card({ className = '', children, style }) {
  return <div className={'card ' + className} style={style}>{children}</div>;
}

function Btn({ tone = 'outline', size = 'sm', icon, children, onClick, disabled, title, type = 'button' }) {
  const cls = ['btn'];
  if (tone === 'primary') {/* default */}
  else if (tone === 'secondary') cls.push('secondary');
  else if (tone === 'ghost') cls.push('ghost');
  else if (tone === 'destructive') cls.push('destructive');
  else cls.push('outline');
  if (size === 'sm') cls.push('sm');
  if (size === 'lg') cls.push('lg');
  return (
    <button type={type} onClick={onClick} disabled={disabled} title={title} className={cls.join(' ')}>
      {icon && <Icon name={icon} size={13} />}
      {children}
    </button>
  );
}

function Pill({ tone = 'neutral', children, dot }) {
  const cls = ['badge'];
  if (tone === 'success' || tone === 'ok') cls.push('success');
  else if (tone === 'warn' || tone === 'warning') cls.push('warning');
  else if (tone === 'danger' || tone === 'destructive') cls.push('destructive');
  else if (tone === 'accent') cls.push('accent');
  else cls.push('neutral');
  if (dot) cls.push('dot');
  return <span className={cls.join(' ')}>{children}</span>;
}

function SoftPill({ color = 'indigo', children }) {
  return <span className={'pill-soft ' + color}>{children}</span>;
}

function StatusPill({ status }) {
  const color = status === 'masuk' || status === 'approved' || status === 'paid' ? 'green'
    : status === 'telat' || status === 'pending' || status === 'draft' ? 'amber'
    : status === 'alpha' || status === 'rejected' ? 'rose'
    : status === 'cuti' || status === 'sakit' ? 'indigo'
    : 'gray';
  return <SoftPill color={color}>{statusLabel(status)}</SoftPill>;
}

function SectionHead({ title, hint, action }) {
  return (
    <div className="row between" style={{marginBottom:12, gap:12}}>
      <div>
        <h3 style={{fontSize:14, fontWeight:750, margin:0, letterSpacing:'-0.01em'}}>{title}</h3>
        {hint && <div style={{fontSize:11.5, color:'hsl(var(--muted-foreground))', marginTop:2}}>{hint}</div>}
      </div>
      {action}
    </div>
  );
}

function EmpAvatar({ name, size = '' }) {
  return <div className={'emp-avatar ' + size}>{initials(name)}</div>;
}

function Sidebar({ active, setActive, role }) {
  const r = ROLES[role];
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <div className="sidebar-brand-mark" style={{background:'hsl(245 60% 55%)'}}>
          <Icon name="users" size={18} style={{color:'white'}} />
        </div>
        <div className="sidebar-brand-text">
          <div className="sidebar-brand-name">Bumi Niaga HR</div>
          <div className="sidebar-brand-sub">PT Bumi Niaga</div>
        </div>
      </div>

      <div style={{flex:1, overflowY:'auto'}}>
        {NAV.map(group => (
          <div key={group.group}>
            <div className="sidebar-section">{group.group}</div>
            {group.items.map(item => (
              <button key={item.id} onClick={() => setActive(item.id)} className={'nav-item' + (active === item.id ? ' active' : '')}>
                <Icon name={item.icon} size={15} className="icon" />
                <span>{item.label}</span>
                {item.id === 'cuti' && KPI.pendingCuti > 0 && (
                  <span style={{marginLeft:'auto', fontSize:11, fontWeight:750, color:'hsl(38 80% 30%)', background:'hsl(38 90% 94%)', padding:'2px 8px', borderRadius:999}}>
                    {KPI.pendingCuti}
                  </span>
                )}
              </button>
            ))}
          </div>
        ))}
      </div>

      <div style={{padding:'10px 4px 4px', borderTop:'1px solid hsl(var(--border))', marginTop:8}}>
        <div className="row" style={{padding:'4px 6px'}}>
          <EmpAvatar name={r.name} size="sm" />
          <div style={{minWidth:0, flex:1}}>
            <div className="sidebar-user-name">{r.name}</div>
            <div className="sidebar-user-role">{r.role}</div>
          </div>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ page, dept, setDept }) {
  const cur = PAGE_TITLES[page] || { t: page, s: '' };
  return (
    <header className="topbar">
      <div style={{flex:1, minWidth:0}}>
        <div className="topbar-title">{cur.t}</div>
        <div className="topbar-crumb">{cur.s}</div>
      </div>
      <div className="row gap-2 text-sm muted" style={{whiteSpace:'nowrap'}}>
        <Icon name="calendar" size={13}/>
        <span className="mono" style={{fontWeight:650, color:'hsl(var(--foreground))'}}>{PERIODE_LABEL}</span>
      </div>
      <DeptFilter value={dept} onChange={setDept} />
      <button className="btn outline sm" title="Notifikasi" style={{position:'relative'}}>
        <Icon name="bell" size={13} />
        <span style={{position:'absolute', top:5, right:5, width:6, height:6, borderRadius:999, background:'hsl(var(--destructive))'}} />
      </button>
    </header>
  );
}

function DeptFilter({ value, onChange }) {
  return (
    <select className="select" value={value} onChange={e => onChange(e.target.value)} style={{width:'auto', minWidth:190, height:32}}>
      <option value="all">Semua Departemen</option>
      {DEPT.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
    </select>
  );
}

function PageHeader({ eyebrow, title, subtitle, actions }) {
  return (
    <div className="card" style={{padding:'18px 22px', marginBottom:18, display:'flex', alignItems:'flex-start', gap:18}}>
      <div style={{flex:1, minWidth:0}}>
        {eyebrow && <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'hsl(var(--muted-foreground))', fontWeight:750, marginBottom:6}}>{eyebrow}</div>}
        <h1 style={{fontSize:22, fontWeight:800, letterSpacing:'-0.03em', margin:0, lineHeight:1.15}}>{title}</h1>
        {subtitle && <p style={{fontSize:13.5, color:'hsl(var(--muted-foreground))', marginTop:6, marginBottom:0, maxWidth:820, lineHeight:1.55}}>{subtitle}</p>}
      </div>
      {actions && <div className="row gap-2" style={{flexWrap:'wrap', justifyContent:'flex-end'}}>{actions}</div>}
    </div>
  );
}

function Kpi({ label, value, hint, icon, tone, progress, sub }) {
  return (
    <div className="card kpi" style={{padding:16}}>
      <div className="row between" style={{marginBottom:8}}>
        <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:750}}>{label}</div>
        {icon && <div className="kpi-icon" data-tone={tone}><Icon name={icon} size={14} /></div>}
      </div>
      <div style={{fontSize:24, fontWeight:800, letterSpacing:'-0.035em', fontVariantNumeric:'tabular-nums', lineHeight:1.1}}>{value}</div>
      {sub && <div style={{fontSize:12, color:'hsl(var(--muted-foreground))', marginTop:6}}>{sub}</div>}
      {hint && <div style={{fontSize:11.5, color:'hsl(var(--muted-foreground))', marginTop:4}}>{hint}</div>}
      {progress != null && <div className="kpi-progress"><div style={{width: Math.min(100, progress) + '%'}} /></div>}
    </div>
  );
}

function Field({ label, value }) {
  return (
    <div>
      <div style={{fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'hsl(var(--muted-foreground))', fontWeight:750, marginBottom:3}}>{label}</div>
      <div style={{fontSize:13, fontWeight:650}}>{value}</div>
    </div>
  );
}

Object.assign(window, {
  NAV, PAGE_TITLES,
  Card, Btn, Pill, SoftPill, StatusPill, SectionHead, EmpAvatar,
  Sidebar, Topbar, DeptFilter, PageHeader, Kpi, Field,
});
