// ============ EXPENSES ============
const { Icon: Ic, formatBaht: fb, formatNumber: fn, StatCard: SC, RevenueChart: RC, Donut: Dn, Ring: Rg } = window.UI;
const Mx = window.MOCK;
const APIx = window.API;

function Expenses() {
  const [showModal, setShowModal] = React.useState(false);
  const [items, setItems] = React.useState(Mx.expenses);
  const [removing, setRemoving] = React.useState(null);
  const [tabFilter, setTabFilter] = React.useState('ທັງໝົດ');
  const tabs = ['ທັງໝົດ', 'ຈ່າຍແລ້ວ', 'ຍັງບໍ່ໄດ້ຈ່າຍ'];

  React.useEffect(() => {
    APIx.expenses.list().then(setItems).catch(() => {});
  }, []);

  const filtered = items.filter(x => {
    if (tabFilter === 'ທັງໝົດ') return true;
    if (tabFilter === 'ຈ່າຍແລ້ວ') return x.paid;
    return !x.paid;
  });
  const total = filtered.reduce((s, x) => s + x.amount, 0);
  const unpaidTotal = items.filter(x => !x.paid).reduce((s, x) => s + x.amount, 0);

  const togglePaid = async (id) => {
    const cur = items.find(x => x.id === id);
    if (!cur) return;
    const newPaid = !cur.paid;
    setItems(items.map(x => x.id === id ? { ...x, paid: newPaid } : x));
    try { await APIx.expenses.update(id, { paid: newPaid }); } catch (e) { console.warn(e); }
  };
  const handleDelete = async (id) => {
    setRemoving(id);
    try { await APIx.expenses.remove(id); } catch (e) { console.warn(e); }
    setTimeout(() => {
      setItems(prev => prev.filter(x => x.id !== id));
      setRemoving(null);
    }, 240);
  };
  const handleSave = async (payload) => {
    try {
      const saved = await APIx.expenses.create(payload);
      setItems([saved, ...items]);
    } catch (e) {
      const fallback = {
        ...payload,
        id: `EXP-LOCAL-${Date.now().toString(36).slice(-6).toUpperCase()}`,
        paid: false,
      };
      setItems([fallback, ...items]);
    }
    setShowModal(false);
  };

  const byCat = {};
  items.forEach(e => byCat[e.category] = (byCat[e.category] || 0) + e.amount);
  const catEntries = Object.entries(byCat).sort((a, b) => b[1] - a[1]);
  const catTotal = catEntries.reduce((s, [, v]) => s + v, 0);
  const catColors = ['#7c3aed', '#06b6d4', '#f59e0b', '#10b981', '#a855f7'];

  return (
    <div className="page">
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <SC label="ລາຍຈ່າຍເດືອນນີ້" value={items.reduce((s, x) => s + x.amount, 0)} color="cyan"
          icon={<Ic.Card/>} isCurrency
          trend={{ dir: 'up', value: `${items.length} ລາຍການ`, label: 'ບັນທຶກໄວ້' }}/>
        <SC label="ຈ່າຍແລ້ວ" value={items.filter(e => e.paid).reduce((s, x) => s + x.amount, 0)} color="green"
          icon={<Ic.Check/>} isCurrency
          trend={{ dir: 'up', value: `${items.filter(e => e.paid).length} ລາຍການ`, label: '' }}/>
        <SC label="ຄ້າງຈ່າຍ" value={unpaidTotal} color="amber"
          icon={<Ic.Phone/>} isCurrency
          trend={{ dir: 'up', value: `${items.filter(e => !e.paid).length} ລາຍການ`, label: 'ຕ້ອງຊຳລະ' }}/>
      </div>

      <div className="grid-2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card-h">
            <div className="tabs">
              {tabs.map(c => <div key={c} className={`tab ${tabFilter === c ? 'active' : ''}`} onClick={() => setTabFilter(c)}>{c}</div>)}
            </div>
            <button className="btn btn-primary" onClick={() => setShowModal(true)}><Ic.Plus/> ບັນທຶກລາຍຈ່າຍ</button>
          </div>
          <table>
            <thead>
              <tr>
                <th>ເລກທີ</th><th>ວັນທີ</th><th>ໝວດ</th><th>ລາຍລະອຽດ</th><th>ສະຖານະການຈ່າຍ</th><th style={{ textAlign: 'right' }}>ຈຳນວນເງິນ</th><th style={{ width: 60 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(e => (
                <tr key={e.id} className={removing === e.id ? 'removing' : ''}>
                  <td className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>{e.id}</td>
                  <td style={{ fontSize: 12, color: 'var(--ink-2)' }}>{e.date}</td>
                  <td><span className="chip cyan"><span className="dot"></span>{e.category}</span></td>
                  <td>
                    <div style={{ fontWeight: 500 }}>{e.desc}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{e.vendor}</div>
                  </td>
                  <td>
                    <span className={`chip clickable ${e.paid ? 'green' : 'amber'}`}
                      onClick={() => togglePaid(e.id)}
                      title="ຄລິກເພື່ອສະຫຼັບສະຖານະ">
                      <span className="dot"></span>{e.paid ? 'ຈ່າຍແລ້ວ' : 'ຍັງບໍ່ໄດ້ຈ່າຍ'}
                    </span>
                  </td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 600, color: '#22d3ee' }}>−{fb(e.amount)}</td>
                  <td>
                    <div className="row-actions">
                      <button className="icon-btn danger" title="ລົບລາຍການ" onClick={() => handleDelete(e.id)}>
                        <Ic.Trash/>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan="7" style={{ textAlign: 'center', padding: '32px', color: 'var(--ink-3)' }}>ບໍ່ພົບລາຍການ</td></tr>
              )}
            </tbody>
            <tfoot>
              <tr style={{ background: 'rgba(6,182,212,0.05)' }}>
                <td colSpan="5" style={{ padding: '14px 18px', fontWeight: 600 }}>ລວມ {filtered.length} ລາຍການ</td>
                <td className="mono" style={{ textAlign: 'right', padding: '14px 18px', fontWeight: 700, color: '#22d3ee' }}>−{fb(total)}</td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>

        <div className="card">
          <div className="card-h">
            <h3>ສັດສ່ວນລາຍຈ່າຍ</h3>
            <span className="chip purple"><span className="dot"></span>{items.length} ລາຍການ</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 6 }}>
            {catEntries.map(([name, val], i) => {
              const pct = catTotal ? (val / catTotal) * 100 : 0;
              return (
                <div key={name}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 12 }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: catColors[i % catColors.length] }}></span>
                      {name}
                    </span>
                    <span className="mono" style={{ color: 'var(--ink-2)' }}>{fb(val)} <span style={{ color: 'var(--ink-3)' }}>· {pct.toFixed(0)}%</span></span>
                  </div>
                  <div className="progress">
                    <span style={{ width: `${pct}%`, background: `linear-gradient(90deg, ${catColors[i % catColors.length]}, ${catColors[(i+1) % catColors.length]})` }}></span>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ marginTop: 24, padding: 14, borderRadius: 12, background: 'rgba(245,158,11,0.06)', border: '1px solid rgba(245,158,11,0.18)' }}>
            <div style={{ fontSize: 11.5, color: 'var(--ink-2)', marginBottom: 4 }}>ຍອດຄ້າງຈ່າຍທັງໝົດ</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: '#fbbf24' }}>{fb(unpaidTotal)}</div>
          </div>
        </div>
      </div>

      {showModal && <NewExpenseModal onClose={() => setShowModal(false)} onSave={handleSave}/>}
    </div>
  );
}

function NewExpenseModal({ onClose, onSave }) {
  const today = new Date().toISOString().slice(0, 10);
  const [date, setDate] = React.useState(today);
  const [category, setCategory] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [vendor, setVendor] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [note, setNote] = React.useState('');
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const formatThaiDateB = (d) => {
    const months = ['ມ.ກ.','ກ.ພ.','ມີ.ນ.','ມສ.','ພ.ສ.','ມິ.ຖ.','ກ.ລ.','ສ.ຫ.','ກ.ຍ.','ຕ.ລ.','ພ.ຈ.','ທ.ວ.'];
    return `${String(d.getDate()).padStart(2,'0')} ${months[d.getMonth()]} ${d.getFullYear()}`;
  };

  const handleSave = async () => {
    if (!category || !desc.trim() || !amount) {
      setError('ກະລຸນາປ້ອນຂໍ້ມູນໃຫ້ຄົບ (ໝວດ / ລາຍລະອຽດ / ຈຳນວນເງິນ)');
      return;
    }
    const amt = Number(String(amount).replace(/,/g, ''));
    if (isNaN(amt) || amt <= 0) {
      setError('ຈຳນວນເງິນບໍ່ຖືກຕ້ອງ');
      return;
    }
    setSaving(true);
    await onSave({
      date: formatThaiDateB(date ? new Date(date) : new Date()),
      category,
      desc: desc.trim(),
      vendor: vendor.trim() || '-',
      amount: amt,
      note: note.trim(),
      paid: false,
    });
  };

  return (
    <window.UI.Modal title="ບັນທຶກລາຍຈ່າຍ" subtitle="ເພີ່ມຄ່າໃຊ້ຈ່າຍ / ຄ່າອາໄຫຼ່" onClose={onClose}
      footer={<>
        {error && <span style={{ color: '#fb7185', fontSize: 12, marginRight: 'auto' }}>{error}</span>}
        <button className="btn" onClick={onClose}>ຍົກເລີກ</button>
        <button className="btn btn-primary" onClick={handleSave} disabled={saving}><Ic.Plus/> {saving ? 'ກຳລັງບັນທຶກ...' : 'ບັນທຶກ'}</button>
      </>}>
      <div className="form-grid">
        <div className="field"><label>ວັນທີ</label><input className="input" type="date" value={date} onChange={e => setDate(e.target.value)}/></div>
        <div className="field"><label>ໝວດລາຍຈ່າຍ</label>
          <select className="select" value={category} onChange={e => setCategory(e.target.value)}>
            <option value="">ເລືອກໝວດ</option>
            <option>ອາໄຫຼ່</option>
            <option>ຄ່າໃຊ້ຈ່າຍຮ້ານ</option>
            <option>ການຕະຫຼາດ</option>
            <option>ອຸປະກອນ</option>
            <option>ອື່ນໆ</option>
          </select>
        </div>
        <div className="field full"><label>ລາຍລະອຽດ</label><input className="input" placeholder="ລະບຸລາຍລະອຽດ" value={desc} onChange={e => setDesc(e.target.value)}/></div>
        <div className="field"><label>ຜູ້ຂາຍ / ແຫຼ່ງຊື້</label><input className="input" placeholder="ຊື່ຮ້ານ ຫຼື ຜູ້ຂາຍ" value={vendor} onChange={e => setVendor(e.target.value)}/></div>
        <div className="field"><label>ຈຳນວນເງິນ (ກີບ)</label><input className="input mono" placeholder="0" value={amount} onChange={e => setAmount(e.target.value)}/></div>
        <div className="field full"><label>ໝາຍເຫດ</label><textarea className="textarea" placeholder="..." value={note} onChange={e => setNote(e.target.value)}/></div>
      </div>
    </window.UI.Modal>
  );
}

// ============ SALARY ============
function makeInitials(name) {
  const parts = (name || '').trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '??';
  const a = parts[0][0] || '';
  const b = (parts[1] && parts[1][0]) || (parts[0][1] || '');
  return (a + b).toUpperCase();
}

function Salary() {
  const [month, setMonth] = React.useState('ພຶດສະພາ 2026');
  const [payOpen, setPayOpen] = React.useState(null);
  const [employees, setEmployees] = React.useState(Mx.employees);
  const [editEmp, setEditEmp] = React.useState(null);
  const [addOpen, setAddOpen] = React.useState(false);
  const [removing, setRemoving] = React.useState(null);

  React.useEffect(() => {
    APIx.employees.list().then(setEmployees).catch(() => {});
  }, []);

  const totalBase = employees.reduce((s, e) => s + e.base, 0);
  const totalBonus = employees.reduce((s, e) => s + e.bonus, 0);
  const totalPay = totalBase + totalBonus;
  const avatars = ['c1', 'c2', 'c3', 'c4'];

  const handleSave = async (emp) => {
    if (emp.id) {
      // UPDATE
      try {
        const updated = await APIx.employees.update(emp.id, {
          name: emp.name, role: emp.role, base: emp.base, bonus: emp.bonus, joined: emp.joined,
        });
        setEmployees(employees.map(e => e.id === emp.id ? updated : e));
      } catch (err) {
        setEmployees(employees.map(e => e.id === emp.id ? emp : e));
      }
    } else {
      // CREATE
      try {
        const created = await APIx.employees.create({
          name: emp.name, role: emp.role, base: emp.base, bonus: emp.bonus,
          joined: emp.joined, initials: makeInitials(emp.name),
        });
        setEmployees([...employees, created]);
      } catch (err) {
        const nextId = (employees.reduce((m, e) => Math.max(m, e.id), 0) || 0) + 1;
        const codeNum = (employees.reduce((m, e) => {
          const n = parseInt(String(e.code).replace(/\D/g, ''), 10);
          return isNaN(n) ? m : Math.max(m, n);
        }, 0) || 0) + 1;
        setEmployees([...employees, {
          ...emp,
          id: nextId,
          code: `EMP-${String(codeNum).padStart(3, '0')}`,
          avatar: avatars[nextId % avatars.length],
          initials: makeInitials(emp.name),
          status: 'active',
        }]);
      }
    }
    setEditEmp(null);
    setAddOpen(false);
  };

  const handleDelete = async (id) => {
    if (!window.confirm('ຢືນຢັນລົບພະນັກງານຄົນນີ້?')) return;
    setRemoving(id);
    try { await APIx.employees.remove(id); } catch (e) { console.warn(e); }
    setTimeout(() => {
      setEmployees(prev => prev.filter(e => e.id !== id));
      setRemoving(null);
    }, 240);
  };

  return (
    <div className="page">
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <SC label="ພະນັກງານທັງໝົດ" value={employees.length} color="purple" icon={<Ic.Salary/>}
          trend={{ dir: 'up', value: 'Active', label: 'ເຮັດວຽກເຕັມເວລາທຸກຄົນ' }}/>
        <SC label="ຖານເງິນເດືອນລວມ" value={totalBase} color="cyan" icon={<Ic.Coin/>} isCurrency
          trend={{ dir: 'up', value: employees.length ? `ສະເລ່ຍ ${fb(totalBase / employees.length)}` : '-', label: 'ຕໍ່ຄົນ' }}/>
        <SC label="ໂບນັດລວມເດືອນນີ້" value={totalBonus} color="amber" icon={<Ic.Trend/>} isCurrency
          trend={{ dir: 'up', value: '+24%', label: 'ຈາກຍອດວຽກສ້ອມ' }}/>
        <SC label="ຄ່າຈ້າງລວມ" value={totalPay} color="green" icon={<Ic.Card/>} isCurrency
          trend={{ dir: 'up', value: '20 ພ.ສ.', label: 'ກຳນົດຈ່າຍເດືອນນີ້' }}/>
      </div>

      <div className="card">
        <div className="card-h">
          <div>
            <h3>ລາຍການເງິນເດືອນພະນັກງານ</h3>
            <div className="sub">ງວດ · {month}</div>
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <select className="select" value={month} onChange={(e) => setMonth(e.target.value)} style={{ minWidth: 160 }}>
              <option>ພຶດສະພາ 2026</option>
              <option>ເມສາ 2026</option>
              <option>ມີນາ 2026</option>
            </select>
            <button className="btn"><Ic.Download/> ສະລິບທັງໝົດ</button>
            <button className="btn btn-primary" onClick={() => setAddOpen(true)}><Ic.Plus/> ເພີ່ມພະນັກງານ</button>
          </div>
        </div>
        <table>
          <thead>
            <tr>
              <th>ລະຫັດ</th>
              <th>ພະນັກງານ</th>
              <th>ຕຳແໜ່ງ</th>
              <th style={{ textAlign: 'right' }}>ເງິນເດືອນພື້ນຖານ</th>
              <th style={{ textAlign: 'right' }}>ໂບນັດ</th>
              <th style={{ textAlign: 'right' }}>ລວມສຸດທິ</th>
              <th style={{ textAlign: 'right', width: 220 }}>ການຈັດການ</th>
            </tr>
          </thead>
          <tbody>
            {employees.map(e => (
              <tr key={e.id} className={removing === e.id ? 'removing' : ''}>
                <td className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>{e.code}</td>
                <td>
                  <div className="emp">
                    <div className={`emp-av ${e.avatar}`}>{e.initials}</div>
                    <div>
                      <div style={{ fontWeight: 500 }}>{e.name}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>ເຂົ້າເຮັດວຽກ {e.joined}</div>
                    </div>
                  </div>
                </td>
                <td><span className="chip purple"><span className="dot"></span>{e.role}</span></td>
                <td className="mono" style={{ textAlign: 'right' }}>{fb(e.base)}</td>
                <td className="mono" style={{ textAlign: 'right', color: '#34d399' }}>+{fb(e.bonus)}</td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ink-0)' }}>{fb(e.base + e.bonus)}</td>
                <td style={{ textAlign: 'right' }}>
                  <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                    <button className="btn" style={{ fontSize: 12 }} onClick={() => setPayOpen(e)}>ສະລິບ</button>
                    <button className="btn" style={{ fontSize: 12 }} onClick={() => setEditEmp(e)}>ແກ້ໄຂ</button>
                    <button className="icon-btn danger" title="ລົບພະນັກງານ" onClick={() => handleDelete(e.id)}>
                      <Ic.Trash/>
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {employees.length === 0 && (
              <tr><td colSpan="7" style={{ textAlign: 'center', padding: '32px', color: 'var(--ink-3)' }}>ຍັງບໍ່ມີພະນັກງານ — ກົດປຸ່ມ "ເພີ່ມພະນັກງານ" ເພື່ອເລີ່ມຕົ້ນ</td></tr>
            )}
          </tbody>
          <tfoot>
            <tr style={{ background: 'rgba(124,58,237,0.05)' }}>
              <td colSpan="3" style={{ padding: '14px 18px', fontWeight: 700 }}>ລວມທັງໝົດ</td>
              <td className="mono" style={{ textAlign: 'right', padding: '14px 18px', fontWeight: 700 }}>{fb(totalBase)}</td>
              <td className="mono" style={{ textAlign: 'right', padding: '14px 18px', fontWeight: 700, color: '#34d399' }}>+{fb(totalBonus)}</td>
              <td className="mono" style={{ textAlign: 'right', padding: '14px 18px', fontWeight: 800, fontSize: 14, color: '#a78bfa' }}>{fb(totalPay)}</td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>

      {payOpen && <PayslipModal emp={payOpen} month={month} onClose={() => setPayOpen(null)}/>}
      {(addOpen || editEmp) && (
        <EmployeeModal
          emp={editEmp}
          onClose={() => { setAddOpen(false); setEditEmp(null); }}
          onSave={handleSave}
        />
      )}
    </div>
  );
}

function EmployeeModal({ emp, onClose, onSave }) {
  const isEdit = !!emp;
  const [name, setName] = React.useState(emp?.name || '');
  const [role, setRole] = React.useState(emp?.role || '');
  const [base, setBase] = React.useState(emp?.base ?? '');
  const [bonus, setBonus] = React.useState(emp?.bonus ?? '');
  const [joined, setJoined] = React.useState(emp?.joined || new Date().toISOString().slice(0, 10));
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const handleSave = async () => {
    if (!name.trim() || !role.trim() || base === '' || bonus === '') {
      setError('ກະລຸນາປ້ອນຂໍ້ມູນໃຫ້ຄົບ (ຊື່ / ຕຳແໜ່ງ / ເງິນເດືອນ / ໂບນັດ)');
      return;
    }
    const baseNum = Number(String(base).replace(/,/g, ''));
    const bonusNum = Number(String(bonus).replace(/,/g, ''));
    if (isNaN(baseNum) || baseNum < 0 || isNaN(bonusNum) || bonusNum < 0) {
      setError('ຕົວເລກເງິນເດືອນ/ໂບນັດບໍ່ຖືກຕ້ອງ');
      return;
    }
    setSaving(true);
    await onSave({
      ...(emp || {}),
      name: name.trim(),
      role: role.trim(),
      base: baseNum,
      bonus: bonusNum,
      joined,
    });
  };

  return (
    <window.UI.Modal
      title={isEdit ? 'ແກ້ໄຂຂໍ້ມູນພະນັກງານ' : 'ເພີ່ມພະນັກງານໃໝ່'}
      subtitle={isEdit ? `${emp.code} · ປັບເງິນເດືອນ / ໂບນັດ / ຕຳແໜ່ງ` : 'ປ້ອນຂໍ້ມູນພະນັກງານແລະເງິນເດືອນ'}
      onClose={onClose}
      footer={<>
        {error && <span style={{ color: '#fb7185', fontSize: 12, marginRight: 'auto' }}>{error}</span>}
        <button className="btn" onClick={onClose}>ຍົກເລີກ</button>
        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
          <Ic.Check/> {saving ? 'ກຳລັງບັນທຶກ...' : (isEdit ? 'ບັນທຶກການແກ້ໄຂ' : 'ເພີ່ມພະນັກງານ')}
        </button>
      </>}>
      <div className="form-grid">
        <div className="field full"><label>ຊື່-ນາມສະກຸນ</label><input className="input" placeholder="ເຊັ່ນ ສົມຊາຍ ໃຈດີ" value={name} onChange={e => setName(e.target.value)}/></div>
        <div className="field"><label>ຕຳແໜ່ງ</label>
          <select className="select" value={role} onChange={e => setRole(e.target.value)}>
            <option value="">ເລືອກຕຳແໜ່ງ</option>
            <option>ຊ່າງສ້ອມຫຼັກ</option>
            <option>ຊ່າງສ້ອມອາວຸໂສ</option>
            <option>ຊ່າງອາໄຫຼ່</option>
            <option>ພະນັກງານໜ້າຮ້ານ</option>
            <option>ຜູ້ຈັດການຮ້ານ</option>
          </select>
        </div>
        <div className="field"><label>ວັນທີເຂົ້າເຮັດວຽກ</label><input className="input" type="date" value={joined} onChange={e => setJoined(e.target.value)}/></div>
        <div className="field"><label>ເງິນເດືອນພື້ນຖານ (ກີບ)</label><input className="input mono" placeholder="0" value={base} onChange={e => setBase(e.target.value)}/></div>
        <div className="field"><label>ໂບນັດເດືອນນີ້ (ກີບ)</label><input className="input mono" placeholder="0" value={bonus} onChange={e => setBonus(e.target.value)}/></div>
      </div>
    </window.UI.Modal>
  );
}

function PayslipModal({ emp, month, onClose }) {
  const net = emp.base + emp.bonus;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ width: 560 }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
          <div>
            <h2 style={{ margin: 0 }}>ສະລິບເງິນເດືອນ</h2>
            <div className="modal-sub">ງວດ · {month}</div>
          </div>
          <button className="btn btn-icon btn-ghost" onClick={onClose}><Ic.Close/></button>
        </div>

        <div style={{
          marginTop: 12,
          padding: 18,
          borderRadius: 14,
          background: 'linear-gradient(135deg, rgba(124,58,237,0.10), rgba(6,182,212,0.05))',
          border: '1px solid rgba(124,58,237,0.20)'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
            <div className={`emp-av ${emp.avatar}`} style={{ width: 48, height: 48, fontSize: 16 }}>{emp.initials}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16, fontWeight: 600 }}>{emp.name}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>{emp.role} · <span className="mono">{emp.code}</span></div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10.5, color: 'var(--ink-3)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>ຍອດສຸດທິ</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: '#a78bfa' }}>{fb(net)}</div>
            </div>
          </div>

          <div className="summary-row">
            <span className="label">ເງິນເດືອນພື້ນຖານ</span>
            <span className="val">{fb(emp.base)}</span>
          </div>
          <div className="summary-row">
            <span className="label">ໂບນັດຈາກວຽກສ້ອມ</span>
            <span className="val" style={{ color: '#34d399' }}>+{fb(emp.bonus)}</span>
          </div>
          <div className="summary-row" style={{ paddingTop: 14, borderTop: '1px solid var(--line-2)', borderBottom: 'none', marginTop: 4 }}>
            <span className="label" style={{ fontWeight: 600, color: 'var(--ink-0)' }}>ລວມຮັບສຸດທິ</span>
            <span className="val" style={{ fontSize: 16, color: '#a78bfa' }}>{fb(net)}</span>
          </div>
        </div>

        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 16, textAlign: 'center' }}>
          PAENG DEE SHOP · ກຳນົດຈ່າຍ 20 ພຶດສະພາ 2026
        </div>

        <div className="modal-actions">
          <button className="btn" onClick={onClose}>ປິດ</button>
          <button className="btn btn-primary"><Ic.Download/> ດາວໂຫຼດ PDF</button>
        </div>
      </div>
    </div>
  );
}

window.PAGES_B = { Expenses, Salary };
