/* screens-config-norms.jsx — /admin/config/dinhmuc — productivity norms (UPH matrix)
   V1 · simple: 1 row per item group, columns = PK types, work type via tab.
   Per-warehouse values (đọc từ scope hiện tại). Chưa có đo đếm thực tế. */

function NormsScreen({ warehouseId }) {
  const CFG = WFP_CFG;
  const { vw, isMobile } = useViewport();
  const wh = WFP.WAREHOUSES.find(w => w.id === warehouseId) || WFP.WAREHOUSES[0];

  // Filters for the matrix
  const [wt, setWt]                = React.useState('WT-PACK');
  const [groupFilter, setGroupFlt] = React.useState('all');
  const [q, setQ]                  = React.useState('');
  const [editing, setEditing]      = React.useState(null);

  // Rows of the matrix
  let groupRows = CFG.ITEM_GROUPS;
  if (groupFilter !== 'all') groupRows = groupRows.filter(g => g.id === groupFilter);
  if (q) groupRows = groupRows.filter(g => (g.name + g.code + g.en).toLowerCase().includes(q.toLowerCase()));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <PageHeader
        breadcrumb={['Cấu hình','Định mức']}
        title="Định mức năng suất"
        subtitle="Bảng UPH theo nhóm ngành hàng × nhóm PK × loại công việc. Nguồn để engine tính WLU và quy đổi sang giờ công."
        status={<WarehouseChip wh={wh}/>}
        actions={
          <>
            <Button variant="outline" icon="download">Xuất Excel</Button>
            <Button variant="primary" icon="plus">Thêm nhóm hàng</Button>
          </>
        }
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20 }}>
        {/* WLU formula explainer */}
        <WluFormulaCard warehouseId={wh.id}/>

        {/* Compact KPI strip — only what we actually know today */}
        <div style={{
          display: 'grid', gap: 12, marginBottom: 16,
          gridTemplateColumns: vw < 720 ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)',
        }}>
          <Metric icon="cube"   label="Nhóm ngành hàng" value={CFG.ITEM_GROUPS.length} sublabel="nhóm đang cấu hình"/>
          <Metric icon="layers" label="Nhóm PK"          value={CFG.PK_TYPES.length}    sublabel="loại danh sách nhặt"/>
          <Metric icon="plan"   label="Loại công việc"  value={'1 / ' + CFG.WORK_TYPES.length}  sublabel="đóng gói · nhặt & kiểm sẽ bổ sung"/>
        </div>

        {/* Matrix */}
        <NormsMatrix
          groupRows={groupRows} workTypeId={wt}
          warehouseId={wh.id}
          wt={wt} setWt={setWt}
          groupFilter={groupFilter} setGroupFlt={setGroupFlt} q={q} setQ={setQ}
          onEdit={(g, p, w) => {
            const n = CFG.findNorm(g.id, p.id, w, wh.id);
            if (n) setEditing({ group: g, pk: p, workTypeId: w, norm: n });
          }}
        />

        {/* Reference data */}
        <div style={{ height: 16 }}/>
        <div style={{
          display: 'grid', gap: 16,
          gridTemplateColumns: vw < 960 ? '1fr' : '1.1fr 1fr',
        }}>
          <ItemGroupsCard/>
          <PkTypesCard/>
        </div>

        <div style={{ height: 16 }}/>
        <ComplexityCard/>
      </div>

      <NormEditDialog open={!!editing} editing={editing} warehouseId={wh.id} onClose={() => setEditing(null)}/>
    </div>
  );
}

// ---------- Warehouse context chip ----------
function WarehouseChip({ wh }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '6px 10px', background: '#eef2ff',
      border: '1px solid rgba(11,67,234,0.16)', borderRadius: 9999,
      fontSize: 12, color: 'var(--bx-primary)',
    }}>
      <Icon name="warehouse" size={12}/>
      <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700 }}>{wh.code}</span>
      <span style={{ color: 'var(--bx-text-muted)' }}>·</span>
      <span>Áp dụng cho kho hiện tại</span>
    </div>
  );
}

// ---------- WLU formula explainer card ----------
function WluFormulaCard({ warehouseId }) {
  const { vw } = useViewport();
  const stacked = vw < 900;
  return (
    <Card style={{ marginBottom: 16 }} bodyStyle={{ padding: 0 }}>
      <div style={{
        display: 'grid', gridTemplateColumns: stacked ? '1fr' : '1.4fr 1fr', gap: 0,
      }}>
        {/* Left: formula */}
        <div style={{ padding: '18px 20px', borderRight: stacked ? 'none' : '1px solid var(--bx-border-muted)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 8, background: '#eef2ff',
              color: 'var(--bx-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="forecast" size={14}/></div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--bx-text-heading)' }}>Cách tính WLU</div>
              <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)' }}>Workload Unit · giờ công quy đổi</div>
            </div>
          </div>
          <div style={{
            background: 'var(--bx-surface-2)', borderRadius: 10, padding: 14,
            fontFamily: 'var(--bx-font-mono)', fontSize: 12.5, lineHeight: 1.8,
            color: 'var(--bx-text-dark)', overflowX: 'auto',
          }}>
            <div>
              <span style={{ color: 'var(--bx-primary)', fontWeight: 700 }}>WLU</span>
              <span style={{ color: 'var(--bx-text-muted)' }}> = </span>
              <span>qty</span>
              <span style={{ color: 'var(--bx-text-muted)' }}> ÷ </span>
              <span style={{ background: '#fefce8', padding: '0 4px', borderRadius: 3 }}>UPH<sub>norm</sub></span>
              <span style={{ color: 'var(--bx-text-muted)' }}> × </span>
              <span style={{ background: '#fef2f2', padding: '0 4px', borderRadius: 3 }}>complexity</span>
              <span style={{ color: 'var(--bx-text-muted)' }}> × </span>
              <span style={{ background: '#eff6ff', padding: '0 4px', borderRadius: 3 }}>month</span>
              <span style={{ color: 'var(--bx-text-muted)' }}> × </span>
              <span style={{ background: '#f0fdf4', padding: '0 4px', borderRadius: 3 }}>sale</span>
            </div>
            <div style={{ marginTop: 8, fontSize: 11.5, color: 'var(--bx-text-muted)' }}>
              UPH<sub>norm</sub> = lookup(nhóm ngành hàng, nhóm PK, loại công việc)
            </div>
          </div>
          <div style={{ display: 'flex', gap: 14, marginTop: 12, flexWrap: 'wrap', fontSize: 11.5 }}>
            <FormulaLegend color="#fefce8" label="Định mức" sublabel="trang này"/>
            <FormulaLegend color="#fef2f2" label="Độ phức tạp" sublabel="trang này"/>
            <FormulaLegend color="#eff6ff" label="Hệ số tháng" sublabel="trong Tham số"/>
            <FormulaLegend color="#f0fdf4" label="Loại sale" sublabel="trong Tham số"/>
          </div>
        </div>
        {/* Right: live example */}
        <WluExample warehouseId={warehouseId}/>
      </div>
    </Card>
  );
}

function FormulaLegend({ color, label, sublabel }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <span style={{ width: 12, height: 12, borderRadius: 3, background: color, border: '1px solid var(--bx-border-muted)' }}/>
      <span style={{ fontWeight: 600, color: 'var(--bx-text-dark)' }}>{label}</span>
      <span style={{ color: 'var(--bx-text-muted)' }}>· {sublabel}</span>
    </div>
  );
}

function WluExample({ warehouseId }) {
  const CFG = WFP_CFG;
  const [exIdx, setExIdx] = React.useState(0);
  const ex = CFG.WLU_EXAMPLES[exIdx];
  const r = CFG.computeWLU(ex, warehouseId);
  const g = CFG.ITEM_GROUPS.find(x => x.id === ex.itemGroupId);
  const wt = CFG.WORK_TYPES.find(x => x.id === ex.workTypeId);
  return (
    <div style={{ padding: '18px 20px', background: 'var(--bx-page-bg)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>Ví dụ</div>
        <div style={{ display: 'flex', gap: 4 }}>
          {CFG.WLU_EXAMPLES.map((_, i) => (
            <button key={i} onClick={() => setExIdx(i)} style={{
              width: 22, height: 22, borderRadius: 6, border: 'none', cursor: 'pointer',
              background: i === exIdx ? 'var(--bx-primary)' : '#fff',
              color: i === exIdx ? '#fff' : 'var(--bx-text-body)',
              fontSize: 11, fontWeight: 600, fontFamily: 'var(--bx-font-mono)',
              boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
            }}>{i + 1}</button>
          ))}
        </div>
      </div>
      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--bx-text-heading)', marginBottom: 4 }}>{ex.label}</div>
      <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)', marginBottom: 12 }}>
        {g.name} · {CFG.PK_TYPES.find(p => p.id === ex.pkTypeId).name} · {wt.name}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <ExLine label="Khối lượng" value={fmt.int(ex.qty) + ' đơn vị'}/>
        <ExLine label="UPH định mức" value={r.norm.uph + ' u/h'} chip="#fefce8"/>
        <ExLine label="× Độ phức tạp" value={r.complexity.mult + ' (' + r.complexity.name + ')'} chip="#fef2f2"/>
        <ExLine label="× Hệ số tháng" value={r.monthly.factor + ' (T' + r.monthly.month + ')'} chip="#eff6ff"/>
        <ExLine label="× Loại sale" value={r.sale.mult + ' (' + r.sale.name + ')'} chip="#f0fdf4"/>
        <div style={{
          marginTop: 8, padding: '10px 12px', background: '#eef2ff', borderRadius: 8,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--bx-primary)' }}>= WLU (giờ công quy đổi)</span>
          <span style={{ fontSize: 18, fontWeight: 700, color: 'var(--bx-primary)', fontFamily: 'var(--bx-font-mono)', fontVariantNumeric: 'tabular-nums' }}>
            {r.wlu.toFixed(1)} h
          </span>
        </div>
      </div>
    </div>
  );
}

function ExLine({ label, value, chip }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12 }}>
      <span style={{ color: 'var(--bx-text-muted)' }}>{label}</span>
      <span style={{
        fontFamily: 'var(--bx-font-mono)', fontWeight: 600, color: 'var(--bx-text-dark)',
        background: chip || 'transparent',
        padding: chip ? '2px 6px' : 0, borderRadius: 4,
      }}>{value}</span>
    </div>
  );
}

// ---------- Matrix table ----------
function NormsMatrix({ groupRows, workTypeId, warehouseId, wt, setWt, groupFilter, setGroupFlt, q, setQ, onEdit }) {
  const CFG = WFP_CFG;
  const wtObj = CFG.WORK_TYPES.find(w => w.id === workTypeId);
  const pkCols = CFG.PK_TYPES;

  return (
    <Card padding={0}>
      <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--bx-border-muted)', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ width: 240 }}>
          <Input icon="search" placeholder="Tìm nhóm ngành hàng…" value={q} onChange={e => setQ(e.target.value)} size="sm"/>
        </div>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, height: 30, padding: '0 12px',
          background: '#eef2ff', borderRadius: 9999, color: 'var(--bx-primary)',
          fontSize: 12.5, fontWeight: 600,
        }}>
          <Icon name={wtObj.icon} size={12}/>
          <span>{wtObj.name}</span>
          <span style={{ color: 'var(--bx-text-muted)', fontWeight: 400, fontSize: 11 }}>· giai đoạn 1</span>
        </div>
        <div style={{ width: 200 }}>
          <Select size="sm" value={groupFilter} onChange={e => setGroupFlt(e.target.value)}
            options={[{ value: 'all', label: 'Tất cả nhóm hàng' }, ...CFG.ITEM_GROUPS.map(g => ({ value: g.id, label: g.code + ' · ' + g.name }))]}/>
        </div>
        <div style={{ flex: 1 }}/>
        <span style={{ fontSize: 11.5, color: 'var(--bx-text-muted)' }}>
          UPH tham chiếu · L2 chính thức · đơn vị {wtObj.unit}
        </span>
      </div>

      <div style={{ width: '100%', overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 13 }}>
          <thead>
            <tr>
              <th style={thStyleMain(220)}>Nhóm ngành hàng</th>
              {pkCols.map(p => (
                <th key={p.id} style={thStyleCell()}>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 11.5, color: 'var(--bx-text-dark)', fontWeight: 700 }}>{p.code}</span>
                    <span style={{ fontSize: 10, color: 'var(--bx-text-muted)', textTransform: 'none', letterSpacing: 'normal', fontWeight: 400, marginTop: 2 }}>{p.name}</span>
                  </div>
                </th>
              ))}
              <th style={thStyleCell(80)}>TB</th>
              <th style={thStyleCell(60)}></th>
            </tr>
          </thead>
          <tbody>
            {groupRows.map((g, i) => {
              const cellsForRow = pkCols.map(p => CFG.findNorm(g.id, p.id, workTypeId, warehouseId));
              const avg = Math.round(cellsForRow.reduce((a, c) => a + (c ? c.uph : 0), 0) / cellsForRow.length);
              return (
                <tr key={g.id} style={{ background: i % 2 === 1 ? 'rgba(245,245,245,0.4)' : '#fff' }}>
                  <td style={tdGroupCell()}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{
                        width: 32, height: 32, borderRadius: 8,
                        background: 'var(--bx-surface-2)',
                        color: 'var(--bx-text-dark)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontFamily: 'var(--bx-font-mono)', fontSize: 10, fontWeight: 700,
                      }}>{g.code}</div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--bx-text-dark)' }}>{g.name}</div>
                        <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', marginTop: 2 }}>
                          <Badge kind={g.defaultComplexity === 'COMPLEX' ? 'CRITICAL' : g.defaultComplexity === 'MEDIUM' ? 'WARNING' : 'APPROVED'} size="sm">
                            {CFG.COMPLEXITY.find(c => c.id === g.defaultComplexity).name}
                          </Badge>
                        </div>
                      </div>
                    </div>
                  </td>
                  {cellsForRow.map((cell, j) => (
                    <td key={j} style={tdNumCell()}>
                      <NormCell norm={cell} onEdit={() => onEdit(g, pkCols[j], workTypeId)}/>
                    </td>
                  ))}
                  <td style={tdNumCell(true)}>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--bx-text-dark)' }}>{avg}</span>
                  </td>
                  <td style={tdNumCell()}>
                    <IconBtn name="ellipsis" title="Tùy chọn"/>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div style={{
        padding: '10px 14px', borderTop: '1px solid var(--bx-border-muted)',
        background: 'var(--bx-surface-2)', display: 'flex', gap: 16, fontSize: 11.5, color: 'var(--bx-text-muted)', flexWrap: 'wrap',
      }}>
        <span><Icon name="info" size={11}/>&nbsp; Bấm vào ô để chỉnh sửa · giá trị áp dụng riêng cho kho hiện tại</span>
        <div style={{ flex: 1 }}/>
        <span><Icon name="lock" size={11}/>&nbsp; Nhặt hàng, kiểm hàng & B2B sẽ bổ sung ở giai đoạn sau</span>
      </div>
    </Card>
  );
}

function thStyleMain(w) {
  return {
    background: 'var(--bx-surface-2)', textAlign: 'left',
    padding: '10px 14px', fontSize: 11, fontWeight: 600, color: 'var(--bx-text-muted)',
    letterSpacing: '0.04em', textTransform: 'uppercase',
    borderBottom: '1px solid var(--bx-border-muted)', width: w,
    position: 'sticky', left: 0, zIndex: 1,
  };
}
function thStyleCell(w) {
  return {
    background: 'var(--bx-surface-2)', textAlign: 'right',
    padding: '8px 14px', fontSize: 11, fontWeight: 600, color: 'var(--bx-text-muted)',
    letterSpacing: '0.04em', textTransform: 'uppercase',
    borderBottom: '1px solid var(--bx-border-muted)', width: w, whiteSpace: 'nowrap',
  };
}
function tdGroupCell() {
  return {
    padding: '10px 14px', borderBottom: '1px solid var(--bx-border-muted)',
    position: 'sticky', left: 0, background: 'inherit', zIndex: 1,
  };
}
function tdNumCell(strong) {
  return {
    padding: '6px 14px', borderBottom: '1px solid var(--bx-border-muted)',
    textAlign: 'right', verticalAlign: 'middle',
    background: strong ? 'rgba(11,67,234,0.04)' : undefined,
  };
}

function NormCell({ norm, onEdit }) {
  if (!norm) return <span style={{ color: 'var(--bx-text-muted)' }}>—</span>;
  return (
    <button onClick={onEdit} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      minWidth: 56, border: '1px solid transparent', background: 'transparent',
      padding: '6px 10px', borderRadius: 8, cursor: 'pointer',
      fontFamily: 'var(--bx-font-mono)', fontSize: 13.5, fontWeight: 600,
      color: 'var(--bx-text-dark)', fontVariantNumeric: 'tabular-nums',
    }}
    onMouseEnter={e => { e.currentTarget.style.background = '#eef2ff'; e.currentTarget.style.borderColor = 'var(--bx-border-muted)'; }}
    onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = 'transparent'; }}
    title="Bấm để chỉnh sửa">
      {norm.uph}
    </button>
  );
}

// ---------- Complexity card ----------
function ComplexityCard() {
  const CFG = WFP_CFG;
  return (
    <Card title="Hệ số độ phức tạp" subtitle="Nhân vào UPH định mức để ra UPH hiệu dụng. Mỗi nhóm ngành hàng có một mức mặc định.">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
        {CFG.COMPLEXITY.map(c => {
          const groupsUsing = CFG.ITEM_GROUPS.filter(g => g.defaultComplexity === c.id);
          return (
            <div key={c.id} style={{
              border: '1px solid var(--bx-border-muted)', borderRadius: 12, padding: 16,
              background: c.bg, display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 700, color: c.color }}>{c.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', marginTop: 2 }}>{c.en}</div>
                </div>
                <div style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 26, fontWeight: 700, color: c.color, fontVariantNumeric: 'tabular-nums' }}>
                  ×{c.mult.toFixed(2)}
                </div>
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--bx-text-body)', lineHeight: 1.5 }}>{c.desc}</div>
              <div style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 10 }}>
                <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, marginBottom: 6 }}>
                  {groupsUsing.length} nhóm áp dụng
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {groupsUsing.length === 0 ? <span style={{ fontSize: 11.5, color: 'var(--bx-text-muted)' }}>—</span> :
                    groupsUsing.map(g => (
                      <span key={g.id} style={{
                        background: '#fff', padding: '2px 8px', borderRadius: 9999, fontSize: 11,
                        color: 'var(--bx-text-dark)', border: '1px solid rgba(0,0,0,0.06)',
                      }}>{g.name}</span>
                    ))}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

// ---------- Item groups card (simplified — no measured data) ----------
function ItemGroupsCard() {
  const CFG = WFP_CFG;
  return (
    <Card title="Nhóm ngành hàng" subtitle={CFG.ITEM_GROUPS.length + ' nhóm · phân loại theo độ phức tạp xử lý'} padding={0}
      actions={<Button variant="ghost" icon="plus" size="sm">Thêm</Button>}>
      <Table
        columns={[
          { header: 'Mã', mono: true, width: 70, render: g => <span style={{ fontWeight: 700, color: 'var(--bx-text-dark)' }}>{g.code}</span> },
          { header: 'Tên nhóm', render: g => (
            <div>
              <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--bx-text-dark)' }}>{g.name}</div>
              <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{g.en}</div>
            </div>
          )},
          { header: 'Độ phức tạp', render: g => {
            const c = CFG.COMPLEXITY.find(x => x.id === g.defaultComplexity);
            return <Badge kind={c.id === 'COMPLEX' ? 'CRITICAL' : c.id === 'MEDIUM' ? 'WARNING' : 'APPROVED'} size="sm">{c.name}</Badge>;
          }},
          { header: '', width: 48, align: 'right', render: () => <IconBtn name="edit" title="Sửa"/> },
        ]}
        rows={CFG.ITEM_GROUPS} getRowKey={g => g.id}
      />
    </Card>
  );
}

// ---------- PK types card (simplified) ----------
function PkTypesCard() {
  const CFG = WFP_CFG;
  return (
    <Card title="Nhóm PK · loại danh sách nhặt" subtitle={CFG.PK_TYPES.length + ' loại · B2C only (giai đoạn 1)'} padding={0}
      actions={<Button variant="ghost" icon="plus" size="sm">Thêm</Button>}>
      <Table
        columns={[
          { header: 'Mã', mono: true, width: 70, render: p => <span style={{ fontWeight: 700 }}>{p.code}</span> },
          { header: 'Tên', render: p => (
            <div>
              <div style={{ fontWeight: 600, color: 'var(--bx-text-dark)' }}>{p.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)', marginTop: 2, whiteSpace: 'normal' }}>{p.description}</div>
            </div>
          )},
          { header: '', width: 48, align: 'right', render: () => <IconBtn name="edit" title="Sửa"/> },
        ]}
        rows={CFG.PK_TYPES} getRowKey={p => p.id}
      />
    </Card>
  );
}

// ---------- Edit dialog ----------
function NormEditDialog({ open, editing, warehouseId, onClose }) {
  const CFG = WFP_CFG;
  const [value, setValue] = React.useState('');
  const [reason, setReason] = React.useState('');
  React.useEffect(() => { if (open && editing) { setValue(String(editing.norm.uph)); setReason(''); }}, [open, editing]);
  if (!editing) return null;
  const wt = CFG.WORK_TYPES.find(w => w.id === editing.workTypeId);
  const wh = WFP.WAREHOUSES.find(w => w.id === warehouseId);
  const errors = {};
  if (!value || isNaN(Number(value))) errors.value = 'Cần một số hợp lệ';
  else if (Number(value) <= 0) errors.value = 'Phải > 0';
  if (!reason || reason.length < 8) errors.reason = 'Cần lý do tối thiểu 8 ký tự';
  const valid = Object.keys(errors).length === 0;
  return (
    <Dialog open={open} onClose={onClose} width={520}
      title="Chỉnh định mức UPH"
      subtitle={editing.group.name + ' · ' + editing.pk.name + ' · ' + wt.name}
      footer={
        <>
          <Button variant="outline" onClick={onClose}>Hủy</Button>
          <Button variant="primary" disabled={!valid} icon="check" onClick={onClose}>Lưu</Button>
        </>
      }>
      <div style={{
        marginBottom: 14, padding: '10px 12px', background: '#eef2ff',
        borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <Icon name="warehouse" size={13} style={{ color: 'var(--bx-primary)' }}/>
        <span style={{ fontSize: 12, color: 'var(--bx-text-dark)' }}>
          Áp dụng cho kho <b style={{ fontFamily: 'var(--bx-font-mono)' }}>{wh ? wh.code : '—'}</b>. Các kho khác giữ giá trị riêng.
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="UPH hiện tại">
          <Input value={String(editing.norm.uph)} disabled/>
        </Field>
        <Field label="UPH mới" required error={errors.value} hint={'Đơn vị: ' + wt.unit}>
          <Input value={value} onChange={e => setValue(e.target.value)} error={errors.value}/>
        </Field>
        <Field label="Hiệu lực từ" hint="Áp dụng cho mọi kế hoạch chạy sau thời điểm này">
          <Input type="datetime-local" value="2026-05-19T00:00"/>
        </Field>
        <Field label="Nguồn dữ liệu">
          <Select value="manual" onChange={() => {}}
            options={[{ value: 'manual', label: 'Thủ công' }, { value: 'measurement', label: 'Đo đếm thực tế' }]}/>
        </Field>
        <Field label="Lý do thay đổi" required error={errors.reason} style={{ gridColumn: '1 / span 2' }}
          hint="Hiển thị trong nhật ký kiểm toán">
          <Input value={reason} onChange={e => setReason(e.target.value)} placeholder="VD: hiệu chuẩn ban đầu theo ước tính của trưởng kho"/>
        </Field>
      </div>
    </Dialog>
  );
}

Object.assign(window, { NormsScreen });
