// ELS HRM — Module 12: Cấu hình — một mục "Cấu hình" (trong nhóm Hệ thống) mở ra màn nhiều tab
// Tab "Trường tùy chỉnh" đầy đủ; 3 tab Chức danh / Địa điểm / Bậc lương: danh mục tham chiếu (CRUD)

// ─── Local style constants (mirror employee-pim-screens.jsx) ─────────────────
const CF_TABLE = "w-full border-collapse text-sm "
  + "[&_thead_th]:border-b [&_thead_th]:border-border [&_thead_th]:bg-muted [&_thead_th]:px-3.5 [&_thead_th]:py-2.5 [&_thead_th]:text-left [&_thead_th]:text-xs [&_thead_th]:font-semibold [&_thead_th]:uppercase [&_thead_th]:tracking-[0.04em] [&_thead_th]:text-muted-foreground [&_thead_th]:whitespace-nowrap "
  + "[&_tbody_td]:border-b [&_tbody_td]:border-border [&_tbody_td]:px-3.5 [&_tbody_td]:py-3 [&_tbody_td]:align-middle [&_tbody_td]:text-foreground "
  + "[&_tbody_tr:last-child_td]:border-0 [&_tbody_tr:hover]:bg-muted";
const CF_CARD = "rounded-xl border border-border bg-card shadow-xs";
const CF_INP  = "h-9 w-full rounded-md border border-input bg-transparent px-3 text-base text-foreground shadow-xs placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring";
const CF_SEL  = "h-9 w-full cursor-pointer appearance-none rounded-md border border-input bg-transparent px-3 text-base text-foreground shadow-xs transition-colors focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring";

// ─── Khung màn "Cấu hình" + thanh tab (mỗi tab là một mục) ───────────────────
const ADMIN_TABS = [
  { id:'custom-fields', label:'Trường tùy chỉnh', icon:'filter'    },
  { id:'job-titles',    label:'Chức danh',        icon:'briefcase' },
  { id:'locations',     label:'Địa điểm',         icon:'map-pin'   },
  { id:'pay-grades',    label:'Bậc lương',        icon:'dollar'    },
];

const AdminTabBar = ({ active }) => (
  <div className="flex shrink-0 items-center gap-0.5 border-b border-border bg-card px-2">
    {ADMIN_TABS.map(t => {
      const on = t.id === active;
      return (
        <div key={t.id}
          className={"relative flex cursor-pointer items-center gap-1.5 px-3.5 py-2.5 text-sm transition-colors "
            + (on ? "font-semibold text-primary" : "font-medium text-muted-foreground hover:text-foreground")}>
          <Icon name={t.icon} size={14} />
          {t.label}
          {on && <span className="absolute inset-x-2.5 -bottom-px h-[2px] rounded-t-sm bg-primary" />}
        </div>
      );
    })}
  </div>
);

// Dải chú thích quyền — khu Cấu hình chỉ Quản trị viên + Quản lý Nhân sự xem/chỉnh sửa.
// Riêng 3 danh mục (chức danh/địa điểm/bậc lương) còn mở route /lookup cho mọi nhân viên
// để hiển thị tên + dropdown ở Hồ sơ nhân viên (PIM) và ESS — không lộ màn quản trị.
const AdminPermNote = ({ tab }) => {
  const isCatalog = tab !== 'custom-fields';
  return (
    <div className="flex shrink-0 flex-wrap items-center gap-x-4 gap-y-1.5 border-b border-border bg-muted/40 px-5 py-2 text-2xs text-muted-foreground">
      <span className="inline-flex items-center gap-1.5 font-semibold text-foreground">
        <Icon name="shield" size={12} style={{ color:'var(--color-primary)' }} />
        Phân quyền
      </span>
      <span className="inline-flex flex-wrap items-center gap-1.5">
        Xem &amp; chỉnh sửa
        <code className="rounded-sm bg-muted px-[5px] py-px font-mono text-[10px]">
          {isCatalog ? 'data:*:all + action:*' : 'screen:config + action:custom_field:manage'}
        </code>
        :
        <Badge variant="primary">Quản trị viên</Badge>
        <Badge variant="primary">Quản lý Nhân sự</Badge>
      </span>
      {isCatalog && (
        <span className="inline-flex items-center gap-1.5 border-l border-border pl-4">
          <Icon name="users" size={11} />
          Tra cứu (dropdown ở Hồ sơ NV / ESS) <code className="rounded-sm bg-muted px-[5px] py-px font-mono text-[10px]">/lookup</code>: mọi nhân viên
        </span>
      )}
    </div>
  );
};

// Sidebar chỉ có 1 mục "Cấu hình" (active='admin'); breadcrumb Hệ thống › Cấu hình; thanh tab ở đầu màn.
const AdminShell = ({ tab, children }) => (
  <HRMShell active="admin" title="Danh mục" crumbs={['Hệ thống', 'Danh mục']}>
    <div className="flex flex-col overflow-hidden rounded-xl border border-border bg-card shadow-xs">
      <AdminTabBar active={tab} />
      {children}
    </div>
  </HRMShell>
);

// ─── Field-type config ────────────────────────────────────────────────────────
const CF_TYPES = {
  text:     { label:'Văn bản',        icon:'file-text',    soft:'var(--color-info-soft)',        fg:'var(--color-info)'        },
  number:   { label:'Số',             icon:'trending-up',  soft:'var(--color-success-soft)',     fg:'var(--color-success)'     },
  date:     { label:'Ngày',           icon:'calendar',     soft:'var(--color-warning-soft)',     fg:'oklch(0.52 0.14 65)'      },
  dropdown: { label:'Danh sách chọn', icon:'filter',       soft:'var(--color-primary-soft)',     fg:'var(--color-primary)'     },
  checkbox: { label:'Hộp kiểm',      icon:'check-circle', soft:'oklch(0.958 0.030 320)',        fg:'oklch(0.564 0.198 320)'   },
};

// ─── Sample data ──────────────────────────────────────────────────────────────
const CF_DATA = [
  { id:'cf01', label:'Số chứng chỉ nghề',         name:'certificate_number',   type:'text',     required:true,  ess:false, order:1, status:'active',   opts:null },
  { id:'cf02', label:'Số năm kinh nghiệm',         name:'years_of_experience',  type:'number',   required:false, ess:false, order:2, status:'active',   opts:null },
  { id:'cf03', label:'Ngày cấp bằng lái xe',       name:'license_issue_date',   type:'date',     required:false, ess:true,  order:3, status:'active',   opts:null },
  { id:'cf04', label:'Cỡ áo đồng phục',            name:'shirt_size',           type:'dropdown', required:true,  ess:true,  order:4, status:'active',   opts:[['xs','XS'],['s','S'],['m','M'],['l','L'],['xl','XL'],['xxl','XXL']] },
  { id:'cf05', label:'Có phương tiện cá nhân',     name:'has_vehicle',          type:'checkbox', required:false, ess:true,  order:5, status:'active',   opts:null },
  { id:'cf06', label:'Nhóm thực phẩm đặc biệt',   name:'dietary_group',        type:'dropdown', required:false, ess:true,  order:6, status:'inactive', opts:[['none','Không'],['vegetarian','Chay'],['halal','Halal'],['other','Khác']] },
  { id:'cf07', label:'Điểm đánh giá nội bộ',       name:'internal_score',       type:'number',   required:false, ess:false, order:7, status:'active',   opts:null },
  { id:'cf08', label:'Ngày xét tăng lương',         name:'salary_review_date',   type:'date',     required:false, ess:false, order:8, status:'inactive', opts:null },
];

// ─── Atoms ────────────────────────────────────────────────────────────────────
const FieldTypePill = ({ type }) => {
  const c = CF_TYPES[type] || CF_TYPES.text;
  return (
    <span className="inline-flex items-center gap-[5px] rounded-md px-[7px] py-[3px] text-xs font-medium"
      style={{ background: c.soft, color: c.fg }}>
      <Icon name={c.icon} size={11} />
      {c.label}
    </span>
  );
};

const SwitchView = ({ on }) => (
  <div className={"relative inline-flex h-[18px] w-8 cursor-default items-center rounded-full transition-colors " + (on ? "bg-primary" : "bg-border-strong")}>
    <span className={"absolute size-3.5 rounded-full bg-white shadow-2xs transition-transform " + (on ? "translate-x-[14px]" : "translate-x-[2px]")} />
  </div>
);

const SwitchRow = ({ label, desc, on }) => (
  <div className="flex items-center justify-between rounded-md border border-border px-3.5 py-3">
    <div>
      <div className="text-sm font-medium">{label}</div>
      {desc && <div className="mt-px text-2xs text-muted-foreground">{desc}</div>}
    </div>
    <SwitchView on={on} />
  </div>
);

const CFFieldLbl = ({ label, req, note, locked }) => (
  <label className="mb-[5px] flex flex-wrap items-center gap-[5px] text-xs font-medium">
    {label}
    {req    && <span className="text-destructive">*</span>}
    {note   && <span className="rounded-sm bg-warning-soft px-[5px] py-px text-2xs font-semibold" style={{ color:'oklch(0.48 0.13 65)' }}>{note}</span>}
    {locked && <span className="rounded-sm bg-muted px-[5px] py-px text-2xs text-muted-foreground">Không thể thay đổi</span>}
  </label>
);

const CFOverlay = ({ children, width = 560 }) => (
  <div className="absolute inset-0 z-50 flex items-center justify-center"
    style={{ background:'rgba(15,20,30,0.28)', backdropFilter:'blur(1.5px)' }}>
    <div className={CF_CARD + " flex max-h-[92%] flex-col overflow-hidden shadow-2xl"} style={{ width }}>
      {children}
    </div>
  </div>
);

// ─── Toolbar ──────────────────────────────────────────────────────────────────
const CFToolbar = ({ filterStatus = 'all' }) => (
  <div className="flex shrink-0 items-center gap-2.5 border-b border-border bg-card px-5 py-3">
    <div className="relative" style={{ flex:'0 0 280px' }}>
      <Icon name="search" size={13} className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
      <input
        className="h-8 w-full rounded-md border border-input bg-transparent pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
        placeholder="Tìm theo nhãn hoặc tên trường…" />
    </div>
    <Select
      options={[{value:'all',label:'Tất cả trạng thái'},{value:'active',label:'Đang dùng'},{value:'inactive',label:'Ngừng dùng'}]}
      defaultValue={filterStatus}
      className="h-8 text-xs" />
    <div className="flex-1" />
    <Btn variant="primary" size="sm" icon="plus">Thêm trường</Btn>
  </div>
);

// ─── Table body ───────────────────────────────────────────────────────────────
const CFTableBody = ({ fields }) => (
  <div className="overflow-auto flex-1">
    <table className={CF_TABLE}>
      <thead>
        <tr>
          <th style={{ minWidth:160 }}>Nhãn</th>
          <th style={{ minWidth:190 }}>Tên trường</th>
          <th style={{ minWidth:148 }}>Kiểu</th>
          <th style={{ minWidth:90 }}>Bắt buộc</th>
          <th style={{ minWidth:110 }}>Hiện NV (ESS)</th>
          <th style={{ minWidth:80 }}>
            <span className="inline-flex items-center gap-1">Thứ tự <Icon name="arrow-up" size={10} /></span>
          </th>
          <th style={{ minWidth:120 }}>Trạng thái</th>
          <th style={{ minWidth:180 }}>Hành động</th>
        </tr>
      </thead>
      <tbody>
        {fields.map(f => {
          const active = f.status === 'active';
          return (
            <tr key={f.id}>
              <td><span className="text-sm font-semibold">{f.label}</span></td>
              <td>
                <code className="rounded-sm bg-muted px-[7px] py-[3px] font-mono text-xs text-muted-foreground">{f.name}</code>
              </td>
              <td><FieldTypePill type={f.type} /></td>
              <td>
                {f.required
                  ? <Badge variant="danger">Bắt buộc</Badge>
                  : <span className="text-xs text-muted-foreground">—</span>}
              </td>
              <td><SwitchView on={f.ess} /></td>
              <td><span className="font-mono text-sm font-bold text-muted-foreground">{f.order}</span></td>
              <td>
                <Badge variant={active ? 'success' : 'neutral'} dot>
                  {active ? 'Đang dùng' : 'Ngừng dùng'}
                </Badge>
              </td>
              <td>
                <div className="flex items-center gap-0.5">
                  <Btn variant="ghost" size="xs" icon="edit">Sửa</Btn>
                  {active
                    ? <Btn variant="ghost" size="xs" icon="pause-circle"
                        style={{ color:'var(--color-muted-foreground)' }}>Ngừng dùng</Btn>
                    : <Btn variant="ghost" size="xs" icon="rotate-ccw"
                        style={{ color:'var(--color-success)' }}>Kích hoạt lại</Btn>}
                </div>
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

const CFPager = ({ total }) => (
  <div className="flex shrink-0 items-center justify-between border-t border-border px-5 py-2.5 text-xs text-muted-foreground">
    <span>Hiển thị <b className="text-foreground">{total}</b> / <b className="text-foreground">{total}</b> trường</span>
    <div className="flex items-center gap-1">
      <Btn variant="outline" size="xs" iconOnly icon="chevron-left" disabled />
      <Btn variant="primary" size="xs">1</Btn>
      <Btn variant="outline" size="xs" iconOnly icon="chevron-right" disabled />
    </div>
  </div>
);

// ─── Add / Edit form dialog ───────────────────────────────────────────────────
const CFFormDialog = ({ mode = 'add', showDropdownOpts = false, duplicateError = false }) => {
  const isEdit    = mode === 'edit';
  const editField = CF_DATA[3]; // shirt_size — dropdown, for edit demo

  const dropdownSection = showDropdownOpts || (isEdit && editField.type === 'dropdown');
  const demoOpts = isEdit ? editField.opts : [['xs','XS'],['s','S'],['m','M']];

  return (
    <>
      {/* Header */}
      <div className="flex shrink-0 items-center justify-between border-b border-border px-[22px] py-4">
        <div className="flex items-center gap-[11px]">
          <div className="grid size-9 shrink-0 place-items-center rounded-md bg-primary-soft">
            <Icon name={isEdit ? 'edit' : 'plus'} size={17} style={{ color:'var(--color-primary)' }} />
          </div>
          <div>
            <div className="text-md font-bold">{isEdit ? 'Sửa trường tùy chỉnh' : 'Thêm trường tùy chỉnh'}</div>
            <div className="mt-px text-xs text-muted-foreground">
              {isEdit
                ? `Trường: ${editField.name} · chỉ sửa được nhãn, mô tả, tùy chọn và cấu hình`
                : 'Trường mới có hiệu lực ngay với các hồ sơ được tạo sau'}
            </div>
          </div>
        </div>
        <Btn variant="ghost" size="sm" iconOnly icon="x" />
      </div>

      {/* Body */}
      <div className="overflow-y-auto px-[22px] py-5" style={{ maxHeight:510 }}>
        {/* Nhãn */}
        <div className="mb-3.5">
          <CFFieldLbl label="Nhãn hiển thị" req />
          <input className={CF_INP} defaultValue={isEdit ? editField.label : ''}
            placeholder="VD: Cỡ áo đồng phục, Số chứng chỉ…" />
        </div>

        <div className="grid grid-cols-2 gap-3.5">
          {/* Tên trường (mã) */}
          <div className="col-span-full">
            <CFFieldLbl label="Tên trường (mã)" req
              note={!isEdit ? 'Không thể thay đổi sau khi tạo' : undefined}
              locked={isEdit} />
            {isEdit ? (
              <div className="flex h-9 items-center gap-2 rounded-md border border-border-strong bg-muted px-3">
                <code className="flex-1 font-mono text-sm text-muted-foreground">{editField.name}</code>
                <span className="text-xs text-muted-foreground">· chỉ đọc</span>
              </div>
            ) : (
              <>
                <input
                  className={CF_INP + " font-mono"}
                  defaultValue={duplicateError ? 'dietary_group' : ''}
                  placeholder="snake_case · tự sinh từ nhãn, có thể chỉnh"
                  style={duplicateError ? { borderColor:'var(--color-destructive)', boxShadow:'0 0 0 3px oklch(0.601 0.215 12 / 0.18)' } : {}}
                />
                {duplicateError ? (
                  <div className="mt-2 rounded-md px-3.5 py-3"
                    style={{ background:'var(--color-destructive-soft)', border:'1px solid oklch(0.601 0.215 12 / 0.25)' }}>
                    <div className="flex items-start gap-2.5">
                      <Icon name="alert-circle" size={14} className="mt-px shrink-0 text-destructive" />
                      <div className="text-xs leading-[1.65]">
                        <span className="font-bold text-destructive">Tên trường này đã tồn tại</span>
                        {' '}(đang ngừng dùng). Hãy{' '}
                        <b>kích hoạt lại trường cũ</b> thay vì tạo mới để giữ nguyên dữ liệu nhân viên đã nhập.
                        <div className="mt-2">
                          <button className="inline-flex items-center gap-1 font-semibold text-primary hover:underline">
                            <Icon name="rotate-ccw" size={12} />
                            Xem trường "dietary_group" (Ngừng dùng) và kích hoạt lại →
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="mt-1 text-xs text-muted-foreground">
                    Chỉ chữ thường a–z, số 0–9, dấu gạch dưới — bắt đầu bằng chữ cái
                  </div>
                )}
              </>
            )}
          </div>

          {/* Kiểu dữ liệu */}
          <div className="col-span-full">
            <CFFieldLbl label="Kiểu dữ liệu" req
              note={!isEdit ? 'Không thể thay đổi sau khi tạo' : undefined}
              locked={isEdit} />
            {isEdit ? (
              <div className="flex h-9 items-center gap-2 rounded-md border border-border-strong bg-muted px-3">
                <FieldTypePill type={editField.type} />
                <span className="text-xs text-muted-foreground">· chỉ đọc</span>
              </div>
            ) : (
              <Select
                options={Object.entries(CF_TYPES).map(([k,v]) => ({ value:k, label:v.label }))}
                defaultValue={showDropdownOpts ? 'dropdown' : 'text'}
                className="w-full" />
            )}
          </div>

          {/* Tùy chọn — chỉ khi type = dropdown */}
          {dropdownSection && (
            <div className="col-span-full">
              <div className="mb-2 flex items-center justify-between">
                <CFFieldLbl label="Tùy chọn" req />
                <Btn variant="soft" size="xs" icon="plus">Thêm tùy chọn</Btn>
              </div>
              <div className="rounded-md border border-border p-3">
                <div className="mb-2 grid grid-cols-[1fr_16px_1fr_32px] items-center gap-x-2 gap-y-1.5 text-2xs font-semibold uppercase tracking-[0.06em] text-muted-foreground">
                  <span className="px-1">Giá trị (key)</span>
                  <span></span>
                  <span className="px-1">Nhãn hiển thị</span>
                  <span></span>
                </div>
                {demoOpts.map(([val, lbl], i) => (
                  <div key={i} className="grid grid-cols-[1fr_16px_1fr_32px] items-center gap-x-2 gap-y-1.5 mb-1.5">
                    <input className={CF_INP.replace('h-9','h-8') + " font-mono text-xs"} defaultValue={val} placeholder="vd: xs" />
                    <Icon name="arrow-right" size={12} className="shrink-0 justify-self-center text-muted-foreground" />
                    <input className={CF_INP.replace('h-9','h-8') + " text-xs"} defaultValue={lbl} placeholder="Nhãn hiển thị" />
                    <Btn variant="ghost" size="sm" iconOnly icon="trash" className="text-muted-foreground" />
                  </div>
                ))}
                <div className="mt-2 text-2xs text-muted-foreground">
                  Bắt buộc ít nhất 1 tùy chọn · Giá trị (key) không nên thay đổi sau khi đã có dữ liệu
                </div>
              </div>
            </div>
          )}

          {/* Mô tả */}
          <div className="col-span-full">
            <CFFieldLbl label="Mô tả" />
            <textarea
              className="w-full resize-none rounded-md border border-input bg-transparent px-3 py-2.5 text-base text-foreground shadow-xs placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
              rows={2}
              defaultValue={isEdit ? 'Cỡ áo đồng phục của nhân viên để phát đồng phục định kỳ' : ''}
              placeholder="Mô tả mục đích / gợi ý điền trường này (tuỳ chọn)…" />
          </div>
        </div>

        {/* Toggles */}
        <div className="mt-3.5 grid grid-cols-2 gap-2.5">
          <SwitchRow label="Bắt buộc nhập"
            desc="HR / nhân viên bắt buộc điền trường này"
            on={isEdit ? editField.required : false} />
          <SwitchRow label="Hiện với nhân viên (ESS)"
            desc="Nhân viên xem / sửa trên hồ sơ của mình"
            on={isEdit ? editField.ess : true} />
        </div>

        {/* Thứ tự */}
        <div className="mt-3.5">
          <CFFieldLbl label="Thứ tự hiển thị" />
          <div className="flex items-center gap-3">
            <input className={CF_INP} type="number" min={1}
              defaultValue={isEdit ? editField.order : (CF_DATA.length + 1)}
              style={{ width:100 }} />
            <span className="text-xs text-muted-foreground">Sắp xếp tăng dần trong hồ sơ nhân viên</span>
          </div>
        </div>
      </div>

      {/* Footer */}
      <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
        <Btn variant="outline" size="sm">Hủy</Btn>
        <Btn variant="primary" size="sm" icon={isEdit ? 'check' : 'plus'}
          disabled={duplicateError}>
          {isEdit ? 'Lưu thay đổi' : 'Tạo trường'}
        </Btn>
      </div>
    </>
  );
};

// ─── Deactivate confirm ───────────────────────────────────────────────────────
const CFDeactivateDialog = () => {
  const f = CF_DATA[0];
  return (
    <>
      <div className="flex shrink-0 items-center gap-3 border-b border-border px-[22px] py-[18px]">
        <div className="grid size-10 shrink-0 place-items-center rounded-md bg-warning-soft">
          <Icon name="pause-circle" size={20} style={{ color:'oklch(0.52 0.14 65)' }} />
        </div>
        <div>
          <div className="text-md font-bold">Ngừng dùng trường?</div>
          <div className="mt-0.5 text-xs text-muted-foreground">
            "{f.label}" ·{' '}<code className="font-mono">{f.name}</code>
          </div>
        </div>
      </div>
      <div className="px-[22px] py-5">
        <div className="mb-4 rounded-md p-3.5 text-sm leading-[1.65]"
          style={{ background:'var(--color-warning-soft)', border:'1px solid oklch(0.835 0.158 80 / 0.3)', color:'oklch(0.38 0.08 65)' }}>
          <div className="flex items-start gap-2.5">
            <Icon name="alert-triangle" size={15} className="mt-[2px] shrink-0" style={{ color:'oklch(0.52 0.14 65)' }} />
            <div>
              Trường sẽ <b>ẩn khỏi các hồ sơ mới</b>, nhưng{' '}
              <b>dữ liệu đã nhập của nhân viên vẫn được giữ nguyên</b>.
              Bạn có thể kích hoạt lại bất kỳ lúc nào — dữ liệu cũ xuất hiện trở lại ngay.
            </div>
          </div>
        </div>
        <div className="rounded-md bg-muted px-3.5 py-3 text-xs leading-[1.6] text-muted-foreground">
          Trường vẫn hiển thị trong danh sách khi lọc <b>"Ngừng dùng"</b>. Không có dữ liệu nào bị xoá.
        </div>
      </div>
      <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
        <Btn variant="outline" size="sm">Hủy</Btn>
        <Btn size="sm" icon="pause-circle"
          style={{ background:'oklch(0.52 0.14 65)', color:'white', borderColor:'transparent' }}>
          Xác nhận ngừng dùng
        </Btn>
      </div>
    </>
  );
};

// ─── Reactivate confirm ───────────────────────────────────────────────────────
const CFReactivateDialog = () => {
  const f = CF_DATA[5];
  return (
    <>
      <div className="flex shrink-0 items-center gap-3 border-b border-border px-[22px] py-[18px]">
        <div className="grid size-10 shrink-0 place-items-center rounded-md bg-success-soft">
          <Icon name="rotate-ccw" size={20} style={{ color:'var(--color-success)' }} />
        </div>
        <div>
          <div className="text-md font-bold">Kích hoạt lại trường?</div>
          <div className="mt-0.5 text-xs text-muted-foreground">
            "{f.label}" ·{' '}<code className="font-mono">{f.name}</code>
          </div>
        </div>
      </div>
      <div className="px-[22px] py-5">
        <div className="mb-4 rounded-md p-3.5 text-sm leading-[1.65]"
          style={{ background:'var(--color-success-soft)', border:'1px solid oklch(0.711 0.180 148 / 0.3)', color:'oklch(0.38 0.1 148)' }}>
          <div className="flex items-start gap-2.5">
            <Icon name="check-circle" size={15} className="mt-[2px] shrink-0" style={{ color:'var(--color-success)' }} />
            <div>
              Trường sẽ được <b>hiển thị trở lại</b> trong hồ sơ nhân viên.
              Dữ liệu đã nhập trước đây <b>vẫn còn nguyên</b> và sẽ hiển thị ngay.
            </div>
          </div>
        </div>
        <div className="rounded-md bg-muted px-3.5 py-3 text-xs leading-[1.6] text-muted-foreground">
          Sau khi kích hoạt, trường <code className="font-mono">{f.name}</code> sẽ xuất hiện khi tạo hồ sơ mới và
          có thể chỉnh sửa trên các hồ sơ hiện có.
        </div>
      </div>
      <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
        <Btn variant="outline" size="sm">Hủy</Btn>
        <Btn variant="primary" size="sm" icon="rotate-ccw">Kích hoạt lại</Btn>
      </div>
    </>
  );
};

// ════════════════════════════════════════════════════════════════════════════
// SCREENS — màn "Cấu hình" · tab "Trường tùy chỉnh"
// ════════════════════════════════════════════════════════════════════════════

// 01 Danh sách (có dữ liệu)
const CustomFieldsListScreen = () => (
  <AdminShell tab="custom-fields">
    <CFToolbar />
    <CFTableBody fields={CF_DATA} />
    <CFPager total={CF_DATA.length} />
  </AdminShell>
);

// 02 Trạng thái rỗng
const CustomFieldsEmptyScreen = () => (
  <AdminShell tab="custom-fields">
    <CFToolbar />
    <div className="flex flex-1 flex-col items-center justify-center gap-4 py-24">
      <div className="grid size-16 place-items-center rounded-full bg-muted">
        <Icon name="filter" size={28} className="text-muted-foreground" />
      </div>
      <div className="text-center">
        <div className="text-md font-semibold">Chưa có trường tùy chỉnh nào</div>
        <div className="mt-1 text-sm text-muted-foreground">
          Thêm trường để mở rộng hồ sơ nhân viên theo nhu cầu tổ chức.
        </div>
      </div>
      <Btn variant="primary" size="sm" icon="plus">Thêm trường đầu tiên</Btn>
    </div>
  </AdminShell>
);

// 03 Đang tải (skeleton)
const SkeletonPulse = ({ w = 'w-24', h = 'h-4' }) => (
  <div className={`${h} ${w} animate-pulse rounded-sm bg-muted`} />
);
const CustomFieldsLoadingScreen = () => (
  <AdminShell tab="custom-fields">
    <CFToolbar />
    <div className="overflow-auto flex-1">
      <table className={CF_TABLE}>
        <thead>
          <tr>
            <th>Nhãn</th><th>Tên trường</th><th>Kiểu</th>
            <th>Bắt buộc</th><th>Hiện NV (ESS)</th>
            <th>Thứ tự ↑</th><th>Trạng thái</th><th>Hành động</th>
          </tr>
        </thead>
        <tbody>
          {[140,180,160,200,130,170,150,190].map((w,i) => (
            <tr key={i}>
              <td><SkeletonPulse w={`w-[${w-20}px]`} /></td>
              <td><SkeletonPulse w={`w-[${w}px]`} /></td>
              <td><SkeletonPulse w="w-28" h="h-5" /></td>
              <td><SkeletonPulse w="w-16" /></td>
              <td><SkeletonPulse w="w-8" h="h-[18px]" /></td>
              <td><SkeletonPulse w="w-5" /></td>
              <td><SkeletonPulse w="w-20" h="h-5" /></td>
              <td><SkeletonPulse w="w-28" /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
    <CFPager total={0} />
  </AdminShell>
);

// 04 Lỗi
const CustomFieldsErrorScreen = () => (
  <AdminShell tab="custom-fields">
    <CFToolbar />
    <div className="flex flex-1 flex-col items-center justify-center gap-4 py-24">
      <div className="grid size-16 place-items-center rounded-full bg-destructive-soft">
        <Icon name="alert-triangle" size={28} className="text-destructive" />
      </div>
      <div className="text-center">
        <div className="text-md font-semibold">Không thể tải danh sách trường</div>
        <div className="mt-1 text-sm text-muted-foreground">
          Lỗi kết nối tới máy chủ. Vui lòng thử lại.
        </div>
        <div className="mt-0.5 font-mono text-xs text-muted-foreground">
          GET /api/v1/admin/custom-fields · 503 Service Unavailable
        </div>
      </div>
      <div className="flex gap-2">
        <Btn variant="outline" size="sm" icon="rotate-ccw">Thử lại</Btn>
        <Btn variant="ghost" size="sm">Báo lỗi kỹ thuật</Btn>
      </div>
    </div>
  </AdminShell>
);

// 05 Dialog thêm — kiểu Văn bản (mặc định)
const CustomFieldsAddScreen = () => (
  <div className="relative size-full">
    <CustomFieldsListScreen />
    <CFOverlay width={600}><CFFormDialog mode="add" /></CFOverlay>
  </div>
);

// 06 Dialog thêm — kiểu Danh sách chọn (hiện khu Tùy chọn)
const CustomFieldsAddDropdownScreen = () => (
  <div className="relative size-full">
    <CustomFieldsListScreen />
    <CFOverlay width={620}><CFFormDialog mode="add" showDropdownOpts={true} /></CFOverlay>
  </div>
);

// 07 Dialog thêm — lỗi trùng tên
const CustomFieldsDuplicateNameScreen = () => (
  <div className="relative size-full">
    <CustomFieldsListScreen />
    <CFOverlay width={620}><CFFormDialog mode="add" showDropdownOpts={true} duplicateError={true} /></CFOverlay>
  </div>
);

// 08 Dialog sửa — tên & kiểu chỉ đọc
const CustomFieldsEditScreen = () => (
  <div className="relative size-full">
    <CustomFieldsListScreen />
    <CFOverlay width={620}><CFFormDialog mode="edit" /></CFOverlay>
  </div>
);

// 09 Xác nhận ngừng dùng
const CustomFieldsDeactivateScreen = () => (
  <div className="relative size-full">
    <CustomFieldsListScreen />
    <CFOverlay width={480}><CFDeactivateDialog /></CFOverlay>
  </div>
);

// 10 Xác nhận kích hoạt lại
const CustomFieldsReactivateScreen = () => (
  <div className="relative size-full">
    <CustomFieldsListScreen />
    <CFOverlay width={480}><CFReactivateDialog /></CFOverlay>
  </div>
);

// ════════════════════════════════════════════════════════════════════════════
// DANH MỤC THAM CHIẾU — Chức danh · Địa điểm · Bậc lương
// API: /api/v1/admin/{job-titles|locations|pay-grades} · CRUD đầy đủ
//   · List: search + lọc active + phân trang     · Tạo (POST)   · Sửa (PATCH, gồm bật/tắt is_active)
//   · Xoá (DELETE, soft) — chặn 409 *_IN_USE nếu còn nhân viên đang dùng → gợi ý "ngừng dùng" thay vì xoá
// ════════════════════════════════════════════════════════════════════════════

const fmtVnd = (n) => n.toLocaleString('vi-VN');

// ─── Sample data ──────────────────────────────────────────────────────────────
const JT_DATA = [
  { id:'jt01', title:'Giám đốc điều hành',     desc:'Điều hành toàn bộ hoạt động công ty',        active:true,  refs:1  },
  { id:'jt02', title:'Trưởng phòng Nhân sự',   desc:'Quản lý hoạt động phòng Nhân sự',            active:true,  refs:1  },
  { id:'jt03', title:'Trưởng nhóm Kỹ thuật',   desc:'Dẫn dắt nhóm phát triển sản phẩm',           active:true,  refs:3  },
  { id:'jt04', title:'Chuyên viên Tuyển dụng', desc:'Phụ trách tuyển dụng và phỏng vấn',          active:true,  refs:2  },
  { id:'jt05', title:'Kế toán viên',            desc:'Xử lý nghiệp vụ kế toán và công nợ',         active:true,  refs:4  },
  { id:'jt06', title:'Nhân viên Kinh doanh',   desc:'Phát triển khách hàng và doanh số',          active:true,  refs:18 },
  { id:'jt07', title:'Thực tập sinh',           desc:'Vị trí thực tập có thời hạn',                active:false, refs:0  },
];

const LOC_DATA = [
  { id:'lo01', name:'Trụ sở Hà Nội',              address:'Tầng 12, Keangnam Landmark, Phạm Hùng', city:'Hà Nội',           country:'Việt Nam',  active:true,  refs:96 },
  { id:'lo02', name:'Văn phòng TP. Hồ Chí Minh',  address:'Tầng 8, Bitexco Financial Tower, Q.1',  city:'TP. Hồ Chí Minh',  country:'Việt Nam',  active:true,  refs:74 },
  { id:'lo03', name:'Chi nhánh Đà Nẵng',          address:'36 Bạch Đằng, Hải Châu',                city:'Đà Nẵng',          country:'Việt Nam',  active:true,  refs:21 },
  { id:'lo04', name:'Kho vận Bình Dương',         address:'KCN VSIP II, Thủ Dầu Một',              city:'Bình Dương',       country:'Việt Nam',  active:true,  refs:12 },
  { id:'lo05', name:'Văn phòng Singapore',        address:'1 Raffles Place, #20-01',               city:'Singapore',        country:'Singapore', active:true,  refs:6  },
  { id:'lo06', name:'VP đại diện Tokyo',          address:'Shibuya, Tokyo',                        city:'Tokyo',            country:'Nhật Bản',  active:false, refs:0  },
];

const PG_DATA = [
  { id:'pg01', name:'Bậc 1 — Nhân viên',          min:8000000,  max:12000000,  cur:'VND', active:true,  refs:42 },
  { id:'pg02', name:'Bậc 2 — Chuyên viên',        min:12000000, max:20000000,  cur:'VND', active:true,  refs:58 },
  { id:'pg03', name:'Bậc 3 — Chuyên viên chính',  min:18000000, max:30000000,  cur:'VND', active:true,  refs:27 },
  { id:'pg04', name:'Bậc 4 — Trưởng nhóm',        min:28000000, max:45000000,  cur:'VND', active:true,  refs:9  },
  { id:'pg05', name:'Bậc 5 — Trưởng phòng',       min:40000000, max:70000000,  cur:'VND', active:true,  refs:4  },
  { id:'pg06', name:'Bậc 6 — Ban giám đốc',       min:70000000, max:120000000, cur:'VND', active:false, refs:0  },
];

// ─── Shared atoms cho danh mục ────────────────────────────────────────────────
const StatusBadge = ({ active }) => (
  <Badge variant={active ? 'success' : 'neutral'} dot>{active ? 'Đang dùng' : 'Ngừng dùng'}</Badge>
);

// Hàng hành động: Sửa · Ngừng dùng/Kích hoạt lại · Xoá (chỉ mockup tĩnh)
const RowActions = ({ active }) => (
  <div className="flex items-center gap-0.5">
    <Btn variant="ghost" size="xs" icon="edit">Sửa</Btn>
    {active
      ? <Btn variant="ghost" size="xs" icon="pause-circle" style={{ color:'var(--color-muted-foreground)' }}>Ngừng dùng</Btn>
      : <Btn variant="ghost" size="xs" icon="rotate-ccw" style={{ color:'var(--color-success)' }}>Kích hoạt lại</Btn>}
    <Btn variant="ghost" size="xs" icon="trash" style={{ color:'var(--color-destructive)' }}>Xoá</Btn>
  </div>
);

// Toolbar dùng chung: tìm kiếm + lọc trạng thái + nút thêm
const CatalogToolbar = ({ placeholder, addLabel }) => (
  <div className="flex shrink-0 items-center gap-2.5 border-b border-border bg-card px-5 py-3">
    <div className="relative" style={{ flex:'0 0 280px' }}>
      <Icon name="search" size={13} className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
      <input
        className="h-8 w-full rounded-md border border-input bg-transparent pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
        placeholder={placeholder} />
    </div>
    <Select
      options={[{value:'all',label:'Tất cả trạng thái'},{value:'active',label:'Đang dùng'},{value:'inactive',label:'Ngừng dùng'}]}
      defaultValue="all"
      className="h-8 text-xs" />
    <div className="flex-1" />
    <Btn variant="primary" size="sm" icon="plus">{addLabel}</Btn>
  </div>
);

const CatalogPager = ({ total, unit }) => (
  <div className="flex shrink-0 items-center justify-between border-t border-border px-5 py-2.5 text-xs text-muted-foreground">
    <span>Hiển thị <b className="text-foreground">{total}</b> / <b className="text-foreground">{total}</b> {unit}</span>
    <div className="flex items-center gap-1">
      <Btn variant="outline" size="xs" iconOnly icon="chevron-left" disabled />
      <Btn variant="primary" size="xs">1</Btn>
      <Btn variant="outline" size="xs" iconOnly icon="chevron-right" disabled />
    </div>
  </div>
);

// Khung header/footer dùng chung cho dialog Thêm/Sửa
const CatalogFormShell = ({ mode, icon, entityLabel, subtitle, width = 540, children }) => {
  const isEdit = mode === 'edit';
  return (
    <CFOverlay width={width}>
      <div className="flex shrink-0 items-center justify-between border-b border-border px-[22px] py-4">
        <div className="flex items-center gap-[11px]">
          <div className="grid size-9 shrink-0 place-items-center rounded-md bg-primary-soft">
            <Icon name={isEdit ? 'edit' : icon} size={17} style={{ color:'var(--color-primary)' }} />
          </div>
          <div>
            <div className="text-md font-bold">{isEdit ? `Sửa ${entityLabel}` : `Thêm ${entityLabel}`}</div>
            <div className="mt-px text-xs text-muted-foreground">{subtitle}</div>
          </div>
        </div>
        <Btn variant="ghost" size="sm" iconOnly icon="x" />
      </div>
      <div className="overflow-y-auto px-[22px] py-5" style={{ maxHeight:520 }}>
        {children}
      </div>
      <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
        <Btn variant="outline" size="sm">Hủy</Btn>
        <Btn variant="primary" size="sm" icon={isEdit ? 'check' : 'plus'}>
          {isEdit ? 'Lưu thay đổi' : `Tạo ${entityLabel}`}
        </Btn>
      </div>
    </CFOverlay>
  );
};

// ─── Confirm dialogs dùng chung (tham số theo entity) ─────────────────────────
const DeactivateDialog = ({ entityLabel, name }) => (
  <CFOverlay width={480}>
    <div className="flex shrink-0 items-center gap-3 border-b border-border px-[22px] py-[18px]">
      <div className="grid size-10 shrink-0 place-items-center rounded-md bg-warning-soft">
        <Icon name="pause-circle" size={20} style={{ color:'oklch(0.52 0.14 65)' }} />
      </div>
      <div>
        <div className="text-md font-bold">Ngừng dùng {entityLabel}?</div>
        <div className="mt-0.5 text-xs text-muted-foreground">"{name}"</div>
      </div>
    </div>
    <div className="px-[22px] py-5">
      <div className="mb-4 rounded-md p-3.5 text-sm leading-[1.65]"
        style={{ background:'var(--color-warning-soft)', border:'1px solid oklch(0.835 0.158 80 / 0.3)', color:'oklch(0.38 0.08 65)' }}>
        <div className="flex items-start gap-2.5">
          <Icon name="alert-triangle" size={15} className="mt-[2px] shrink-0" style={{ color:'oklch(0.52 0.14 65)' }} />
          <div>
            {entityLabel} sẽ <b>ẩn khỏi các lựa chọn</b> khi tạo / sửa hồ sơ nhân viên, nhưng{' '}
            <b>nhân viên đang được gán vẫn giữ nguyên</b>. Có thể kích hoạt lại bất kỳ lúc nào.
          </div>
        </div>
      </div>
      <div className="rounded-md bg-muted px-3.5 py-3 text-xs leading-[1.6] text-muted-foreground">
        Mục vẫn hiển thị khi lọc <b>"Ngừng dùng"</b>. Không có dữ liệu liên kết nào bị xoá.
      </div>
    </div>
    <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
      <Btn variant="outline" size="sm">Hủy</Btn>
      <Btn size="sm" icon="pause-circle"
        style={{ background:'oklch(0.52 0.14 65)', color:'white', borderColor:'transparent' }}>
        Xác nhận ngừng dùng
      </Btn>
    </div>
  </CFOverlay>
);

const ReactivateDialog = ({ entityLabel, name }) => (
  <CFOverlay width={480}>
    <div className="flex shrink-0 items-center gap-3 border-b border-border px-[22px] py-[18px]">
      <div className="grid size-10 shrink-0 place-items-center rounded-md bg-success-soft">
        <Icon name="rotate-ccw" size={20} style={{ color:'var(--color-success)' }} />
      </div>
      <div>
        <div className="text-md font-bold">Kích hoạt lại {entityLabel}?</div>
        <div className="mt-0.5 text-xs text-muted-foreground">"{name}"</div>
      </div>
    </div>
    <div className="px-[22px] py-5">
      <div className="mb-4 rounded-md p-3.5 text-sm leading-[1.65]"
        style={{ background:'var(--color-success-soft)', border:'1px solid oklch(0.711 0.180 148 / 0.3)', color:'oklch(0.38 0.1 148)' }}>
        <div className="flex items-start gap-2.5">
          <Icon name="check-circle" size={15} className="mt-[2px] shrink-0" style={{ color:'var(--color-success)' }} />
          <div>
            {entityLabel} sẽ <b>xuất hiện trở lại</b> trong các lựa chọn khi tạo / sửa hồ sơ nhân viên.
            Các liên kết cũ <b>vẫn còn nguyên</b>.
          </div>
        </div>
      </div>
    </div>
    <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
      <Btn variant="outline" size="sm">Hủy</Btn>
      <Btn variant="primary" size="sm" icon="rotate-ccw">Kích hoạt lại</Btn>
    </div>
  </CFOverlay>
);

const DeleteDialog = ({ entityLabel, name }) => (
  <CFOverlay width={480}>
    <div className="flex shrink-0 items-center gap-3 border-b border-border px-[22px] py-[18px]">
      <div className="grid size-10 shrink-0 place-items-center rounded-md bg-destructive-soft">
        <Icon name="trash" size={19} style={{ color:'var(--color-destructive)' }} />
      </div>
      <div>
        <div className="text-md font-bold">Xoá {entityLabel}?</div>
        <div className="mt-0.5 text-xs text-muted-foreground">"{name}"</div>
      </div>
    </div>
    <div className="px-[22px] py-5">
      <div className="mb-4 rounded-md p-3.5 text-sm leading-[1.65]"
        style={{ background:'var(--color-destructive-soft)', border:'1px solid oklch(0.601 0.215 12 / 0.25)', color:'oklch(0.4 0.12 12)' }}>
        <div className="flex items-start gap-2.5">
          <Icon name="alert-triangle" size={15} className="mt-[2px] shrink-0 text-destructive" />
          <div>
            Thao tác này <b>gỡ {entityLabel} khỏi danh mục</b>. Chỉ thực hiện được khi{' '}
            <b>không còn nhân viên nào đang dùng</b>.
          </div>
        </div>
      </div>
      <div className="rounded-md bg-muted px-3.5 py-3 text-xs leading-[1.6] text-muted-foreground">
        Nếu chỉ muốn ngừng sử dụng, hãy chọn <b>Ngừng dùng</b> để giữ lại các liên kết với nhân viên.
      </div>
    </div>
    <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
      <Btn variant="outline" size="sm">Hủy</Btn>
      <Btn variant="destructive" size="sm" icon="trash">Xoá</Btn>
    </div>
  </CFOverlay>
);

const DeleteBlockedDialog = ({ entityLabel, name, refCount, endpoint, code }) => (
  <CFOverlay width={500}>
    <div className="flex shrink-0 items-center gap-3 border-b border-border px-[22px] py-[18px]">
      <div className="grid size-10 shrink-0 place-items-center rounded-md bg-destructive-soft">
        <Icon name="alert-triangle" size={20} className="text-destructive" />
      </div>
      <div>
        <div className="text-md font-bold">Không thể xoá {entityLabel}</div>
        <div className="mt-0.5 text-xs text-muted-foreground">"{name}"</div>
      </div>
    </div>
    <div className="px-[22px] py-5">
      <div className="mb-4 rounded-md p-3.5 text-sm leading-[1.65]"
        style={{ background:'var(--color-destructive-soft)', border:'1px solid oklch(0.601 0.215 12 / 0.25)', color:'oklch(0.4 0.12 12)' }}>
        <div className="flex items-start gap-2.5">
          <Icon name="users" size={15} className="mt-[2px] shrink-0 text-destructive" />
          <div>
            Còn <b>{refCount} nhân viên</b> đang dùng {entityLabel} này. Hệ thống đã{' '}
            <b>chặn xoá</b> để tránh mất dữ liệu liên kết.
          </div>
        </div>
      </div>
      <div className="mb-3 rounded-md bg-muted px-3.5 py-2.5 font-mono text-xs text-muted-foreground">
        DELETE {endpoint} · 409 {code}
      </div>
      <div className="rounded-md bg-muted px-3.5 py-3 text-xs leading-[1.6] text-muted-foreground">
        Hãy đặt <b>Ngừng dùng</b> để ẩn {entityLabel} khỏi lựa chọn mới mà vẫn giữ liên kết hiện có.
      </div>
    </div>
    <div className="flex shrink-0 justify-end gap-2 border-t border-border px-[22px] py-3.5">
      <Btn variant="outline" size="sm">Đóng</Btn>
      <Btn size="sm" icon="pause-circle"
        style={{ background:'oklch(0.52 0.14 65)', color:'white', borderColor:'transparent' }}>
        Ngừng dùng thay vì xoá
      </Btn>
    </div>
  </CFOverlay>
);

// ════════════════════════════════════════════════════════════════════════════
// CHỨC DANH (job-titles)
// ════════════════════════════════════════════════════════════════════════════
const JobTitlesTable = () => (
  <div className="overflow-auto flex-1">
    <table className={CF_TABLE}>
      <thead>
        <tr>
          <th style={{ minWidth:220 }}>Chức danh</th>
          <th>Mô tả</th>
          <th style={{ minWidth:130 }}>Trạng thái</th>
          <th style={{ minWidth:200 }}>Hành động</th>
        </tr>
      </thead>
      <tbody>
        {JT_DATA.map(r => (
          <tr key={r.id}>
            <td><span className="text-sm font-semibold">{r.title}</span></td>
            <td><span className="line-clamp-1 text-muted-foreground">{r.desc}</span></td>
            <td><StatusBadge active={r.active} /></td>
            <td><RowActions active={r.active} /></td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const JobTitlesListScreen = () => (
  <AdminShell tab="job-titles">
    <CatalogToolbar placeholder="Tìm theo tên chức danh…" addLabel="Thêm chức danh" />
    <JobTitlesTable />
    <CatalogPager total={JT_DATA.length} unit="chức danh" />
  </AdminShell>
);

const JobTitleForm = ({ mode }) => {
  const isEdit = mode === 'edit';
  const r = JT_DATA[1];
  return (
    <CatalogFormShell mode={mode} icon="briefcase" entityLabel="chức danh"
      subtitle={isEdit ? 'Cập nhật tên, mô tả hoặc trạng thái sử dụng' : 'Chức danh dùng để gán cho nhân viên trong hồ sơ'}>
      <div className="mb-3.5">
        <CFFieldLbl label="Tên chức danh" req />
        <input className={CF_INP} defaultValue={isEdit ? r.title : ''}
          placeholder="VD: Trưởng phòng Kinh doanh" />
      </div>
      <div className="mb-3.5">
        <CFFieldLbl label="Mô tả" />
        <textarea
          className="w-full resize-none rounded-md border border-input bg-transparent px-3 py-2.5 text-base text-foreground shadow-xs placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
          rows={3}
          defaultValue={isEdit ? r.desc : ''}
          placeholder="Mô tả ngắn về phạm vi công việc của chức danh (tuỳ chọn)…" />
      </div>
      <SwitchRow label="Đang sử dụng"
        desc="Cho phép gán chức danh này khi tạo / sửa hồ sơ nhân viên"
        on={isEdit ? r.active : true} />
    </CatalogFormShell>
  );
};

const JobTitlesAddScreen = () => (
  <div className="relative size-full"><JobTitlesListScreen /><JobTitleForm mode="add" /></div>
);
const JobTitlesEditScreen = () => (
  <div className="relative size-full"><JobTitlesListScreen /><JobTitleForm mode="edit" /></div>
);
const JobTitlesDeactivateScreen = () => (
  <div className="relative size-full"><JobTitlesListScreen />
    <DeactivateDialog entityLabel="chức danh" name="Nhân viên Kinh doanh" /></div>
);
const JobTitlesReactivateScreen = () => (
  <div className="relative size-full"><JobTitlesListScreen />
    <ReactivateDialog entityLabel="chức danh" name="Thực tập sinh" /></div>
);
const JobTitlesDeleteScreen = () => (
  <div className="relative size-full"><JobTitlesListScreen />
    <DeleteDialog entityLabel="chức danh" name="Thực tập sinh" /></div>
);
const JobTitlesDeleteBlockedScreen = () => (
  <div className="relative size-full"><JobTitlesListScreen />
    <DeleteBlockedDialog entityLabel="chức danh" name="Nhân viên Kinh doanh" refCount={18}
      endpoint="/api/v1/admin/job-titles/:id" code="JOB_TITLE_IN_USE" /></div>
);

// ════════════════════════════════════════════════════════════════════════════
// ĐỊA ĐIỂM (locations)
// ════════════════════════════════════════════════════════════════════════════
const LocationsTable = () => (
  <div className="overflow-auto flex-1">
    <table className={CF_TABLE}>
      <thead>
        <tr>
          <th style={{ minWidth:210 }}>Tên địa điểm</th>
          <th style={{ minWidth:150 }}>Thành phố</th>
          <th style={{ minWidth:120 }}>Quốc gia</th>
          <th>Địa chỉ</th>
          <th style={{ minWidth:130 }}>Trạng thái</th>
          <th style={{ minWidth:200 }}>Hành động</th>
        </tr>
      </thead>
      <tbody>
        {LOC_DATA.map(r => (
          <tr key={r.id}>
            <td>
              <span className="flex items-center gap-2 text-sm font-semibold">
                <Icon name="map-pin" size={14} className="shrink-0 text-muted-foreground" />
                {r.name}
              </span>
            </td>
            <td><span className="text-sm">{r.city}</span></td>
            <td>
              <span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
                <Icon name="globe" size={13} className="shrink-0" />{r.country}
              </span>
            </td>
            <td><span className="line-clamp-1 text-muted-foreground">{r.address}</span></td>
            <td><StatusBadge active={r.active} /></td>
            <td><RowActions active={r.active} /></td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const LocationsListScreen = () => (
  <AdminShell tab="locations">
    <CatalogToolbar placeholder="Tìm theo tên, thành phố…" addLabel="Thêm địa điểm" />
    <LocationsTable />
    <CatalogPager total={LOC_DATA.length} unit="địa điểm" />
  </AdminShell>
);

const LocationForm = ({ mode }) => {
  const isEdit = mode === 'edit';
  const r = LOC_DATA[1];
  return (
    <CatalogFormShell mode={mode} icon="map-pin" entityLabel="địa điểm" width={560}
      subtitle={isEdit ? 'Cập nhật thông tin địa điểm / văn phòng' : 'Địa điểm làm việc dùng để gán cho nhân viên'}>
      <div className="mb-3.5">
        <CFFieldLbl label="Tên địa điểm" req />
        <input className={CF_INP} defaultValue={isEdit ? r.name : ''}
          placeholder="VD: Văn phòng TP. Hồ Chí Minh" />
      </div>
      <div className="mb-3.5">
        <CFFieldLbl label="Địa chỉ" />
        <textarea
          className="w-full resize-none rounded-md border border-input bg-transparent px-3 py-2.5 text-base text-foreground shadow-xs placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-[3px] focus:ring-ring"
          rows={2}
          defaultValue={isEdit ? r.address : ''}
          placeholder="Số nhà, đường, toà nhà, quận / huyện…" />
      </div>
      <div className="grid grid-cols-2 gap-3.5">
        <div>
          <CFFieldLbl label="Thành phố" />
          <input className={CF_INP} defaultValue={isEdit ? r.city : ''} placeholder="VD: Hà Nội" />
        </div>
        <div>
          <CFFieldLbl label="Quốc gia" />
          <input className={CF_INP} defaultValue={isEdit ? r.country : 'Việt Nam'} placeholder="VD: Việt Nam" />
        </div>
      </div>
      <div className="mt-3.5">
        <SwitchRow label="Đang sử dụng"
          desc="Cho phép gán địa điểm này khi tạo / sửa hồ sơ nhân viên"
          on={isEdit ? r.active : true} />
      </div>
    </CatalogFormShell>
  );
};

const LocationsAddScreen = () => (
  <div className="relative size-full"><LocationsListScreen /><LocationForm mode="add" /></div>
);
const LocationsEditScreen = () => (
  <div className="relative size-full"><LocationsListScreen /><LocationForm mode="edit" /></div>
);
const LocationsDeactivateScreen = () => (
  <div className="relative size-full"><LocationsListScreen />
    <DeactivateDialog entityLabel="địa điểm" name="VP đại diện Tokyo" /></div>
);
const LocationsDeleteScreen = () => (
  <div className="relative size-full"><LocationsListScreen />
    <DeleteDialog entityLabel="địa điểm" name="VP đại diện Tokyo" /></div>
);
const LocationsDeleteBlockedScreen = () => (
  <div className="relative size-full"><LocationsListScreen />
    <DeleteBlockedDialog entityLabel="địa điểm" name="Trụ sở Hà Nội" refCount={96}
      endpoint="/api/v1/admin/locations/:id" code="LOCATION_IN_USE" /></div>
);

// ════════════════════════════════════════════════════════════════════════════
// BẬC LƯƠNG (pay-grades)
// ════════════════════════════════════════════════════════════════════════════
const PayGradesTable = () => (
  <div className="overflow-auto flex-1">
    <table className={CF_TABLE}>
      <thead>
        <tr>
          <th style={{ minWidth:220 }}>Bậc lương</th>
          <th style={{ minWidth:220 }}>Khoảng lương / tháng</th>
          <th style={{ minWidth:100 }}>Tiền tệ</th>
          <th style={{ minWidth:130 }}>Trạng thái</th>
          <th style={{ minWidth:200 }}>Hành động</th>
        </tr>
      </thead>
      <tbody>
        {PG_DATA.map(r => (
          <tr key={r.id}>
            <td><span className="text-sm font-semibold">{r.name}</span></td>
            <td>
              <span className="font-mono text-sm tabular-nums text-foreground">
                {fmtVnd(r.min)} <span className="text-muted-foreground">–</span> {fmtVnd(r.max)}
              </span>
            </td>
            <td><Badge variant="neutral">{r.cur}</Badge></td>
            <td><StatusBadge active={r.active} /></td>
            <td><RowActions active={r.active} /></td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const PayGradesListScreen = () => (
  <AdminShell tab="pay-grades">
    <CatalogToolbar placeholder="Tìm theo tên bậc lương…" addLabel="Thêm bậc lương" />
    <PayGradesTable />
    <CatalogPager total={PG_DATA.length} unit="bậc lương" />
  </AdminShell>
);

const PayGradeForm = ({ mode }) => {
  const isEdit = mode === 'edit';
  const r = PG_DATA[1];
  return (
    <CatalogFormShell mode={mode} icon="dollar" entityLabel="bậc lương" width={560}
      subtitle={isEdit ? 'Cập nhật tên, khoảng lương hoặc trạng thái' : 'Bậc lương xác định khoảng lương cho nhóm vị trí'}>
      <div className="mb-3.5">
        <CFFieldLbl label="Tên bậc lương" req />
        <input className={CF_INP} defaultValue={isEdit ? r.name : ''}
          placeholder="VD: Bậc 3 — Chuyên viên chính" />
      </div>
      <div className="grid grid-cols-2 gap-3.5">
        <div>
          <CFFieldLbl label="Lương tối thiểu" req />
          <div className="relative">
            <input className={CF_INP + " pr-12 text-right font-mono tabular-nums"} type="number" min={0}
              defaultValue={isEdit ? r.min : ''} placeholder="0" />
            <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">/ tháng</span>
          </div>
        </div>
        <div>
          <CFFieldLbl label="Lương tối đa" req />
          <div className="relative">
            <input className={CF_INP + " pr-12 text-right font-mono tabular-nums"} type="number" min={0}
              defaultValue={isEdit ? r.max : ''} placeholder="0" />
            <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">/ tháng</span>
          </div>
        </div>
      </div>
      <div className="mt-1 mb-3.5 text-xs text-muted-foreground">
        Lương tối đa phải lớn hơn hoặc bằng lương tối thiểu.
      </div>
      <div className="mb-3.5" style={{ width:200 }}>
        <CFFieldLbl label="Tiền tệ" req />
        <Select
          options={[{value:'VND',label:'VND — Việt Nam Đồng'},{value:'USD',label:'USD — Đô la Mỹ'}]}
          defaultValue={isEdit ? r.cur : 'VND'}
          className="w-full" />
      </div>
      <SwitchRow label="Đang sử dụng"
        desc="Cho phép gán bậc lương này khi tạo / sửa hồ sơ nhân viên"
        on={isEdit ? r.active : true} />
    </CatalogFormShell>
  );
};

const PayGradesAddScreen = () => (
  <div className="relative size-full"><PayGradesListScreen /><PayGradeForm mode="add" /></div>
);
const PayGradesEditScreen = () => (
  <div className="relative size-full"><PayGradesListScreen /><PayGradeForm mode="edit" /></div>
);
const PayGradesDeactivateScreen = () => (
  <div className="relative size-full"><PayGradesListScreen />
    <DeactivateDialog entityLabel="bậc lương" name="Bậc 6 — Ban giám đốc" /></div>
);
const PayGradesDeleteScreen = () => (
  <div className="relative size-full"><PayGradesListScreen />
    <DeleteDialog entityLabel="bậc lương" name="Bậc 6 — Ban giám đốc" /></div>
);
const PayGradesDeleteBlockedScreen = () => (
  <div className="relative size-full"><PayGradesListScreen />
    <DeleteBlockedDialog entityLabel="bậc lương" name="Bậc 2 — Chuyên viên" refCount={58}
      endpoint="/api/v1/admin/pay-grades/:id" code="PAY_GRADE_IN_USE" /></div>
);

Object.assign(window, {
  CustomFieldsListScreen, CustomFieldsEmptyScreen, CustomFieldsLoadingScreen, CustomFieldsErrorScreen,
  CustomFieldsAddScreen, CustomFieldsAddDropdownScreen, CustomFieldsDuplicateNameScreen,
  CustomFieldsEditScreen, CustomFieldsDeactivateScreen, CustomFieldsReactivateScreen,
  // Chức danh
  JobTitlesListScreen, JobTitlesAddScreen, JobTitlesEditScreen,
  JobTitlesDeactivateScreen, JobTitlesReactivateScreen, JobTitlesDeleteScreen, JobTitlesDeleteBlockedScreen,
  // Địa điểm
  LocationsListScreen, LocationsAddScreen, LocationsEditScreen,
  LocationsDeactivateScreen, LocationsDeleteScreen, LocationsDeleteBlockedScreen,
  // Bậc lương
  PayGradesListScreen, PayGradesAddScreen, PayGradesEditScreen,
  PayGradesDeactivateScreen, PayGradesDeleteScreen, PayGradesDeleteBlockedScreen,
  AdminShell, AdminTabBar,
});
