/* screens-config-params.jsx — /admin/config/thamso — monthly factors + sale type multipliers */

function ParamsScreen() {
  const CFG = WFP_CFG;
  const { vw, isMobile } = useViewport();
  const [section, setSection] = React.useState('monthly');
  const [editMonth, setEditMonth] = React.useState(null);
  const [editSale, setEditSale]   = React.useState(null);

  // KPI numbers
  const avgFactor = (CFG.MONTHLY_FACTORS.reduce((a, m) => a + m.factor, 0) / 12).toFixed(2);
  const peakMonth = CFG.MONTHLY_FACTORS.reduce((max, m) => m.factor > max.factor ? m : max, CFG.MONTHLY_FACTORS[0]);
  const lowMonth  = CFG.MONTHLY_FACTORS.reduce((min, m) => m.factor < min.factor ? m : min, CFG.MONTHLY_FACTORS[0]);
  const peakSale  = CFG.SALE_TYPES.reduce((max, s) => s.mult > max.mult ? s : max, CFG.SALE_TYPES[0]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <PageHeader
        breadcrumb={['Cấu hình','Tham số']}
        title="Tham số mùa vụ & sự kiện"
        subtitle="Hệ số nhân các tháng trong năm và các loại sale. Áp dụng vào công thức WLU để tính khối lượng công việc thực tế."
        actions={
          <>
            <Button variant="outline" icon="download">Xuất Excel</Button>
            <Button variant="outline" icon="history">Lịch sử</Button>
            <Button variant="primary" icon="plus" onClick={() => section === 'monthly' ? null : setEditSale({ isNew: true })}>
              {section === 'monthly' ? 'Tạo bản sao năm sau' : 'Loại sale mới'}
            </Button>
          </>
        }
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20 }}>
        {/* KPI strip */}
        <div style={{
          display: 'grid', gap: 12, marginBottom: 16,
          gridTemplateColumns: vw < 720 ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)',
        }}>
          <Metric icon="forecast" label="Hệ số TB năm" value={avgFactor} sublabel="vs. baseline 1.00"/>
          <Metric icon="arrowUp"  label="Đỉnh cao nhất" value={'×' + peakMonth.factor.toFixed(2)} sublabel={peakMonth.label}/>
          <Metric icon="arrowDown" label="Thấp nhất"     value={'×' + lowMonth.factor.toFixed(2)}  sublabel={lowMonth.label}/>
          <Metric icon="rocket"   label="Sale lớn nhất"  value={'×' + peakSale.mult.toFixed(2)}    sublabel={peakSale.name}/>
        </div>

        <div style={{ marginBottom: 14 }}>
          <SectionTabs value={section} onChange={setSection} tabs={[
            { id: 'monthly', label: 'Hệ số tháng',  idx: 1, count: 12 },
            { id: 'sale',    label: 'Loại sale',     idx: 2, count: CFG.SALE_TYPES.length },
            { id: 'formula', label: 'Cách áp dụng',  idx: 3 },
          ]}/>
        </div>

        {section === 'monthly' && (
          <>
            <MonthlyChartCard/>
            <div style={{ height: 16 }}/>
            <MonthlyTableCard onEdit={setEditMonth}/>
          </>
        )}
        {section === 'sale' && (
          <>
            <SaleTypesGridCard onEdit={setEditSale}/>
            <div style={{ height: 16 }}/>
            <SaleTypesUsageCard/>
          </>
        )}
        {section === 'formula' && <FormulaAppliedCard/>}
      </div>

      <MonthEditDialog open={!!editMonth} month={editMonth} onClose={() => setEditMonth(null)}/>
      <SaleEditDialog  open={!!editSale}  sale={editSale}   onClose={() => setEditSale(null)}/>
    </div>
  );
}

// ---------- Monthly chart card (bar chart with peak shading) ----------
function MonthlyChartCard() {
  const CFG = WFP_CFG;
  const months = CFG.MONTHLY_FACTORS;
  const max = Math.max(...months.map(m => m.factor));
  const min = Math.min(...months.map(m => m.factor));
  const range = max - 0; // y-axis from 0 to max
  const H = 200;
  const todayMonth = 5; // May 2026 → highlight

  return (
    <Card title="Đường cong mùa vụ" subtitle="Hệ số nhân của 12 tháng so với baseline 1.00 · cập nhật theo Q4 review">
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: H + 36, padding: '0 4px', position: 'relative' }}>
        {/* gridlines */}
        <div style={{ position: 'absolute', top: 0, left: 36, right: 4, bottom: 36 }}>
          {[0, 0.5, 1, 1.5, 2].filter(g => g <= max + 0.1).map(g => (
            <div key={g} style={{
              position: 'absolute', left: 0, right: 0, bottom: (g / max) * H,
              borderTop: g === 1 ? '1px dashed var(--bx-primary)' : '1px dashed var(--bx-border-muted)',
              opacity: g === 1 ? 0.6 : 0.5,
            }}>
              <span style={{
                position: 'absolute', left: -32, top: -7, fontSize: 10,
                color: g === 1 ? 'var(--bx-primary)' : 'var(--bx-text-muted)',
                fontFamily: 'var(--bx-font-mono)', fontWeight: g === 1 ? 600 : 400,
              }}>×{g.toFixed(1)}</span>
            </div>
          ))}
        </div>
        <div style={{ width: 36 }}/>
        {months.map((m, i) => {
          const h = (m.factor / max) * H;
          const isPeak = m.peak;
          const isCurrent = m.month === todayMonth;
          const tone = isPeak ? '#b91c1c' : m.factor < 0.8 ? '#92400e' : '#0b43ea';
          return (
            <div key={m.month} style={{
              flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center',
              gap: 4, position: 'relative',
            }}>
              <div style={{
                fontSize: 10.5, fontFamily: 'var(--bx-font-mono)',
                fontWeight: 700, color: tone,
              }}>×{m.factor.toFixed(2)}</div>
              <div style={{
                width: '100%', maxWidth: 48, height: h,
                background: 'linear-gradient(180deg, ' + tone + ' 0%, ' + tone + 'dd 100%)',
                borderRadius: '6px 6px 0 0',
                boxShadow: isCurrent ? '0 0 0 2px #fff, 0 0 0 4px var(--bx-primary)' : 'none',
                position: 'relative',
              }}>
                {isCurrent && (
                  <div style={{
                    position: 'absolute', top: -22, left: '50%', transform: 'translateX(-50%)',
                    fontSize: 9, color: '#fff', background: 'var(--bx-primary)',
                    padding: '2px 6px', borderRadius: 4, whiteSpace: 'nowrap', fontWeight: 600,
                  }}>Hiện tại</div>
                )}
              </div>
              <div style={{
                fontSize: 11, color: isCurrent ? 'var(--bx-primary)' : 'var(--bx-text-body)',
                fontWeight: isCurrent ? 700 : 500, fontFamily: 'var(--bx-font-mono)',
              }}>T{m.month}</div>
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginTop: 12, fontSize: 11.5, color: 'var(--bx-text-muted)' }}>
        <LegendDot color="#b91c1c" label="Tháng cao điểm"/>
        <LegendDot color="#0b43ea" label="Bình thường"/>
        <LegendDot color="#92400e" label="Tháng thấp · Tết Âm"/>
      </div>
    </Card>
  );
}

function LegendDot({ color, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      <span style={{ width: 10, height: 10, borderRadius: 3, background: color }}/>
      <span>{label}</span>
    </span>
  );
}

// ---------- Monthly table card ----------
function MonthlyTableCard({ onEdit }) {
  const CFG = WFP_CFG;
  return (
    <Card title="Hệ số 12 tháng" subtitle="Bấm vào dòng để chỉnh sửa. Hệ số = 1.00 nghĩa là đúng baseline trung bình năm." padding={0}>
      <Table
        columns={[
          { header: 'Tháng', width: 60, render: m => (
            <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 13 }}>T{m.month}</span>
          )},
          { header: 'Tên', render: m => (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontWeight: 600, color: 'var(--bx-text-dark)' }}>{m.label}</span>
              {m.peak && <Badge kind="CRITICAL" size="sm">Cao điểm</Badge>}
            </div>
          )},
          { header: 'Hệ số', align: 'right', width: 120, render: m => (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <FactorBar value={m.factor}/>
              <span style={{
                fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 14,
                color: m.factor > 1 ? 'var(--bx-error)' : m.factor < 0.85 ? 'var(--bx-warning-fg)' : 'var(--bx-primary)',
                minWidth: 50, textAlign: 'right',
              }}>×{m.factor.toFixed(2)}</span>
            </div>
          )},
          { header: 'Δ vs. baseline', align: 'right', mono: true, priority: 2,
            render: m => {
              const pct = ((m.factor - 1) * 100);
              return (
                <span style={{
                  color: pct > 0 ? 'var(--bx-error)' : pct < 0 ? 'var(--bx-error)' : 'var(--bx-text-muted)',
                  fontWeight: 600,
                }}>{pct > 0 ? '+' : ''}{pct.toFixed(0)}%</span>
              );
            }},
          { header: 'Ghi chú', wrap: true, priority: 2,
            render: m => <span style={{ fontSize: 12, color: 'var(--bx-text-body)' }}>{m.note}</span> },
          { header: '', width: 60, align: 'right', render: m => (
            <IconBtn name="edit" title="Chỉnh sửa" onClick={() => onEdit(m)}/>
          )},
        ]}
        rows={CFG.MONTHLY_FACTORS} getRowKey={m => m.month}
        onRowClick={onEdit}
      />
    </Card>
  );
}

function FactorBar({ value }) {
  // bar showing deviation from 1.0
  const maxDelta = 0.8; // ±80% range
  const pct = Math.min(Math.abs(value - 1) / maxDelta, 1);
  const w = 80;
  const half = w / 2;
  const barW = pct * half;
  const isUp = value >= 1;
  const tone = value > 1.2 ? '#b91c1c' : value < 0.85 ? '#92400e' : '#0b43ea';
  return (
    <div style={{ position: 'relative', width: w, height: 8, background: 'var(--bx-surface-2)', borderRadius: 4 }}>
      <div style={{ position: 'absolute', left: half - 0.5, top: -2, bottom: -2, width: 1, background: 'var(--bx-border)' }}/>
      <div style={{
        position: 'absolute', top: 0, height: '100%',
        background: tone, opacity: 0.85,
        left:  isUp ? half : half - barW,
        width: barW,
        borderRadius: isUp ? '0 4px 4px 0' : '4px 0 0 4px',
      }}/>
    </div>
  );
}

// ---------- Sale types grid card ----------
function SaleTypesGridCard({ onEdit }) {
  const CFG = WFP_CFG;
  return (
    <Card title="Loại sale & sự kiện" subtitle="Các sự kiện áp lực cao đẩy lưu lượng lên gấp nhiều lần baseline. Hệ số nhân áp dụng cùng với hệ số tháng.">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 12 }}>
        {CFG.SALE_TYPES.map(s => (
          <button key={s.code} onClick={() => onEdit(s)} style={{
            display: 'flex', flexDirection: 'column', textAlign: 'left',
            border: '1px solid var(--bx-border-muted)', borderRadius: 12, padding: 16,
            background: '#fff', cursor: 'pointer', gap: 10,
            fontFamily: 'var(--bx-font-sans)',
          }}
          onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--bx-primary)'}
          onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--bx-border-muted)'}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <Badge kind={s.code === 'MEGA_SALE' ? 'CRITICAL' : s.code === 'NORMAL' ? 'INACTIVE' : s.code === 'DOUBLE_DAY' ? 'WARNING' : 'INFO'} size="sm">
                {s.code}
              </Badge>
              <span style={{
                fontFamily: 'var(--bx-font-mono)', fontSize: 22, fontWeight: 700,
                color: s.color, fontVariantNumeric: 'tabular-nums',
              }}>×{s.mult.toFixed(2)}</span>
            </div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--bx-text-heading)' }}>{s.name}</div>
              <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{s.en}</div>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--bx-text-body)', lineHeight: 1.5,
              padding: '8px 10px', background: s.bg, borderRadius: 6, color: s.color, fontWeight: 500 }}>
              {s.examples}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--bx-text-muted)' }}>
              <Icon name="clock" size={11}/>
              <span>Lead time KAM: <b style={{ color: 'var(--bx-text-dark)' }}>{s.leadTimeDays} ngày</b></span>
              <div style={{ flex: 1 }}/>
              <span>Ưu tiên #{s.priority}</span>
            </div>
          </button>
        ))}
      </div>
    </Card>
  );
}

// ---------- Sale types usage card (sample applications) ----------
function SaleTypesUsageCard() {
  const CFG = WFP_CFG;
  // Combined factor chart: factor for May 2026 × each sale type
  const may = CFG.MONTHLY_FACTORS.find(m => m.month === 5);
  const nov = CFG.MONTHLY_FACTORS.find(m => m.month === 11);
  return (
    <Card title="Ví dụ hệ số kết hợp" subtitle={'Tháng × sale = hệ số cuối cùng áp vào WLU. So sánh ' + may.label + ' (bình thường) và ' + nov.label + ' (cao điểm).'}>
      <div style={{ width: '100%', overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 13 }}>
          <thead>
            <tr>
              <th style={th()}>Loại sale</th>
              <th style={th('right')}>× tháng 5 (×{may.factor})</th>
              <th style={th('right')}>× tháng 11 (×{nov.factor})</th>
              <th style={th('right')}>Chênh lệch</th>
            </tr>
          </thead>
          <tbody>
            {CFG.SALE_TYPES.map((s, i) => {
              const a = +(s.mult * may.factor).toFixed(2);
              const b = +(s.mult * nov.factor).toFixed(2);
              const delta = +((b - a) / a * 100).toFixed(0);
              return (
                <tr key={s.code} style={{ background: i % 2 === 1 ? 'rgba(245,245,245,0.4)' : '#fff' }}>
                  <td style={td()}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ width: 4, height: 22, borderRadius: 2, background: s.color }}/>
                      <span style={{ fontWeight: 600, color: 'var(--bx-text-dark)' }}>{s.name}</span>
                    </div>
                  </td>
                  <td style={tdNum()}>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 600 }}>×{a}</span>
                  </td>
                  <td style={tdNum()}>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, color: 'var(--bx-error)' }}>×{b}</span>
                  </td>
                  <td style={tdNum()}>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', color: 'var(--bx-error)', fontWeight: 600 }}>+{delta}%</span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

function th(align) {
  return {
    background: 'var(--bx-surface-2)', textAlign: align || '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)', whiteSpace: 'nowrap',
  };
}
function td() {
  return { padding: '11px 14px', borderBottom: '1px solid var(--bx-border-muted)', verticalAlign: 'middle' };
}
function tdNum() {
  return { ...td(), textAlign: 'right' };
}

// ---------- Formula applied card ----------
function FormulaAppliedCard() {
  const CFG = WFP_CFG;
  const may = CFG.MONTHLY_FACTORS.find(m => m.month === 5);
  const nov = CFG.MONTHLY_FACTORS.find(m => m.month === 11);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card title="Trình tự áp dụng" subtitle="Engine WLU đọc các tham số theo đúng thứ tự dưới đây mỗi khi tính khối lượng công việc cho một đơn.">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { idx: 1, label: 'Lookup UPH định mức', desc: 'Tra cứu UPH = norm[nhóm ngành hàng, nhóm PK, loại công việc]', source: 'Trang Định mức', icon: 'layers' },
            { idx: 2, label: 'Nhân hệ số phức tạp',  desc: 'UPH hiệu dụng = UPH × complexity_mult', source: 'Trang Định mức', icon: 'cube' },
            { idx: 3, label: 'Quy đổi giờ thô',        desc: 'hours = qty ÷ UPH hiệu dụng', source: 'Engine', icon: 'clock' },
            { idx: 4, label: 'Nhân hệ số tháng',       desc: 'hours × month_factor (mùa vụ năm)', source: 'Trang Tham số', icon: 'calendar' },
            { idx: 5, label: 'Nhân hệ số sale',         desc: 'WLU = hours × sale_factor (sự kiện trong ngày)', source: 'Trang Tham số', icon: 'rocket' },
          ].map(step => (
            <div key={step.idx} style={{
              display: 'flex', alignItems: 'flex-start', gap: 14,
              padding: 14, background: 'var(--bx-surface-2)', borderRadius: 10,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 9999, flexShrink: 0,
                background: '#fff', color: 'var(--bx-primary)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                border: '1px solid var(--bx-border-muted)',
                fontWeight: 700, fontFamily: 'var(--bx-font-mono)', fontSize: 13,
              }}>{step.idx}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Icon name={step.icon} size={13} style={{ color: 'var(--bx-text-muted)' }}/>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--bx-text-heading)' }}>{step.label}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--bx-text-body)', marginTop: 4, fontFamily: 'var(--bx-font-mono)' }}>{step.desc}</div>
                <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', marginTop: 4 }}>Nguồn: {step.source}</div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card title="Tác động kết hợp" subtitle={'Cùng một đơn hàng L’Oréal (1180 đơn vị · medium · đóng gói · Mix) thay đổi như thế nào theo bối cảnh.'}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          {[
            { label: 'Tháng 5 · Bình thường', month: may, sale: CFG.SALE_TYPES.find(s => s.code === 'NORMAL'),    tone: '#0b43ea' },
            { label: 'Tháng 5 · Payday',       month: may, sale: CFG.SALE_TYPES.find(s => s.code === 'PAYDAY'),    tone: '#15803d' },
            { label: 'Tháng 11 · Double Day',  month: nov, sale: CFG.SALE_TYPES.find(s => s.code === 'DOUBLE_DAY'), tone: '#d97706' },
            { label: 'Tháng 11 · Mega Sale',   month: nov, sale: CFG.SALE_TYPES.find(s => s.code === 'MEGA_SALE'),  tone: '#b91c1c' },
          ].map((sc, i) => {
            const norm = CFG.findNorm('IG-COSM', 'PK-MIX', 'WT-PACK', 'wh-vn-hn-01');
            const cx = CFG.COMPLEXITY.find(c => c.id === 'MEDIUM');
            const uphEff = norm.uph * cx.mult;
            const wlu = (1180 / uphEff) * sc.month.factor * sc.sale.mult;
            return (
              <div key={i} style={{
                border: '1px solid var(--bx-border-muted)', borderRadius: 12, padding: 14,
                display: 'flex', flexDirection: 'column', gap: 8,
              }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: sc.tone }}>{sc.label}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
                  <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 28, fontWeight: 700, color: 'var(--bx-text-heading)', fontVariantNumeric: 'tabular-nums' }}>
                    {wlu.toFixed(1)}
                  </span>
                  <span style={{ fontSize: 12, color: 'var(--bx-text-muted)' }}>WLU (giờ)</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', fontFamily: 'var(--bx-font-mono)' }}>
                  ÷{Math.round(uphEff)} × {sc.month.factor} × {sc.sale.mult}
                </div>
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

// ---------- Edit dialogs ----------
function MonthEditDialog({ open, month, onClose }) {
  const [factor, setFactor] = React.useState('');
  const [note, setNote] = React.useState('');
  React.useEffect(() => { if (open && month) { setFactor(String(month.factor)); setNote(month.note || ''); }}, [open, month]);
  if (!month) return null;
  const err = !factor || isNaN(Number(factor)) || Number(factor) < 0;
  return (
    <Dialog open={open} onClose={onClose} width={520}
      title={'Hệ số · ' + month.label}
      subtitle="Lưu sẽ sinh phiên bản mới và áp dụng cho mọi kế hoạch chạy sau hôm nay."
      footer={
        <>
          <Button variant="outline" onClick={onClose}>Hủy</Button>
          <Button variant="primary" disabled={err} icon="check" onClick={onClose}>Lưu</Button>
        </>
      }>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Hệ số hiện tại">
          <Input value={String(month.factor)} disabled/>
        </Field>
        <Field label="Hệ số mới" required hint="1.00 = baseline; ví dụ 1.55 = +55% so với TB năm">
          <Input value={factor} onChange={e => setFactor(e.target.value)} error={err ? 'Cần số > 0' : null}/>
        </Field>
        <Field label="Đánh dấu cao điểm" style={{ gridColumn: '1 / span 2' }}>
          <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
            <input type="checkbox" defaultChecked={month.peak} style={{ accentColor: 'var(--bx-primary)' }}/>
            <span>Tháng này được coi là cao điểm · tăng tần suất họp dự báo từ tuần lên 2 ngày/lần</span>
          </label>
        </Field>
        <Field label="Ghi chú" style={{ gridColumn: '1 / span 2' }} hint="Hiển thị trong nhật ký và bảng tháng.">
          <Input value={note} onChange={e => setNote(e.target.value)}/>
        </Field>
      </div>
    </Dialog>
  );
}

function SaleEditDialog({ open, sale, onClose }) {
  const isNew = sale && sale.isNew;
  const [code, setCode] = React.useState('');
  const [name, setName] = React.useState('');
  const [mult, setMult] = React.useState('');
  const [lead, setLead] = React.useState('');
  const [examples, setExamples] = React.useState('');
  React.useEffect(() => {
    if (open && sale) {
      setCode(sale.code || ''); setName(sale.name || '');
      setMult(String(sale.mult || '')); setLead(String(sale.leadTimeDays || ''));
      setExamples(sale.examples || '');
    }
  }, [open, sale]);
  if (!sale) return null;
  return (
    <Dialog open={open} onClose={onClose} width={560}
      title={isNew ? 'Loại sale mới' : 'Chỉnh sửa · ' + sale.name}
      subtitle={isNew ? 'Khai báo loại sự kiện mới để KAM có thể chọn khi gửi dự báo.' : 'Lưu sẽ sinh phiên bản mới và áp dụng cho mọi kế hoạch chạy sau hôm nay.'}
      footer={
        <>
          <Button variant="outline" onClick={onClose}>Hủy</Button>
          <Button variant="primary" icon={isNew ? 'plus' : 'check'} onClick={onClose}>
            {isNew ? 'Tạo loại sale' : 'Lưu'}
          </Button>
        </>
      }>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Mã" required hint="VIẾT_HOA_GẠCH_DƯỚI">
          <Input value={code} onChange={e => setCode(e.target.value.toUpperCase().replace(/\s+/g,'_'))} disabled={!isNew}/>
        </Field>
        <Field label="Tên hiển thị" required>
          <Input value={name} onChange={e => setName(e.target.value)}/>
        </Field>
        <Field label="Hệ số nhân" required hint="VD: ×4.50 cho Mega Sale">
          <Input value={mult} onChange={e => setMult(e.target.value)}/>
        </Field>
        <Field label="Lead time KAM (ngày)" required hint="KAM phải gửi dự báo trước X ngày">
          <Input value={lead} onChange={e => setLead(e.target.value)}/>
        </Field>
        <Field label="Ví dụ" style={{ gridColumn: '1 / span 2' }} hint="Liệt kê các ngày/sự kiện điển hình">
          <Input value={examples} onChange={e => setExamples(e.target.value)}/>
        </Field>
      </div>
    </Dialog>
  );
}

Object.assign(window, { ParamsScreen });
