/* ============================================================
   Davomat va ish haqi (HR) — faqat super admin.
   Ishchi (fix oylik + norma) · Ofis (geofence) · Davomat (kel/ket) · Oylik hisob.
   Daqiqa narxi = oylik / norma; ish haqi = ishlangan daqiqa × narx.
   ddFull — distributors.jsx'dan (umumiy scope). 2-bosqich: Telegram check-in.
   ============================================================ */

const HR_MONTHS = ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'Iyun', 'Iyul', 'Avgust', 'Sentyabr', 'Oktyabr', 'Noyabr', 'Dekabr'];
const hrMin = (m) => { m = Math.max(0, Math.round(m || 0)); const h = Math.floor(m / 60); return (h ? h + ' s ' : '') + (m % 60) + ' d'; };
const hrPct = (v) => (v == null ? '—' : Math.round(Number(v) * 100) + '%');
function hrStatus(pct) {
  if (pct == null) return { ink: 'var(--ink-4)', tint: 'var(--bg-2)' };
  if (pct >= 1) return { ink: '#1D8A6E', tint: 'rgba(61,190,156,.12)' };
  if (pct >= 0.8) return { ink: '#A6651E', tint: 'rgba(227,162,59,.14)' };
  return { ink: '#C2453A', tint: 'rgba(232,115,95,.12)' };
}

/* ---------- Ishchi modal ---------- */
function EmployeeModal({ initial, offices, onClose, onSaved, showToast }) {
  const isNew = !initial.id;
  const [name, setName] = useState(initial.name || '');
  const [position, setPosition] = useState(initial.position || '');
  const [phone, setPhone] = useState(initial.phone || '');
  const [age, setAge] = useState(initial.age ? String(initial.age) : '');
  const [salary, setSalary] = useState(initial.salary ? String(Math.round(initial.salary)) : '');
  const [normMinutes, setNormMinutes] = useState(initial.normMinutes ? String(initial.normMinutes) : '');
  const [workStart, setWorkStart] = useState(initial.workStart || '09:00');
  const [workEnd, setWorkEnd] = useState(initial.workEnd || '18:00');
  const [workDays, setWorkDays] = useState(initial.workDays && initial.workDays.length ? initial.workDays : [1, 2, 3, 4, 5, 6]);
  const [overtimeEnabled, setOvertimeEnabled] = useState(initial.overtimeEnabled !== false);
  const [officeId, setOfficeId] = useState(initial.officeId || '');
  const [userId, setUserId] = useState(initial.userId || '');
  const [active, setActive] = useState(initial.active !== false);
  const [statsEnabled, setStatsEnabled] = useState(initial.statsEnabled === true);
  const [geoExempt, setGeoExempt] = useState(initial.geoExempt === true);
  const [busy, setBusy] = useState(false);

  async function save() {
    if (!name.trim()) return showToast('F.I.Sh kiriting');
    setBusy(true);
    try {
      const p = {
        name: name.trim(), position: position || null, phone: phone || null,
        age: age ? Math.max(0, Math.round(Number(age))) : null,
        salary: Math.max(0, Math.round(Number(salary) || 0)),
        normMinutes: normMinutes ? Math.max(0, Math.round(Number(normMinutes))) : null,
        workStart: workStart || null, workEnd: workEnd || null, workDays,
        overtimeEnabled,
        officeId: officeId || null, userId: userId || null, active, statsEnabled, geoExempt,
      };
      const r = isNew ? await API.hrCreateEmployee(p) : await API.hrUpdateEmployee(initial.id, p);
      showToast('Saqlandi'); onSaved(r.employee); onClose();
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); setBusy(false); }
  }
  const fld = (label, node) => (<label style={{ display: 'block' }}><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>{node}</label>);

  return (
    <Modal onClose={onClose} width={520}>
      <ModalHeader title={isNew ? 'Yangi ishchi' : 'Ishchini tahrirlash'} subtitle="Fix oylik + norma" onClose={onClose} />
      <div style={{ padding: 20, display: 'grid', gap: 13 }}>
        {fld('F.I.Sh *', <input className="input" value={name} onChange={(e) => setName(e.target.value)} style={{ width: '100%' }} />)}
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 2fr 1fr', gap: 13 }}>
          {fld('Lavozim', <input className="input" value={position} onChange={(e) => setPosition(e.target.value)} style={{ width: '100%' }} />)}
          {fld('Telefon', <input className="input" value={phone} onChange={(e) => setPhone(e.target.value)} style={{ width: '100%' }} />)}
          {fld('Yosh', <input className="input tnum" type="number" min="0" value={age} onChange={(e) => setAge(e.target.value)} style={{ width: '100%' }} />)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          {fld("Fix oylik (so'm)", <input className="input tnum" type="number" min="0" value={salary} onChange={(e) => setSalary(e.target.value)} style={{ width: '100%' }} />)}
          {fld('Norma (daqiqa, ixtiyoriy)', <input className="input tnum" type="number" min="0" value={normMinutes} onChange={(e) => setNormMinutes(e.target.value)} placeholder="bo'sh = standart" style={{ width: '100%' }} />)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          {fld('Ofis (geofence)', (
            <select className="input" value={officeId} onChange={(e) => setOfficeId(e.target.value)} style={{ width: '100%' }}>
              <option value="">— yo'q —</option>
              {offices.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
            </select>
          ))}
          {fld('Login user (ixtiyoriy)', (
            <select className="input" value={userId} onChange={(e) => setUserId(e.target.value)} style={{ width: '100%' }}>
              <option value="">— loginsiz —</option>
              {(DB.USERS || []).map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          ))}
        </div>
        {/* Ish grafigi — overtime (kech ketish) shu bo'yicha hisoblanadi */}
        <div style={{ borderTop: '1px solid var(--border)', paddingTop: 13 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8 }}>Ish grafigi <span style={{ fontWeight: 400, color: 'var(--ink-4)' }}>— kech ketsa overtime shu bo'yicha</span></div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', marginBottom: 10 }}>
            <input className="input" type="time" value={workStart} onChange={(e) => setWorkStart(e.target.value)} style={{ width: 120 }} />
            <span style={{ color: 'var(--ink-4)' }}>—</span>
            <input className="input" type="time" value={workEnd} onChange={(e) => setWorkEnd(e.target.value)} style={{ width: 120 }} />
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[[1, 'Du'], [2, 'Se'], [3, 'Ch'], [4, 'Pa'], [5, 'Ju'], [6, 'Sh'], [7, 'Ya']].map(([n, lbl]) => {
              const on = workDays.includes(n);
              return (
                <button key={n} type="button" onClick={() => setWorkDays(on ? workDays.filter((x) => x !== n) : [...workDays, n].sort((a, b) => a - b))}
                  style={{ border: '1px solid var(--border)', borderRadius: 8, padding: '6px 11px', cursor: 'pointer', fontSize: 12, fontWeight: 700,
                           background: on ? 'var(--brand)' : 'var(--bg-2)', color: on ? '#fff' : 'var(--ink-3)' }}>{lbl}</button>
              );
            })}
          </div>
        </div>
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={overtimeEnabled} onChange={(e) => setOvertimeEnabled(e.target.checked)} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Qo'shimcha (overtime) oylik hisoblansin</span>
        </label>
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Faol</span>
        </label>
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={statsEnabled} onChange={(e) => setStatsEnabled(e.target.checked)} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Botda o'z statistikasini ko'rsin <span style={{ fontWeight: 400, color: 'var(--ink-4)' }}>(📊 tugma)</span></span>
        </label>
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={geoExempt} onChange={(e) => setGeoExempt(e.target.checked)} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Lokatsiyani solishtirmaslik <span style={{ fontWeight: 400, color: 'var(--ink-4)' }}>(lokatsiya baribir yuboriladi, lekin ofis bilan solishtirilmaydi — ofis shart emas)</span></span>
        </label>
      </div>
      <div style={{ display: 'flex', gap: 10, padding: '14px 20px', borderTop: '1px solid var(--border)', justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor</button>
        <button className="btn btn--primary" onClick={save} disabled={busy}><Icon name="check" size={15} stroke={2.4} /> Saqlash</button>
      </div>
    </Modal>
  );
}

/* ---------- Ofis modal ---------- */
function OfficeModal({ initial, onClose, onSaved, showToast }) {
  const isNew = !initial.id;
  const [name, setName] = useState(initial.name || '');
  const [lat, setLat] = useState(initial.lat != null ? String(initial.lat) : '');
  const [lng, setLng] = useState(initial.lng != null ? String(initial.lng) : '');
  const [radiusM, setRadiusM] = useState(initial.radiusM ? String(initial.radiusM) : '150');
  const [active, setActive] = useState(initial.active !== false);
  const [busy, setBusy] = useState(false);
  const [geoBusy, setGeoBusy] = useState(false);

  function useMyLocation() {
    if (!navigator.geolocation) return showToast('Brauzer joylashuvni qo`llamaydi');
    setGeoBusy(true);
    navigator.geolocation.getCurrentPosition(
      (pos) => { setLat(String(pos.coords.latitude)); setLng(String(pos.coords.longitude)); setGeoBusy(false); showToast('Joylashuv olindi (aniqlik ~' + Math.round(pos.coords.accuracy) + ' m)'); },
      (err) => { setGeoBusy(false); showToast('Joylashuv olinmadi: ' + (err.message || '')); },
      { enableHighAccuracy: true, timeout: 10000 }
    );
  }
  async function save() {
    if (!name.trim()) return showToast('Ofis nomini kiriting');
    const la = Number(lat), ln = Number(lng);
    if (!isFinite(la) || !isFinite(ln) || (la === 0 && ln === 0)) return showToast('Koordinatani kiriting yoki "Joriy joylashuv"ni bosing');
    setBusy(true);
    try {
      const p = { name: name.trim(), lat: la, lng: ln, radiusM: Math.max(20, Math.round(Number(radiusM) || 150)), active };
      const r = isNew ? await API.hrCreateOffice(p) : await API.hrUpdateOffice(initial.id, p);
      showToast('Saqlandi'); onSaved(r.office); onClose();
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); setBusy(false); }
  }
  const fld = (label, node) => (<label style={{ display: 'block' }}><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>{node}</label>);

  return (
    <Modal onClose={onClose} width={460}>
      <ModalHeader title={isNew ? 'Yangi ofis' : 'Ofisni tahrirlash'} subtitle="Geofence markazi" onClose={onClose} />
      <div style={{ padding: 20, display: 'grid', gap: 13 }}>
        {fld('Nom *', <input className="input" value={name} onChange={(e) => setName(e.target.value)} style={{ width: '100%' }} placeholder="Bosh ofis / Sklad…" />)}
        <button className="btn btn--ghost" style={{ height: 38 }} onClick={useMyLocation} disabled={geoBusy}>
          <Icon name="pin" size={15} /> {geoBusy ? 'Olinmoqda…' : 'Joriy joylashuvni olish'}
        </button>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          {fld('Kenglik (lat)', <input className="input tnum" value={lat} onChange={(e) => setLat(e.target.value)} style={{ width: '100%' }} />)}
          {fld('Uzunlik (lng)', <input className="input tnum" value={lng} onChange={(e) => setLng(e.target.value)} style={{ width: '100%' }} />)}
        </div>
        {fld('Radius (metr)', <input className="input tnum" type="number" min="20" value={radiusM} onChange={(e) => setRadiusM(e.target.value)} style={{ width: '100%' }} />)}
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Faol</span>
        </label>
      </div>
      <div style={{ display: 'flex', gap: 10, padding: '14px 20px', borderTop: '1px solid var(--border)', justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor</button>
        <button className="btn btn--primary" onClick={save} disabled={busy}><Icon name="check" size={15} stroke={2.4} /> Saqlash</button>
      </div>
    </Modal>
  );
}

/* ---------- Davomat (qo'lda) modal ---------- */
function AttendanceModal({ employees, onClose, onSaved, showToast }) {
  const today = new Date().toISOString().slice(0, 10);
  const [employeeId, setEmployeeId] = useState((employees[0] && employees[0].id) || '');
  const [workDate, setWorkDate] = useState(today);
  const [inT, setInT] = useState('09:00');
  const [outT, setOutT] = useState('18:00');
  const [busy, setBusy] = useState(false);

  async function save() {
    if (!employeeId) return showToast('Ishchini tanlang');
    setBusy(true);
    try {
      const mk = (t) => (t ? new Date(workDate + 'T' + t + ':00').toISOString() : null);
      await API.hrSaveAttendance({ employeeId, workDate, checkInAt: mk(inT), checkOutAt: mk(outT) });
      showToast('Davomat saqlandi'); onSaved(); onClose();
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); setBusy(false); }
  }
  const fld = (label, node) => (<label style={{ display: 'block' }}><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>{node}</label>);
  return (
    <Modal onClose={onClose} width={420}>
      <ModalHeader title="Qo'lda davomat" subtitle="Kel / ket vaqti" onClose={onClose} />
      <div style={{ padding: 20, display: 'grid', gap: 13 }}>
        {fld('Ishchi', (
          <select className="input" value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} style={{ width: '100%' }}>
            {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
          </select>
        ))}
        {fld('Sana', <input className="input" type="date" value={workDate} onChange={(e) => setWorkDate(e.target.value)} style={{ width: '100%' }} />)}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          {fld('Keldi', <input className="input" type="time" value={inT} onChange={(e) => setInT(e.target.value)} style={{ width: '100%' }} />)}
          {fld('Ketdi', <input className="input" type="time" value={outT} onChange={(e) => setOutT(e.target.value)} style={{ width: '100%' }} />)}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10, padding: '14px 20px', borderTop: '1px solid var(--border)', justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor</button>
        <button className="btn btn--primary" onClick={save} disabled={busy}><Icon name="check" size={15} stroke={2.4} /> Saqlash</button>
      </div>
    </Modal>
  );
}

function HrStat({ label, value, sub, accent }) {
  return (
    <div style={{ flex: '1 1 150px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '13px 16px', boxShadow: 'var(--sh-1)' }}>
      <div style={{ fontSize: 11.5, color: 'var(--ink-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.03em' }}>{label}</div>
      <div className="tnum" style={{ fontSize: 21, fontWeight: 800, marginTop: 3, color: accent || 'var(--ink)' }}>{value}</div>
      {sub != null && <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

/* ---------- Ustunli mini-grafik ---------- */
function HrBars({ data, color = 'var(--brand)', fmt }) {
  const mx = Math.max(1, ...data.map((d) => d.value || 0));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 130, overflowX: 'auto', paddingBottom: 4 }}>
      {data.length === 0 ? <div style={{ color: 'var(--ink-4)', fontSize: 12.5 }}>Ma'lumot yo'q</div> : data.map((d, i) => (
        <div key={i} title={(d.title || d.label) + ': ' + (fmt ? fmt(d.value) : d.value)}
          style={{ flex: '1 0 13px', minWidth: 13, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, height: '100%', justifyContent: 'flex-end' }}>
          <div style={{ width: '72%', height: Math.max(2, (d.value || 0) / mx * 100) + '%', minHeight: 2, borderRadius: '3px 3px 0 0', background: (d.value || 0) > 0 ? color : 'var(--bg-2)' }} />
          <div style={{ fontSize: 9, color: 'var(--ink-4)', whiteSpace: 'nowrap' }}>{d.label}</div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Statistika tab ---------- */
function HrStatsTab({ stats, statsEmp, setStatsEmp, employees }) {
  const tm = (d) => d ? new Date(d).toLocaleTimeString('uz', { hour: '2-digit', minute: '2-digit' }) : '—';
  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <select className="input" value={statsEmp} onChange={(e) => setStatsEmp(e.target.value)} style={{ height: 36, minWidth: 220 }}>
          <option value="">Hamma ishchilar (umumiy)</option>
          {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
        </select>
      </div>

      {!stats ? <div style={{ color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div> : stats.scope === 'all' ? (
        <>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
            <HrStat label="Faol ishchilar" value={stats.summary.employees} />
            <HrStat label="Jami ishlangan" value={hrMin(stats.summary.totalMinutes)} />
            <HrStat label="Qo'shimcha (overtime)" value={ddFull(stats.summary.totalOvertimePay) + " so'm"} accent="#A6651E" sub={hrMin(stats.summary.totalOvertime)} />
            <HrStat label="Kechikish jarimasi" value={ddFull(stats.summary.totalLatePenalty) + " so'm"} accent="#C2453A" sub="olib qolingan" />
            <HrStat label="Jami ish haqi" value={ddFull(stats.summary.totalPay) + " so'm"} accent="#1D8A6E" />
          </div>
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16, boxShadow: 'var(--sh-1)', marginBottom: 16 }}>
            <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 10 }}>Kunlik kelganlar soni</div>
            <HrBars data={stats.daily.map((d) => ({ label: d.day, value: d.present, title: d.iso }))} fmt={(v) => v + ' kishi'} />
          </div>
          <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto', background: 'var(--surface)' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 560 }}>
              <thead><tr style={{ textAlign: 'right', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', background: 'var(--bg-2)' }}>
                <th style={{ padding: '9px 14px', textAlign: 'left' }}>Ishchi</th><th style={{ padding: '9px 12px' }}>Kun</th>
                <th style={{ padding: '9px 12px' }}>Ishlangan</th><th style={{ padding: '9px 12px' }}>Norma %</th><th style={{ padding: '9px 12px' }}>Qo'shimcha</th><th style={{ padding: '9px 12px' }}>Kechikish</th><th style={{ padding: '9px 14px' }}>Ish haqi</th>
              </tr></thead>
              <tbody>
                {stats.employees.map((r) => { const st = hrStatus(r.pct); return (
                  <tr key={r.employeeId} style={{ borderTop: '1px solid var(--border)' }}>
                    <td style={{ padding: '9px 14px', textAlign: 'left', fontWeight: 700, cursor: 'pointer', color: 'var(--brand-700)' }} onClick={() => setStatsEmp(r.employeeId)}>{r.name}</td>
                    <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }}>{r.days}</td>
                    <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }}>{hrMin(r.minutes)}</td>
                    <td style={{ padding: '9px 12px', textAlign: 'right' }}><span className="tnum" style={{ padding: '2px 8px', borderRadius: 999, fontWeight: 800, fontSize: 11.5, background: st.tint, color: st.ink }}>{hrPct(r.pct)}</span></td>
                    <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right', color: r.overtimeMinutes > 0 ? '#A6651E' : 'var(--ink-4)' }} title={hrMin(r.overtimeMinutes)}>{r.overtimePay > 0 ? '+' + ddFull(r.overtimePay) : '—'}</td>
                    <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right', color: r.latePenalty > 0 ? '#C2453A' : 'var(--ink-4)' }} title={(r.lateDays || 0) + ' kun'}>{r.latePenalty > 0 ? '−' + ddFull(r.latePenalty) : '—'}</td>
                    <td className="tnum" style={{ padding: '9px 14px', textAlign: 'right', fontWeight: 800, color: '#1D8A6E' }}>{ddFull(r.pay)}</td>
                  </tr>
                ); })}
              </tbody>
            </table>
          </div>
        </>
      ) : (
        <>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
            <HrStat label={stats.employee.name} value={hrMin(stats.summary.minutes)} sub={(stats.employee.position || '') + ' · ' + (stats.employee.officeName || 'ofissiz')} />
            <HrStat label="Ishlangan kun" value={stats.summary.days} />
            <HrStat label="Norma %" value={hrPct(stats.summary.pct)} accent={hrStatus(stats.summary.pct).ink} />
            <HrStat label="Qo'shimcha (overtime)" value={ddFull(stats.summary.overtimePay) + " so'm"} accent="#A6651E" sub={(stats.employee.overtimeEnabled === false ? "o'chiq · " : '') + hrMin(stats.summary.overtimeMinutes)} />
            <HrStat label="Kechikish jarimasi" value={ddFull(stats.summary.latePenalty) + " so'm"} accent="#C2453A" sub={(stats.summary.lateDays || 0) + ' kun · ' + hrMin(stats.summary.lateMinutes)} />
            <HrStat label="Jami haq" value={ddFull(stats.summary.pay) + " so'm"} accent="#1D8A6E" sub={'asosiy ' + ddFull(stats.summary.basePay)} />
          </div>
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16, boxShadow: 'var(--sh-1)', marginBottom: 16 }}>
            <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 10 }}>Kunlik ishlangan (daqiqa)</div>
            <HrBars data={stats.daily.map((d) => ({ label: d.day, value: d.minutes, title: d.iso }))} color="var(--brand-700)" fmt={hrMin} />
          </div>
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16, boxShadow: 'var(--sh-1)', marginBottom: 16 }}>
            <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 10 }}>So'nggi 6 oy</div>
            <HrBars data={stats.trend.map((t) => ({ label: HR_MONTHS[t.month - 1].slice(0, 3), value: t.minutes, title: HR_MONTHS[t.month - 1] + ' ' + t.year }))} color="#8E74FF" fmt={hrMin} />
          </div>
          <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto', background: 'var(--surface)' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 460 }}>
              <thead><tr style={{ textAlign: 'left', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', background: 'var(--bg-2)' }}>
                <th style={{ padding: '8px 14px' }}>Kun</th><th style={{ padding: '8px 12px' }}>Keldi</th><th style={{ padding: '8px 12px' }}>Ketdi</th><th style={{ padding: '8px 14px', textAlign: 'right' }}>Ishlangan</th>
              </tr></thead>
              <tbody>
                {stats.daily.filter((d) => d.minutes > 0 || d.checkInAt).map((d) => (
                  <tr key={d.iso} style={{ borderTop: '1px solid var(--border)' }}>
                    <td style={{ padding: '8px 14px', fontWeight: 600 }}>{d.iso}</td>
                    <td className="tnum" style={{ padding: '8px 12px' }}>{tm(d.checkInAt)}</td>
                    <td className="tnum" style={{ padding: '8px 12px' }}>{tm(d.checkOutAt)}</td>
                    <td className="tnum" style={{ padding: '8px 14px', textAlign: 'right', fontWeight: 700 }}>{hrMin(d.minutes)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </>
  );
}

/* ---------- Bonus / Jarima / Avans modal ---------- */
const ADJ_LABEL = { bonus: 'Bonus', fine: 'Jarima', advance: 'Avans', kpi: 'KPI' };
const ADJ_POSITIVE = { bonus: true, kpi: true, fine: false, advance: false };
function AdjustmentsModal({ year, month, employees, onClose, onChanged, showToast }) {
  const [list, setList] = useState(null);
  const [empId, setEmpId] = useState(employees[0] ? employees[0].id : '');
  const [kind, setKind] = useState('bonus');
  const [amount, setAmount] = useState('');
  const [note, setNote] = useState('');
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    try { const r = await API.hrAdjustments(year, month); setList(r.adjustments || []); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }, [year, month, showToast]);
  useEffect(() => { load(); }, [load]);

  async function add() {
    const amt = Math.max(0, Math.round(Number(amount) || 0));
    if (!empId) return showToast('Ishchini tanlang');
    if (!amt) return showToast('Summani kiriting');
    setBusy(true);
    try {
      await API.hrCreateAdjustment({ employeeId: empId, year, month, kind, amount: amt, note: note || null });
      setAmount(''); setNote('');
      await load(); onChanged && onChanged();
      showToast("Qo'shildi");
    } catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
    finally { setBusy(false); }
  }
  async function del(a) {
    try { await API.hrDeleteAdjustment(a.id); await load(); onChanged && onChanged(); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }

  return (
    <Modal onClose={onClose} width={580}>
      <ModalHeader title="Bonus / KPI / Jarima / Avans" subtitle={HR_MONTHS[month - 1] + ' ' + year} onClose={onClose} />
      <div style={{ padding: 18 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
          <select className="input" value={empId} onChange={(e) => setEmpId(e.target.value)}>
            {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
          </select>
          <select className="input" value={kind} onChange={(e) => setKind(e.target.value)}>
            <option value="bonus">Bonus (+)</option>
            <option value="kpi">KPI (+)</option>
            <option value="fine">Jarima (−)</option>
            <option value="advance">Avans / olingan pul (−)</option>
          </select>
        </div>
        <div style={{ display: 'flex', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
          <input className="input tnum" type="number" min="0" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Summa (so'm)" style={{ flex: '1 1 130px' }} />
          <input className="input" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Izoh (ixtiyoriy)" style={{ flex: '1 1 130px' }} />
          <button className="btn btn--primary" onClick={add} disabled={busy}><Icon name="plus" size={15} stroke={2.4} /> Qo'shish</button>
        </div>
        <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r)', overflow: 'auto', maxHeight: '42vh' }}>
          {!list ? <div style={{ padding: 16, color: 'var(--ink-4)' }}>Yuklanmoqda…</div>
            : list.length === 0 ? <div style={{ padding: 16, color: 'var(--ink-4)', fontSize: 12.5 }}>Bu oyda tuzatish yo'q</div>
              : list.map((a) => (
                <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderTop: '1px solid var(--border)' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 13 }}>{a.employeeName}</div>
                    {a.note && <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{a.note}</div>}
                  </div>
                  <span style={{ fontSize: 11, fontWeight: 800, padding: '2px 8px', borderRadius: 999, background: ADJ_POSITIVE[a.kind] ? 'rgba(61,190,156,.14)' : 'rgba(232,115,95,.12)', color: ADJ_POSITIVE[a.kind] ? '#1D8A6E' : '#C2453A' }}>{ADJ_LABEL[a.kind]}</span>
                  <span className="tnum" style={{ fontWeight: 800, color: ADJ_POSITIVE[a.kind] ? '#1D8A6E' : '#C2453A', minWidth: 96, textAlign: 'right' }}>{ADJ_POSITIVE[a.kind] ? '+' : '−'}{ddFull(a.amount)}</span>
                  <button className="btn btn--icon btn--ghost" onClick={() => del(a)} style={{ width: 26, height: 26, color: '#C2453A' }}><Icon name="trash" size={13} /></button>
                </div>
              ))}
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '12px 18px', borderTop: '1px solid var(--border)' }}>
        <button className="btn btn--ghost" onClick={onClose}>Yopish</button>
      </div>
    </Modal>
  );
}

/* ---------- Maosh (birlashtirilgan, motivatsion) ---------- */
// Manbalar (musbat) — jami daromadga qo'shiladi; deduksiyalar alohida.
const MAOSH_SRC = [
  { key: 'fixDavomat', label: 'Fix / Davomat', color: '#8E74FF', icon: 'clock' },
  { key: 'checklistPay', label: 'Cheklist', color: '#5A9FD4', icon: 'check' },
  { key: 'kpi', label: 'KPI', color: '#7A5CF0', icon: 'chart' },
  { key: 'bonus', label: 'Bonus', color: '#3DBE9C', icon: 'coin' },
];
function MaoshTab({ payroll, month, year }) {
  const [kpiData, setKpiData] = useState(null);
  const [detail, setDetail] = useState(null); // tafsilot ochilgan ishchi (payroll qatori)
  useEffect(() => {
    let alive = true;
    API.hrKpi(year, month).then((r) => { if (alive) setKpiData(r); }).catch(() => {});
    return () => { alive = false; };
  }, [year, month]);
  if (!payroll) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>;
  const rows = [...(payroll.payroll || [])].sort((a, b) => (b.salaryTotal || 0) - (a.salaryTotal || 0));
  const t = payroll.totals || {};
  const money = (n) => ddFull(Math.round(n || 0)) + " so'm";
  if (!rows.length) return <Empty icon="users" text="Ishchi yo'q" />;

  return (
    <div>
      {/* Umumiy sarhisob */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px,1fr))', gap: 10, marginBottom: 18 }}>
        <div className="dx-kpi" style={{ '--_a': '#1D8A6E', gridColumn: 'span 2' }}>
          <div className="dx-kpi__l">Jami maosh (qo'lga) — {HR_MONTHS[month - 1]} {year}</div>
          <div className="dx-kpi__v" style={{ color: '#1D8A6E', fontSize: 22 }}>{money(t.salaryTotal)}</div>
        </div>
        {MAOSH_SRC.map((s) => (
          <div key={s.key} className="dx-kpi" style={{ '--_a': s.color }}>
            <div className="dx-kpi__l">{s.label}</div>
            <div className="dx-kpi__v" style={{ color: s.color, fontSize: 15 }}>{money(t[s.key])}</div>
          </div>
        ))}
        <div className="dx-kpi" style={{ '--_a': '#C2453A' }}>
          <div className="dx-kpi__l">Ushlanmalar (Jarima + Avans)</div>
          <div className="dx-kpi__v" style={{ color: '#C2453A', fontSize: 15 }}>−{money((t.fine || 0) + (t.advance || 0))}</div>
        </div>
      </div>

      {/* Har ishchi — motivatsion karta */}
      <div style={{ display: 'grid', gap: 12 }}>
        {rows.map((r) => {
          const gross = (r.fixDavomat || 0) + (r.checklistPay || 0) + (r.kpi || 0) + (r.bonus || 0);
          const deduct = (r.fine || 0) + (r.advance || 0);
          return (
            <div key={r.employeeId} className="dx-card" style={{ padding: '16px 18px', cursor: 'pointer' }}
              onClick={() => setDetail(r)} title="Tafsilotni ko'rish">
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap', marginBottom: 12 }}>
                <div style={{ fontWeight: 800, fontSize: 15 }}>{r.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>{r.position || ''}</div>
                <div style={{ flex: 1 }} />
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 600 }}>Bu oy topdi (qo'lga) · bosing ›</div>
                  <div className="tnum" style={{ fontSize: 22, fontWeight: 800, color: '#1D8A6E', lineHeight: 1.1 }}>{money(r.salaryTotal)}</div>
                </div>
              </div>
              {/* Stacked bar — qaysi manbadan qancha */}
              <div style={{ display: 'flex', height: 12, borderRadius: 100, overflow: 'hidden', background: 'var(--bg-2)', marginBottom: 10 }}>
                {MAOSH_SRC.map((s) => {
                  const v = r[s.key] || 0; if (v <= 0 || gross <= 0) return null;
                  return <div key={s.key} title={s.label + ': ' + money(v)} style={{ width: (v / gross * 100) + '%', background: s.color }} />;
                })}
              </div>
              {/* Manbalar ro'yxati */}
              <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 12.5 }}>
                {MAOSH_SRC.map((s) => (
                  <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ width: 9, height: 9, borderRadius: 3, background: s.color, flex: 'none' }} />
                    <span style={{ color: 'var(--ink-3)', fontWeight: 600 }}>{s.label}:</span>
                    <span className="tnum" style={{ fontWeight: 700 }}>{money(r[s.key])}</span>
                  </div>
                ))}
                {deduct > 0 && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginLeft: 'auto' }}>
                    <span style={{ color: '#C2453A', fontWeight: 600 }}>Ushlandi:</span>
                    <span className="tnum" style={{ fontWeight: 700, color: '#C2453A' }}>
                      −{money(deduct)}{r.advance > 0 ? ` (avans ${ddFull(r.advance)})` : ''}
                    </span>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 14, fontSize: 11.5, color: 'var(--ink-4)' }}>
        Har ishchi ustiga bosib tafsilotini ko'ring. Jami = Fix/Davomat + Cheklist + KPI + Bonus − Jarima − Avans.
      </div>
      {detail && <MaoshDetail row={detail} kpi={kpiData && kpiData.kpi ? kpiData.kpi[detail.employeeId] : null}
        month={month} year={year} onClose={() => setDetail(null)} />}
    </div>
  );
}

/* ---------- Maosh tafsiloti (bitta ishchi) ---------- */
function MaoshDetail({ row, kpi, month, year, onClose }) {
  const money = (n) => ddFull(Math.round(n || 0)) + " so'm";
  const Line = ({ label, value, sub, color, bold }) => (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '7px 0', borderTop: '1px solid var(--border)' }}>
      <div style={{ fontSize: 13, fontWeight: bold ? 800 : 600, color: color || 'var(--ink-2)' }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{sub}</div>}
      <div style={{ flex: 1 }} />
      <div className="tnum" style={{ fontSize: 13.5, fontWeight: bold ? 800 : 700, color: color || 'var(--ink-1)' }}>{value}</div>
    </div>
  );
  const deduct = (row.fine || 0) + (row.advance || 0);
  return (
    <Modal onClose={onClose} width={560}>
      <ModalHeader title={row.name + ' — maosh tafsiloti'} subtitle={(row.position ? row.position + ' · ' : '') + HR_MONTHS[month - 1] + ' ' + year} onClose={onClose} />
      <div style={{ padding: 18, maxHeight: '74vh', overflow: 'auto' }}>
        {/* Katta jami */}
        <div style={{ textAlign: 'center', padding: '10px 0 16px' }}>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', fontWeight: 600 }}>Bu oy qo'lga tegadi</div>
          <div className="tnum" style={{ fontSize: 30, fontWeight: 800, color: '#1D8A6E' }}>{money(row.salaryTotal)}</div>
        </div>

        {/* ── Fix / Davomat ── */}
        <div style={{ fontSize: 12, fontWeight: 800, color: '#8E74FF', margin: '6px 0 2px' }}>Fix / Davomat — {money(row.fixDavomat)}</div>
        <Line label="Asosiy (ishlangan)" sub={row.days + ' kun · ' + hrMin(row.workedMinutes)} value={money(row.basePay)} />
        {row.overtimePay > 0 && <Line label="Qo'shimcha (overtime)" value={'+' + money(row.overtimePay)} color="#A6651E" />}
        {row.leavePay > 0 && <Line label="Ta'til / bayram / komandirovka" sub={(row.leaveDays + row.holidayDays) + ' kun'} value={'+' + money(row.leavePay)} color="#1D8A6E" />}

        {/* ── Cheklist ── */}
        <div style={{ fontSize: 12, fontWeight: 800, color: '#5A9FD4', margin: '14px 0 2px' }}>Cheklist</div>
        <Line label="Kunlik vazifalar daromadi" value={money(row.checklistPay)} />

        {/* ── KPI ── */}
        <div style={{ fontSize: 12, fontWeight: 800, color: '#7A5CF0', margin: '14px 0 2px' }}>KPI — {money(row.kpi)}</div>
        {kpi ? (<>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead><tr style={{ color: 'var(--ink-4)', textAlign: 'right' }}>
              <th style={{ textAlign: 'left', padding: '5px 2px' }}>Ko'rsatkich</th><th>Og'ir.</th><th>Yopish</th><th>Bonus</th>
            </tr></thead>
            <tbody>
              {kpi.metrics.map((m) => (
                <tr key={m.key} style={{ borderTop: '1px solid var(--border)', textAlign: 'right' }}>
                  <td style={{ textAlign: 'left', padding: '5px 2px' }}>{m.label}</td>
                  <td>{Math.round(m.weight * 100)}%</td>
                  <td style={{ color: m.yopish >= (kpi.threshold || 0.7) ? '#1D8A6E' : '#A6651E' }}>{kpiPct(m.yopish)}</td>
                  <td className="tnum" style={{ fontWeight: 700, color: m.bonus > 0 ? '#1D8A6E' : 'var(--ink-4)' }}>{ddFull(m.bonus)}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <Line label="Bir martalik (Shartnoma+Programma)" value={'+' + money(kpi.oneTime)} />
        </>) : (
          <Line label={row.kpi > 0 ? 'Qo\'lda kiritilgan KPI' : 'KPI sozlanmagan'} value={money(row.kpi)} />
        )}

        {/* ── Bonus ── */}
        {row.bonus > 0 && (<>
          <div style={{ fontSize: 12, fontWeight: 800, color: '#3DBE9C', margin: '14px 0 2px' }}>Bonus</div>
          <Line label="Qo'shimcha bonus" value={'+' + money(row.bonus)} color="#1D8A6E" />
        </>)}

        {/* ── Ushlanmalar ── */}
        {deduct > 0 && (<>
          <div style={{ fontSize: 12, fontWeight: 800, color: '#C2453A', margin: '14px 0 2px' }}>Ushlanmalar</div>
          {row.fine > 0 && <Line label="Jarima" value={'−' + money(row.fine)} color="#C2453A" />}
          {row.advance > 0 && <Line label="Avans (olingan pul)" value={'−' + money(row.advance)} color="#C2453A" />}
        </>)}

        {/* ── Jami ── */}
        <div style={{ marginTop: 14, borderTop: '2px solid var(--border)', paddingTop: 4 }}>
          <Line label="JAMI (qo'lga)" value={money(row.salaryTotal)} color="#1D8A6E" bold />
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '12px 18px', borderTop: '1px solid var(--border)' }}>
        <button className="btn btn--ghost" onClick={onClose}>Yopish</button>
      </div>
    </Modal>
  );
}

/* ---------- KPI sozlash va hisob ---------- */
const kpiPct = (v) => (v == null ? '—' : Math.round(v * 100) + '%');
const kfmt = (n, unit) => unit === 'kor' ? (Math.round((n || 0) * 10) / 10) + ' kor' : ddFull(Math.round(n || 0));
function KpiModal({ year, month, onClose, onChanged, showToast }) {
  const [data, setData] = useState(null);
  const [empId, setEmpId] = useState('');
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    try { const r = await API.hrKpi(year, month); setData(r); setEmpId((prev) => prev || (r.employees[0] ? r.employees[0].id : '')); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }, [year, month, showToast]);
  useEffect(() => { load(); }, [load]);

  const cfg = (data && data.config[empId]) || {};
  const kpi = data && data.kpi[empId];
  const deb = (data && (data.debitorka || {})[empId]) || { plan: 0, fakt: 0 };

  async function saveCfg(patch) {
    setBusy(true);
    try { await API.hrKpiConfig({ employeeId: empId, ...patch }); await load(); onChanged && onChanged(); showToast('Saqlandi'); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); } finally { setBusy(false); }
  }
  async function saveDeb(plan, fakt) {
    setBusy(true);
    try { await API.hrKpiDebitorka({ year, month, employeeId: empId, plan: Number(plan) || 0, fakt: Number(fakt) || 0 }); await load(); onChanged && onChanged(); showToast('Saqlandi'); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); } finally { setBusy(false); }
  }
  // Bitta ko'rsatkich og'irligini (%) o'zgartirib, to'liq weights obyektini saqlaymiz
  async function saveWeight(metricKey, pct) {
    const w = {};
    (kpi.metrics || []).forEach((m) => { w[m.key] = m.key === metricKey ? (Number(pct) || 0) / 100 : m.weight; });
    await saveCfg({ weights: w });
  }

  const mism = kpi && kpi.mismatch ? [...(kpi.mismatch.sellout || []).map((r) => 'Sell-out: ' + r), ...(kpi.mismatch.sellin || []).map((r) => 'Sell-in: ' + r)] : [];

  return (
    <Modal onClose={onClose} width={680}>
      <ModalHeader title="KPI — menejerlar bonusi" subtitle={HR_MONTHS[month - 1] + ' ' + year} onClose={onClose} />
      <div style={{ padding: 18, maxHeight: '72vh', overflow: 'auto' }}>
        {!data ? <div style={{ color: 'var(--ink-4)' }}>Yuklanmoqda…</div> : (<>
          <select className="input" value={empId} onChange={(e) => setEmpId(e.target.value)} style={{ marginBottom: 12 }}>
            {data.employees.map((e) => <option key={e.id} value={e.id}>{e.name}{data.config[e.id] && data.config[e.id].bonusFund > 0 ? ' ✓' : ''}</option>)}
          </select>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
            <label><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 4 }}>Bonus fondi (so'm)</div>
              <input key={'bf' + empId} className="input tnum" type="number" min="0" defaultValue={cfg.bonusFund || ''} placeholder="masalan 15000000"
                onBlur={(e) => { const v = e.target.value.trim() === '' ? null : Number(e.target.value); if (v !== (cfg.bonusFund ?? null)) saveCfg({ bonusFund: v }); }} style={{ width: '100%' }} /></label>
            <label><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 4 }}>Bir martalik (Shartnoma+Programma)</div>
              <input key={'ot' + empId} className="input tnum" type="number" min="0" defaultValue={cfg.oneTime != null ? cfg.oneTime : 5000000}
                onBlur={(e) => { const v = Number(e.target.value) || 0; if (v !== (cfg.oneTime != null ? cfg.oneTime : 5000000)) saveCfg({ oneTime: v }); }} style={{ width: '100%' }} /></label>
          </div>

          {!kpi ? (
            <div style={{ padding: 16, background: 'var(--bg-2)', borderRadius: 10, fontSize: 13, color: 'var(--ink-3)' }}>
              Bonus fondini kiriting — KPI shundan keyin avtomatik hisoblanadi (sell-out/sell-in/plastinka biriktirilgan viloyatdan).
            </div>
          ) : (<>
            {mism.length > 0 && (
              <div style={{ marginBottom: 12, padding: '9px 12px', borderRadius: 8, background: 'rgba(232,115,95,.10)', border: '1px solid rgba(232,115,95,.3)', fontSize: 12, color: '#C2453A' }}>
                <b>⚠️ Nom mos kelmadi</b> (bu manba 0 bo'ladi) — sheets bilan bir xil bo'lishi kerak:<br />{mism.join(' · ')}
              </div>
            )}
            <div style={{ fontSize: 12, color: 'var(--ink-4)', marginBottom: 6 }}>Biriktirilgan viloyat(lar): {(kpi.regions || []).join(', ') || '—'}</div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
              <thead><tr style={{ color: 'var(--ink-4)', textAlign: 'right' }}>
                <th style={{ textAlign: 'left', padding: '6px 4px' }}>Ko'rsatkich</th><th>Og'ir.</th><th>Plan</th><th>Fakt</th><th>Yopish</th><th>Ulush</th><th>Bonus</th>
              </tr></thead>
              <tbody>
                {kpi.metrics.map((m) => (
                  <tr key={m.key} style={{ borderTop: '1px solid var(--border)', textAlign: 'right' }}>
                    <td style={{ textAlign: 'left', padding: '7px 4px', fontWeight: 600 }}>{m.label}{m.key === 'debitorka' ? " (qo'lda)" : ''}</td>
                    <td>
                      <input key={'w' + m.key + empId} className="input tnum" type="number" min="0" max="100" defaultValue={Math.round(m.weight * 100)}
                        onBlur={(e) => { const p = Number(e.target.value) || 0; if (p !== Math.round(m.weight * 100)) saveWeight(m.key, p); }}
                        style={{ width: 56, height: 28, textAlign: 'right', padding: '0 6px' }} title="Og'irlik (%)" />%
                    </td>
                    {m.key === 'debitorka' ? (<>
                      <td><input key={'dp' + empId} className="input tnum" type="number" defaultValue={deb.plan || ''} placeholder="plan" style={{ width: 92, height: 28, textAlign: 'right' }}
                        onBlur={(e) => saveDeb(e.target.value, deb.fakt)} /></td>
                      <td><input key={'df' + empId} className="input tnum" type="number" defaultValue={deb.fakt || ''} placeholder="fakt" style={{ width: 92, height: 28, textAlign: 'right' }}
                        onBlur={(e) => saveDeb(deb.plan, e.target.value)} /></td>
                    </>) : (<>
                      <td className="tnum">{kfmt(m.plan, m.unit)}</td>
                      <td className="tnum">{kfmt(m.fakt, m.unit)}</td>
                    </>)}
                    <td className="tnum" style={{ fontWeight: 700, color: m.yopish >= (kpi.threshold || 0.7) ? '#1D8A6E' : '#A6651E' }}>{kpiPct(m.yopish)}</td>
                    <td className="tnum" style={{ color: 'var(--ink-4)' }}>{ddFull(m.ulush)}</td>
                    <td className="tnum" style={{ fontWeight: 800, color: m.bonus > 0 ? '#1D8A6E' : 'var(--ink-4)' }}>{ddFull(m.bonus)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div style={{ marginTop: 12, padding: '10px 14px', borderRadius: 10, background: 'rgba(142,116,255,.10)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>KPI bonus {ddFull(kpi.bonusSum)} + bir martalik {ddFull(kpi.oneTime)}</span>
              <span className="tnum" style={{ fontSize: 18, fontWeight: 800, color: '#7A5CF0' }}>Jami KPI: {ddFull(kpi.kpiTotal)} so'm</span>
            </div>
            {(() => {
              const wSum = Math.round((kpi.metrics || []).reduce((s, m) => s + (m.weight || 0), 0) * 100);
              return (
                <div style={{ marginTop: 8, fontSize: 11, color: wSum === 100 ? 'var(--ink-4)' : '#C2453A' }}>
                  Og'irliklar jami: <b>{wSum}%</b>{wSum !== 100 ? ' — 100% bo\'lishi tavsiya etiladi' : ' ✓'} · Ulush = og'irlik × bonus fondi.
                  Yopish% ≥ {kpiPct(kpi.threshold || 0.7)} bo'lsa bonus hisoblanadi (maks {kpiPct(kpi.cap || 1)}). Sell-out/Sell-in/Plastinka avtomatik, Debitorka qo'lda.
                </div>
              );
            })()}
          </>)}
        </>)}
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '12px 18px', borderTop: '1px solid var(--border)' }}>
        <button className="btn btn--ghost" onClick={onClose} disabled={busy}>Yopish</button>
      </div>
    </Modal>
  );
}

/* ---------- Ta'til / ruxsat / bayram tab ---------- */
const LEAVE_LABEL = { vacation: "Ta'til", sick: 'Kasallik', unpaid: 'Ruxsat (haqsiz)', komandirovka: 'Komandirovka', other: 'Boshqa' };
function LeaveTab({ year, month, employees, showToast }) {
  const [leaves, setLeaves] = useState(null);
  const [holidays, setHolidays] = useState(null);
  const [lEmp, setLEmp] = useState(employees[0] ? employees[0].id : '');
  const [lStart, setLStart] = useState('');
  const [lEnd, setLEnd] = useState('');
  const [lType, setLType] = useState('vacation');
  const [lPaid, setLPaid] = useState(true);
  const [lNote, setLNote] = useState('');
  const [hDate, setHDate] = useState('');
  const [hName, setHName] = useState('');
  const [busy, setBusy] = useState(false);

  const loadLeaves = useCallback(async () => { try { const r = await API.hrLeaves(year, month); setLeaves(r.leaves || []); } catch (ex) { showToast(ex.message); } }, [year, month, showToast]);
  const loadHolidays = useCallback(async () => { try { const r = await API.hrHolidays(year); setHolidays(r.holidays || []); } catch (ex) { showToast(ex.message); } }, [year, showToast]);
  useEffect(() => { loadLeaves(); }, [loadLeaves]);
  useEffect(() => { loadHolidays(); }, [loadHolidays]);

  async function addLeave() {
    if (!lEmp) return showToast('Ishchini tanlang');
    if (!lStart || !lEnd) return showToast('Sanalarni tanlang');
    setBusy(true);
    try { await API.hrCreateLeave({ employeeId: lEmp, startDate: lStart, endDate: lEnd, type: lType, paid: lPaid, note: lNote || null }); setLStart(''); setLEnd(''); setLNote(''); await loadLeaves(); showToast("Qo'shildi"); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); } finally { setBusy(false); }
  }
  async function delLeave(l) { try { await API.hrDeleteLeave(l.id); await loadLeaves(); } catch (ex) { showToast(ex.message); } }
  async function addHoliday() {
    if (!hDate || !hName.trim()) return showToast('Sana va nom kiriting');
    setBusy(true);
    try { await API.hrCreateHoliday({ date: hDate, name: hName.trim(), paid: true }); setHDate(''); setHName(''); await loadHolidays(); showToast("Qo'shildi"); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); } finally { setBusy(false); }
  }
  async function delHoliday(h) { try { await API.hrDeleteHoliday(h.id); await loadHolidays(); } catch (ex) { showToast(ex.message); } }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(340px, 1fr))', gap: 16 }}>
      {/* Ta'til / ruxsat */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', overflow: 'hidden' }}>
        <div style={{ padding: '12px 14px', fontWeight: 800, fontSize: 14 }}>Ta'til / kasallik / ruxsat <span style={{ fontWeight: 400, color: 'var(--ink-4)', fontSize: 12 }}>· {HR_MONTHS[month - 1]} {year}</span></div>
        <div style={{ padding: '0 14px 12px', display: 'grid', gap: 8 }}>
          <select className="input" value={lEmp} onChange={(e) => setLEmp(e.target.value)}>
            {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
          </select>
          <div style={{ display: 'flex', gap: 8 }}>
            <input className="input" type="date" value={lStart} onChange={(e) => setLStart(e.target.value)} style={{ flex: 1 }} title="Boshlanish" />
            <input className="input" type="date" value={lEnd} onChange={(e) => setLEnd(e.target.value)} style={{ flex: 1 }} title="Tugash" />
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            <select className="input" value={lType} onChange={(e) => { const v = e.target.value; setLType(v); if (v === 'komandirovka') setLPaid(true); }} style={{ flex: 1, minWidth: 120 }}>
              <option value="vacation">Ta'til</option>
              <option value="sick">Kasallik</option>
              <option value="unpaid">Ruxsat (haqsiz)</option>
              <option value="komandirovka">Komandirovka</option>
              <option value="other">Boshqa</option>
            </select>
            <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 13 }}>
              <input type="checkbox" checked={lPaid} onChange={(e) => setLPaid(e.target.checked)} /> Haqli
            </label>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input className="input" value={lNote} onChange={(e) => setLNote(e.target.value)} placeholder="Izoh (ixtiyoriy)" style={{ flex: 1 }} />
            <button className="btn btn--primary" onClick={addLeave} disabled={busy}><Icon name="plus" size={15} stroke={2.4} /> Qo'shish</button>
          </div>
        </div>
        <div style={{ maxHeight: '46vh', overflow: 'auto' }}>
          {!leaves ? <div style={{ padding: 14, color: 'var(--ink-4)' }}>Yuklanmoqda…</div>
            : leaves.length === 0 ? <div style={{ padding: 14, color: 'var(--ink-4)', fontSize: 12.5 }}>Bu oyda yo'qlik yo'q</div>
              : leaves.map((l) => (
                <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 14px', borderTop: '1px solid var(--border)' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 13 }}>{l.employeeName}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{l.startDate} → {l.endDate}{l.note ? ' · ' + l.note : ''}</div>
                  </div>
                  <span style={{ fontSize: 10.5, fontWeight: 800, padding: '2px 8px', borderRadius: 999, background: l.paid ? 'rgba(61,190,156,.14)' : 'var(--bg-2)', color: l.paid ? '#1D8A6E' : 'var(--ink-4)' }}>{LEAVE_LABEL[l.type] || l.type}{l.paid ? '' : ' · haqsiz'}</span>
                  <button className="btn btn--icon btn--ghost" onClick={() => delLeave(l)} style={{ width: 26, height: 26, color: '#C2453A' }}><Icon name="trash" size={13} /></button>
                </div>
              ))}
        </div>
      </div>

      {/* Bayramlar */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', overflow: 'hidden' }}>
        <div style={{ padding: '12px 14px', fontWeight: 800, fontSize: 14 }}>Bayram / dam olish kunlari <span style={{ fontWeight: 400, color: 'var(--ink-4)', fontSize: 12 }}>· {year}</span></div>
        <div style={{ padding: '0 14px 12px', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <input className="input" type="date" value={hDate} onChange={(e) => setHDate(e.target.value)} style={{ flex: '1 1 140px' }} />
          <input className="input" value={hName} onChange={(e) => setHName(e.target.value)} placeholder="Bayram nomi" style={{ flex: '1 1 140px' }} />
          <button className="btn btn--primary" onClick={addHoliday} disabled={busy}><Icon name="plus" size={15} stroke={2.4} /> Qo'shish</button>
        </div>
        <div style={{ maxHeight: '46vh', overflow: 'auto' }}>
          {!holidays ? <div style={{ padding: 14, color: 'var(--ink-4)' }}>Yuklanmoqda…</div>
            : holidays.length === 0 ? <div style={{ padding: 14, color: 'var(--ink-4)', fontSize: 12.5 }}>Bayram qo'shilmagan</div>
              : holidays.map((h) => (
                <div key={h.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 14px', borderTop: '1px solid var(--border)' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 13 }}>{h.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{h.date}{h.paid ? ' · haqli' : ''}</div>
                  </div>
                  <button className="btn btn--icon btn--ghost" onClick={() => delHoliday(h)} style={{ width: 26, height: 26, color: '#C2453A' }}><Icon name="trash" size={13} /></button>
                </div>
              ))}
        </div>
      </div>
    </div>
  );
}

function Hr({ user, showToast, initialTab, maoshOnly }) {
  const now = new Date();
  const [tab, setTab] = useState(initialTab || 'payroll');
  const [year, setYear] = useState(now.getFullYear());
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [employees, setEmployees] = useState([]);
  const [offices, setOffices] = useState([]);
  const [payroll, setPayroll] = useState(null);
  const [attendance, setAttendance] = useState([]);
  const [stats, setStats] = useState(null);
  const [statsEmp, setStatsEmp] = useState('');
  const [config, setConfig] = useState(null);
  const [loading, setLoading] = useState(true);
  const [empModal, setEmpModal] = useState(null);
  const [offModal, setOffModal] = useState(null);
  const [attModal, setAttModal] = useState(false);
  const [adjOpen, setAdjOpen] = useState(false);
  const [kpiOpen, setKpiOpen] = useState(false);

  const mk = year + '-' + String(month).padStart(2, '0');

  const loadAll = useCallback(async () => {
    const cached = window.PageCache ? window.PageCache.get('hr:all') : null;
    if (cached) { setEmployees(cached.employees || []); setOffices(cached.offices || []); setConfig(cached.config); setLoading(false); }
    else setLoading(true);
    try {
      const [e, o, c] = await Promise.all([API.hrEmployees(), API.hrOffices(), API.hrConfig()]);
      setEmployees(e.employees || []); setOffices(o.offices || []); setConfig(c);
      if (window.PageCache) window.PageCache.set('hr:all', { employees: e.employees || [], offices: o.offices || [], config: c });
    } catch (ex) { if (!cached) showToast((ex && ex.message) || 'Yuklashda xatolik'); }
    finally { setLoading(false); }
  }, [showToast]);
  useEffect(() => { loadAll(); }, [loadAll]);

  const loadPayroll = useCallback(async () => {
    const ck = 'hr:payroll:' + year + '-' + month;
    const cached = window.PageCache ? window.PageCache.get(ck) : null;
    if (cached) setPayroll(cached);
    try { const r = await API.hrPayroll(year, month); setPayroll(r); if (window.PageCache) window.PageCache.set(ck, r); }
    catch (ex) { if (!cached) showToast((ex && ex.message) || 'Xatolik'); }
  }, [year, month, showToast]);
  const loadAttendance = useCallback(async () => {
    const ck = 'hr:att:' + mk;
    const cached = window.PageCache ? window.PageCache.get(ck) : null;
    if (cached) setAttendance(cached);
    try { const r = await API.hrAttendance(mk); setAttendance(r.attendance || []); if (window.PageCache) window.PageCache.set(ck, r.attendance || []); }
    catch (ex) { if (!cached) showToast((ex && ex.message) || 'Xatolik'); }
  }, [mk, showToast]);
  const loadStats = useCallback(async () => {
    const ck = 'hr:stats:' + year + '-' + month + ':' + (statsEmp || '');
    const cached = window.PageCache ? window.PageCache.get(ck) : null;
    setStats(cached || null);
    try { const r = await API.hrDashboard(year, month, statsEmp || null); setStats(r); if (window.PageCache) window.PageCache.set(ck, r); }
    catch (ex) { if (!cached) showToast((ex && ex.message) || 'Xatolik'); }
  }, [year, month, statsEmp, showToast]);

  useEffect(() => { if (tab === 'payroll' || tab === 'maosh') loadPayroll(); if (tab === 'attendance') loadAttendance(); if (tab === 'stats') loadStats(); }, [tab, loadPayroll, loadAttendance, loadStats]);

  async function saveConfig(patch) {
    try { const c = await API.hrUpdateConfig(patch); setConfig(c); showToast('Saqlandi'); if (tab === 'payroll') loadPayroll(); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }
  async function delEmployee(e) { if (!window.confirm('"' + e.name + '" o`chirilsinmi?')) return; try { await API.hrDeleteEmployee(e.id); setEmployees((p) => p.filter((x) => x.id !== e.id)); showToast("O'chirildi"); } catch (ex) { showToast(ex.message); } }
  async function toggleStats(e) { try { const r = await API.hrUpdateEmployee(e.id, { statsEnabled: !e.statsEnabled }); setEmployees((p) => p.map((x) => x.id === e.id ? r.employee : x)); showToast(r.employee.statsEnabled ? "Bot statistikasi yoqildi" : "O'chirildi"); } catch (ex) { showToast(ex.message); } }
  async function delOffice(o) { if (!window.confirm('"' + o.name + '" o`chirilsinmi?')) return; try { await API.hrDeleteOffice(o.id); setOffices((p) => p.filter((x) => x.id !== o.id)); showToast("O'chirildi"); } catch (ex) { showToast(ex.message); } }
  async function delAttendance(a) { if (!window.confirm("Yozuv o'chirilsinmi?")) return; try { await API.hrDeleteAttendance(a.id); loadAttendance(); } catch (ex) { showToast(ex.message); } }

  // Oylik hisobni CSV (Excel) qilib yuklab olish — joriy yuklangan ma'lumotdan
  function exportPayrollCsv() {
    if (!payroll || !payroll.payroll.length) return showToast("Ma'lumot yo'q");
    const head = ['Ishchi', 'Lavozim', 'Oylik', 'Daqiqa narxi', 'Ishlangan (daq)', 'Kun', "Ta'til/bayram kun", 'Overtime', 'Kechikish jarima', "Ta'til/bayram haq", 'Bonus', 'Jarima', 'Avans', 'Asosiy', 'Jami haq'];
    const data = payroll.payroll.map((r) => [r.name, r.position || '', r.salary, Math.round(r.perMinute), r.workedMinutes, r.days, (r.leaveDays + r.holidayDays), r.overtimePay, r.latePenalty, r.leavePay, r.bonus, r.fine, r.advance, r.basePay, r.pay]);
    const esc = (v) => { const s = String(v == null ? '' : v); return /[";\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
    const csv = [head, ...data].map((row) => row.map(esc).join(';')).join('\n');
    const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'oylik-hisob-' + year + '-' + String(month).padStart(2, '0') + '.csv'; a.click();
    URL.revokeObjectURL(url);
  }
  async function sendAllPayslips() {
    if (!window.confirm("Barcha ishchilarga oylik hisobvarag'i Telegram orqali yuborilsinmi?")) return;
    try { const r = await API.hrSendPayslip({ year, month }); showToast('Yuborildi: ' + r.sent + ' ta' + (r.skipped ? ' · ' + r.skipped + ' ulanmagan' : '')); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }
  async function sendOnePayslip(r) {
    try { const x = await API.hrSendPayslip({ year, month, employeeId: r.employeeId }); showToast(x.sent ? 'Yuborildi ✅' : (x.skipped ? 'Ishchi Telegramga ulanmagan' : 'Yuborilmadi')); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }

  // Maosh endi alohida nav bo'lim (maoshOnly). Davomat tablarida ko'rsatilmaydi.
  const TABS = maoshOnly ? [] : [['stats', 'Statistika', 'chart'], ['payroll', 'Oylik hisob', 'coin'], ['employees', 'Ishchilar', 'users'], ['offices', 'Ofislar', 'pin'], ['attendance', 'Davomat', 'clock'], ['leave', "Ta'til/Bayram", 'cal'], ['config', 'Sozlama', 'gear']];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <div className="board-toolbar" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 22px 10px', flexWrap: 'wrap' }}>
        <div>
          <h2 style={{ fontSize: 18, fontWeight: 800, letterSpacing: '-.02em', margin: 0 }}>{maoshOnly ? 'Maosh' : 'Davomat va ish haqi'}</h2>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>{maoshOnly ? 'Fix/Davomat + Cheklist + KPI + Bonus − Jarima − Avans' : "Ishchilar · fix oylik · daqiqa bo'yicha hisob"}</div>
        </div>
        <div style={{ flex: 1 }} />
        {(tab === 'maosh' || tab === 'payroll' || tab === 'attendance' || tab === 'stats' || tab === 'leave') && (
          <>
            <select className="input" value={month} onChange={(e) => setMonth(parseInt(e.target.value, 10))} style={{ height: 36, width: 130 }}>
              {HR_MONTHS.map((m, i) => <option key={i} value={i + 1}>{m}</option>)}
            </select>
            <select className="input" value={year} onChange={(e) => setYear(parseInt(e.target.value, 10))} style={{ height: 36, width: 100 }}>
              {[now.getFullYear() - 1, now.getFullYear(), now.getFullYear() + 1].map((y) => <option key={y} value={y}>{y}</option>)}
            </select>
          </>
        )}
        {tab === 'maosh' && <button className="btn btn--ghost" style={{ height: 36 }} onClick={() => setKpiOpen(true)} disabled={!employees.length}><Icon name="chart" size={15} /> KPI sozlash</button>}
        {tab === 'maosh' && <button className="btn btn--primary" style={{ height: 36 }} onClick={() => setAdjOpen(true)} disabled={!employees.length}><Icon name="plus" size={15} stroke={2.4} /> Bonus / Jarima / Avans</button>}
        {tab === 'employees' && <button className="btn btn--primary" style={{ height: 36 }} onClick={() => setEmpModal({})}><Icon name="plus" size={15} stroke={2.4} /> Yangi ishchi</button>}
        {tab === 'offices' && <button className="btn btn--primary" style={{ height: 36 }} onClick={() => setOffModal({})}><Icon name="plus" size={15} stroke={2.4} /> Yangi ofis</button>}
        {tab === 'attendance' && <button className="btn btn--primary" style={{ height: 36 }} onClick={() => setAttModal(true)} disabled={!employees.length}><Icon name="plus" size={15} stroke={2.4} /> Qo'lda davomat</button>}
        {tab === 'payroll' && <button className="btn btn--ghost" style={{ height: 36 }} onClick={() => setAdjOpen(true)} disabled={!employees.length}><Icon name="coin" size={15} /> Bonus / Jarima</button>}
        {tab === 'payroll' && <button className="btn btn--ghost" style={{ height: 36 }} onClick={exportPayrollCsv} disabled={!payroll}><Icon name="box" size={15} /> Excel</button>}
        {tab === 'payroll' && <button className="btn btn--primary" style={{ height: 36 }} onClick={sendAllPayslips} disabled={!payroll}><Icon name="send" size={15} /> Payslip → hammaga</button>}
      </div>

      {!maoshOnly && <div style={{ display: 'flex', gap: 4, padding: '0 22px', borderBottom: '1px solid var(--border)', flexWrap: 'wrap' }}>
        {TABS.map(([k, lbl, ic]) => (
          <button key={k} onClick={() => setTab(k)}
            style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '9px 13px', border: 'none', background: 'transparent', cursor: 'pointer',
                     fontWeight: 700, fontSize: 13, color: tab === k ? 'var(--brand-700)' : 'var(--ink-3)',
                     borderBottom: '2px solid ' + (tab === k ? 'var(--brand)' : 'transparent'), marginBottom: -1 }}>
            <Icon name={ic} size={15} /> {lbl}
          </button>
        ))}
      </div>}

      <div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '14px 22px 24px' }}>
        {loading ? <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div> : (
          <>
            {/* ===== Maosh ===== */}
            {tab === 'maosh' && <MaoshTab payroll={payroll} month={month} year={year} />}

            {/* ===== Statistika ===== */}
            {tab === 'stats' && <HrStatsTab stats={stats} statsEmp={statsEmp} setStatsEmp={setStatsEmp} employees={employees} />}

            {/* ===== Ta'til / Bayram ===== */}
            {tab === 'leave' && <LeaveTab year={year} month={month} employees={employees} showToast={showToast} />}

            {/* ===== Oylik hisob ===== */}
            {tab === 'payroll' && (
              !payroll ? <div style={{ color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div> : (
                <>
                  <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
                    <HrStat label="Ishchilar" value={payroll.totals.count} />
                    <HrStat label="Jami ishlangan" value={hrMin(payroll.totals.workedMinutes)} sub={'overtime ' + hrMin(payroll.totals.overtimeMinutes)} />
                    <HrStat label="Qo'shimcha (overtime)" value={ddFull(payroll.totals.overtimePay) + " so'm"} accent="#A6651E" sub={'koeff. ×' + (payroll.overtimeRate || 1)} />
                    <HrStat label="Kechikish jarimasi" value={ddFull(payroll.totals.latePenalty) + " so'm"} accent="#C2453A" sub={'olib qolingan · ' + hrMin(payroll.totals.lateMinutes)} />
                    <HrStat label="Ta'til / Bayram haqi" value={ddFull(payroll.totals.leavePay) + " so'm"} accent="#1D8A6E" sub="haqli yo'qliklar" />
                    <HrStat label="Bonus / Jarima / Avans" value={'+' + ddFull(payroll.totals.bonus)} accent="#1D8A6E" sub={'−' + ddFull(payroll.totals.fine + payroll.totals.advance) + ' (jarima+avans)'} />
                    <HrStat label="Jami ish haqi" value={ddFull(payroll.totals.pay) + " so'm"} accent="#1D8A6E" sub={'asosiy ' + ddFull(payroll.totals.basePay)} />
                  </div>
                  <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto', background: 'var(--surface)' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 760 }}>
                      <thead><tr style={{ textAlign: 'right', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', background: 'var(--bg-2)' }}>
                        <th style={{ padding: '9px 14px', textAlign: 'left' }}>Ishchi</th>
                        <th style={{ padding: '9px 12px' }}>Oylik</th>
                        <th style={{ padding: '9px 12px' }}>Daqiqa narxi</th>
                        <th style={{ padding: '9px 12px' }}>Ishlangan</th>
                        <th style={{ padding: '9px 12px' }}>Kun</th>
                        <th style={{ padding: '9px 12px' }}>Norma %</th>
                        <th style={{ padding: '9px 12px' }}>Qo'shimcha</th>
                        <th style={{ padding: '9px 12px' }}>Kechikish</th>
                        <th style={{ padding: '9px 12px' }}>Bonus/Jarima</th>
                        <th style={{ padding: '9px 14px' }}>Jami haq</th>
                      </tr></thead>
                      <tbody>
                        {payroll.payroll.length === 0 ? (
                          <tr><td colSpan={10} style={{ padding: 18, textAlign: 'center', color: 'var(--ink-4)' }}>Ishchi yo'q</td></tr>
                        ) : payroll.payroll.map((r) => {
                          const st = hrStatus(r.pct);
                          return (
                            <tr key={r.employeeId} style={{ borderTop: '1px solid var(--border)' }}>
                              <td style={{ padding: '9px 14px', textAlign: 'left', fontWeight: 700 }}>
                                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>{r.name}
                                  <button className="btn btn--icon btn--ghost" onClick={() => sendOnePayslip(r)} title="Payslip Telegram'ga yuborish" style={{ width: 22, height: 22, color: 'var(--brand-700)' }}><Icon name="send" size={12} /></button>
                                </span>
                                <div style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 400 }}>{r.position || ''}</div>
                              </td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right', color: 'var(--ink-3)' }}>{ddFull(r.salary)}</td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }}>{ddFull(Math.round(r.perMinute))}</td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }}>{hrMin(r.workedMinutes)}</td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }}>{r.days}{(r.leaveDays + r.holidayDays) > 0 && <div style={{ fontSize: 10, color: '#1D8A6E' }} title="Ta'til/bayram (haqli)">+{r.leaveDays + r.holidayDays} t/b</div>}</td>
                              <td style={{ padding: '9px 12px', textAlign: 'right' }}><span className="tnum" style={{ padding: '2px 8px', borderRadius: 999, fontWeight: 800, fontSize: 11.5, background: st.tint, color: st.ink }}>{hrPct(r.pct)}</span></td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right', color: r.overtimeMinutes > 0 ? '#A6651E' : 'var(--ink-4)' }} title={hrMin(r.overtimeMinutes)}>{r.overtimePay > 0 ? '+' + ddFull(r.overtimePay) : '—'}</td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right', color: r.latePenalty > 0 ? '#C2453A' : 'var(--ink-4)' }} title={hrMin(r.lateMinutes)}>{r.latePenalty > 0 ? '−' + ddFull(r.latePenalty) : '—'}</td>
                              <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }} title={'bonus +' + ddFull(r.bonus) + ' · jarima −' + ddFull(r.fine) + ' · avans −' + ddFull(r.advance)}>
                                {(() => { const net = (r.bonus || 0) - (r.fine || 0) - (r.advance || 0); if (!net) return <span style={{ color: 'var(--ink-4)' }}>—</span>; return <span style={{ color: net > 0 ? '#1D8A6E' : '#C2453A', fontWeight: 700 }}>{net > 0 ? '+' : '−'}{ddFull(Math.abs(net))}</span>; })()}
                              </td>
                              <td className="tnum" style={{ padding: '9px 14px', textAlign: 'right', fontWeight: 800, color: '#1D8A6E' }}>{ddFull(r.pay)}</td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 10 }}>Daqiqa narxi = oylik ÷ norma · Hisoblangan = ishlangan daqiqa × daqiqa narxi</div>
                </>
              )
            )}

            {/* ===== Ishchilar ===== */}
            {tab === 'employees' && (
              employees.length === 0 ? <Empty icon="users" text="Ishchi yo'q. “Yangi ishchi” bilan boshlang." /> : (
                <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto', background: 'var(--surface)' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 720 }}>
                    <thead><tr style={{ textAlign: 'left', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', background: 'var(--bg-2)' }}>
                      <th style={{ padding: '9px 14px' }}>F.I.Sh</th><th style={{ padding: '9px 12px' }}>Lavozim</th>
                      <th style={{ padding: '9px 12px', textAlign: 'right' }}>Oylik</th><th style={{ padding: '9px 12px' }}>Ofis</th>
                      <th style={{ padding: '9px 12px' }}>Telegram</th><th style={{ padding: '9px 12px', textAlign: 'center' }}>📊 Bot stat</th><th style={{ padding: '9px 12px', textAlign: 'center' }}>Faol</th><th />
                    </tr></thead>
                    <tbody>
                      {employees.map((e) => (
                        <tr key={e.id} style={{ borderTop: '1px solid var(--border)' }}>
                          <td style={{ padding: '9px 14px', fontWeight: 700 }}>{e.name}{e.userName ? <span style={{ fontSize: 10, color: 'var(--ink-4)', marginLeft: 6 }}>({e.userName})</span> : ''}</td>
                          <td style={{ padding: '9px 12px', color: 'var(--ink-3)' }}>{e.position || '—'}</td>
                          <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right' }}>{ddFull(e.salary)}</td>
                          <td style={{ padding: '9px 12px', color: 'var(--ink-3)' }}>{e.officeName || '—'}</td>
                          <td style={{ padding: '9px 12px' }}>{e.telegramLinked ? <span style={{ color: '#1D8A6E', fontWeight: 700 }}>ulangan</span> : <span style={{ color: 'var(--ink-4)' }}>—</span>}</td>
                          <td style={{ padding: '9px 12px', textAlign: 'center' }}>
                            <button onClick={() => toggleStats(e)} title="Botda statistika tugmasini yoqish/o'chirish"
                              style={{ border: 'none', cursor: 'pointer', borderRadius: 999, padding: '2px 10px', fontSize: 11, fontWeight: 800,
                                       background: e.statsEnabled ? 'rgba(61,190,156,.14)' : 'var(--bg-2)', color: e.statsEnabled ? '#1D8A6E' : 'var(--ink-4)' }}>
                              {e.statsEnabled ? 'Yoqilgan' : "O'chiq"}
                            </button>
                          </td>
                          <td style={{ padding: '9px 12px', textAlign: 'center' }}>{e.active ? <span style={{ color: '#1D8A6E', fontWeight: 700 }}>✓</span> : <span style={{ color: 'var(--ink-4)' }}>✕</span>}</td>
                          <td style={{ padding: '9px 12px', textAlign: 'right', whiteSpace: 'nowrap' }}>
                            <button className="btn btn--icon btn--ghost" onClick={() => setEmpModal(e)} style={{ width: 28, height: 28 }}><Icon name="edit" size={14} /></button>
                            <button className="btn btn--icon btn--ghost" onClick={() => delEmployee(e)} style={{ width: 28, height: 28, color: '#C2453A' }}><Icon name="trash" size={14} /></button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )
            )}

            {/* ===== Ofislar ===== */}
            {tab === 'offices' && (
              offices.length === 0 ? <Empty icon="pin" text="Ofis yo'q. “Yangi ofis” bilan geofence belgilang." /> : (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
                  {offices.map((o) => (
                    <div key={o.id} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 14, boxShadow: 'var(--sh-1)' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ color: 'var(--brand)', display: 'inline-flex' }}><Icon name="pin" size={15} /></span>
                        <span style={{ fontWeight: 800, fontSize: 14 }}>{o.name}</span>
                        <div style={{ flex: 1 }} />
                        <button className="btn btn--icon btn--ghost" onClick={() => setOffModal(o)} style={{ width: 26, height: 26 }}><Icon name="edit" size={13} /></button>
                        <button className="btn btn--icon btn--ghost" onClick={() => delOffice(o)} style={{ width: 26, height: 26, color: '#C2453A' }}><Icon name="trash" size={13} /></button>
                      </div>
                      <div className="tnum" style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 8 }}>{Number(o.lat).toFixed(5)}, {Number(o.lng).toFixed(5)}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>Radius: <b className="tnum">{o.radiusM} m</b> · {o.active ? 'faol' : 'nofaol'}</div>
                    </div>
                  ))}
                </div>
              )
            )}

            {/* ===== Davomat ===== */}
            {tab === 'attendance' && (
              attendance.length === 0 ? <Empty icon="clock" text={"Bu oyda davomat yo'q. “Qo'lda davomat” bilan kiriting (2-bosqichda Telegram orqali avtomatik)."} /> : (
                <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto', background: 'var(--surface)' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 680 }}>
                    <thead><tr style={{ textAlign: 'left', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', background: 'var(--bg-2)' }}>
                      <th style={{ padding: '9px 14px' }}>Sana</th><th style={{ padding: '9px 12px' }}>Ishchi</th>
                      <th style={{ padding: '9px 12px' }}>Keldi</th><th style={{ padding: '9px 12px' }}>Ketdi</th>
                      <th style={{ padding: '9px 12px', textAlign: 'right' }}>Ishlangan</th><th style={{ padding: '9px 12px' }}>Selfi</th><th style={{ padding: '9px 12px' }}>Manba</th><th />
                    </tr></thead>
                    <tbody>
                      {attendance.map((a) => {
                        const tm = (d) => d ? new Date(d).toLocaleTimeString('uz', { hour: '2-digit', minute: '2-digit' }) : '—';
                        return (
                          <tr key={a.id} style={{ borderTop: '1px solid var(--border)' }}>
                            <td style={{ padding: '9px 14px', fontWeight: 600 }}>{a.workDate}</td>
                            <td style={{ padding: '9px 12px' }}>{a.employeeName}</td>
                            <td className="tnum" style={{ padding: '9px 12px' }}>{tm(a.checkInAt)}</td>
                            <td className="tnum" style={{ padding: '9px 12px' }}>{tm(a.checkOutAt)}</td>
                            <td className="tnum" style={{ padding: '9px 12px', textAlign: 'right', fontWeight: 700 }}>{hrMin(a.minutes)}</td>
                            <td style={{ padding: '9px 12px' }}>{a.checkInPhoto ? <a href={a.checkInPhoto} target="_blank" rel="noopener noreferrer"><img src={a.checkInPhoto} alt="selfi" style={{ width: 30, height: 30, borderRadius: 6, objectFit: 'cover', border: '1px solid var(--border)' }} /></a> : <span style={{ color: 'var(--ink-4)' }}>—</span>}</td>
                            <td style={{ padding: '9px 12px' }}><span style={{ fontSize: 11, color: a.source === 'telegram' ? '#1D8A6E' : 'var(--ink-4)' }}>{a.source === 'telegram' ? 'Telegram' : "Qo'lda"}</span></td>
                            <td style={{ padding: '9px 12px', textAlign: 'right' }}><button className="btn btn--icon btn--ghost" onClick={() => delAttendance(a)} style={{ width: 26, height: 26, color: '#C2453A' }}><Icon name="trash" size={13} /></button></td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )
            )}

            {/* ===== Sozlama ===== */}
            {tab === 'config' && config && (
              <div style={{ maxWidth: 480 }}>
                <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 18, boxShadow: 'var(--sh-1)' }}>
                  <div style={{ fontWeight: 800, fontSize: 14, marginBottom: 4 }}>Ish vaqti normasi</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', marginBottom: 14 }}>Daqiqa narxi shu normaga bo'lib hisoblanadi (har ishchida alohida norma ham bo'lishi mumkin).</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
                    <label><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Ish kunlari (oyiga)</div>
                      <input className="input tnum" type="number" min="1" max="31" defaultValue={config.config.normDays || ''}
                        placeholder="avtomatik" title="Bo'sh qoldirilsa — avtomatik: oy kunlari, yakshanbalardan tashqari. Son kiritilsa — qo'lda belgilangan."
                        onBlur={(e) => {
                          const raw = e.target.value.trim();
                          const v = raw === '' ? null : parseInt(raw, 10);
                          if (v !== (config.config.normDays || null)) saveConfig({ normDays: v });
                        }} style={{ width: '100%' }} /></label>
                    <label><div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Kunlik soat</div>
                      <input className="input tnum" type="number" min="1" max="24" defaultValue={config.config.normHours}
                        onBlur={(e) => { const v = parseInt(e.target.value, 10); if (v && v !== config.config.normHours) saveConfig({ normHours: v }); }} style={{ width: '100%' }} /></label>
                  </div>
                  <div style={{ marginTop: 12, padding: '10px 12px', borderRadius: 10, background: 'var(--bg-2)', fontSize: 12.5 }}>
                    Joriy oy normasi: <b className="tnum">{hrMin(config.normMinutes)}</b>
                    {' '}({config.config.normDays > 0
                      ? `qo'lda: ${config.config.normDays} kun × ${config.config.normHours} soat`
                      : `avtomatik: oy ish kunlari × ${config.config.normHours} soat, faqat yakshanba dam`})
                  </div>
                  <label style={{ display: 'block', marginTop: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Overtime koeffitsienti (kech ketgan daqiqaga)</div>
                    <input className="input tnum" type="number" min="0" step="0.1" defaultValue={config.config.overtimeRate != null ? config.config.overtimeRate : 1}
                      onBlur={(e) => { const v = Number(e.target.value); if (v >= 0 && v !== (config.config.overtimeRate != null ? config.config.overtimeRate : 1)) saveConfig({ overtimeRate: v }); }} style={{ width: 160 }} />
                    <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4 }}>1 = oddiy daqiqa narxi · 1.5 = yarim baravar ko'p</div>
                  </label>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, cursor: 'pointer' }}>
                    <input type="checkbox" checked={config.config.requirePhoto !== false} onChange={(e) => saveConfig({ requirePhoto: e.target.checked })} />
                    <span style={{ fontSize: 13, fontWeight: 600 }}>Telegram check-in'da selfie majburiy (2-bosqich)</span>
                  </label>
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {empModal && <EmployeeModal initial={empModal} offices={offices} onClose={() => setEmpModal(null)} onSaved={() => loadAll()} showToast={showToast} />}
      {offModal && <OfficeModal initial={offModal} onClose={() => setOffModal(null)} onSaved={() => loadAll()} showToast={showToast} />}
      {attModal && <AttendanceModal employees={employees} onClose={() => setAttModal(false)} onSaved={() => loadAttendance()} showToast={showToast} />}
      {adjOpen && <AdjustmentsModal year={year} month={month} employees={employees} onClose={() => setAdjOpen(false)} onChanged={() => loadPayroll()} showToast={showToast} />}
      {kpiOpen && <KpiModal year={year} month={month} onClose={() => setKpiOpen(false)} onChanged={() => loadPayroll()} showToast={showToast} />}
    </div>
  );
}
