/* screens-customer-config.jsx — Tùy chỉnh tab + Approvals card + Alerts card
   for the customer detail page. */

// ============================================================
// Approvals card (Plan tab)
// ============================================================
function ApprovalsCard({ rows, navigate }) {
  const pending = rows.filter(r => r.status === 'PENDING');
  const approved = rows.filter(r => r.status === 'APPROVED').length;
  const rejected = rows.filter(r => r.status === 'REJECTED').length;
  return (
    <Card title="Yêu cầu phê duyệt"
      subtitle={pending.length > 0
        ? pending.length + ' chờ duyệt · ' + approved + ' đã duyệt · ' + rejected + ' từ chối · trong 14 ngày'
        : 'Không có yêu cầu mới · ' + approved + ' đã duyệt · ' + rejected + ' từ chối'}
      padding={0}
      actions={
        rows.length > 0 && (
          <Button size="sm" variant="ghost-primary" icon="external" onClick={() => navigate('/planner/forecast/review')}>
            Mở phê duyệt
          </Button>
        )
      }>
      {rows.length === 0 ? (
        <Empty icon="check" title="Chưa có yêu cầu điều chỉnh"
          subtitle="KAM chưa gửi override nào trong 14 ngày tới."/>
      ) : (
        <Table dense
          columns={[
            { header: 'Ngày', mono: true, render: r => (
              <div>
                <div style={{ fontWeight: 600 }}>{fmt.shortDate(r.date)}</div>
                <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)' }}>{viWeekday(r.date)}</div>
              </div>
            )},
            { header: 'SKU', render: r => (
              <div>
                <div style={{ fontWeight: 500, color: 'var(--bx-text-dark)' }}>{r.productName}</div>
                <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)', fontFamily: 'var(--bx-font-mono)' }}>{r.bsin}</div>
              </div>
            )},
            { header: 'Baseline', priority: 2, mono: true, align: 'right', render: r => fmt.int(r.qtyBaseline) },
            { header: 'Override', mono: true, align: 'right', render: r => (
              <div>
                <div style={{ fontWeight: 700, color: 'var(--bx-text-dark)' }}>{fmt.int(r.qtyOverride)}</div>
                <div style={{ fontSize: 10.5, fontWeight: 600,
                  color: r.delta > 0 ? 'var(--bx-success)' : 'var(--bx-error)' }}>
                  {r.delta > 0 ? '+' : ''}{Math.round(r.delta / r.qtyBaseline * 100)}%
                </div>
              </div>
            )},
            { header: 'Cảnh báo', priority: 2, render: r => r.warningCode ? (
              <Badge kind={r.warningCode === 'EXCEEDS_HISTORICAL_3X' ? 'CRITICAL' : 'WARNING'} size="sm">
                {r.warningCode === 'EXCEEDS_HISTORICAL_3X' ? '> 3× lịch sử'
                 : r.warningCode === 'EXCEEDS_HISTORICAL_2X' ? '> 2× lịch sử'
                 : r.warningCode === 'BELOW_HISTORICAL_50PCT' ? '< 50% lịch sử' : r.warningCode}
              </Badge>
            ) : <span style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>—</span> },
            { header: 'Trạng thái', render: r => (
              <Badge kind={r.status === 'APPROVED' ? 'APPROVED'
                : r.status === 'REJECTED' ? 'CRITICAL'
                : 'WARNING'} size="sm">{r.status}</Badge>
            )},
            { header: '', priority: 2, width: 90, render: r => r.status === 'PENDING' ? (
              <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                <IconBtn name="check" size={26} title="Duyệt"/>
                <IconBtn name="x" size={26} title="Từ chối"/>
              </div>
            ) : null },
          ]}
          rows={rows} getRowKey={r => r.id}/>
      )}
    </Card>
  );
}

// ============================================================
// Alerts card (Plan tab)
// ============================================================
function AlertsCard({ alerts }) {
  if (alerts.length === 0) {
    return (
      <Card title="Cảnh báo & gợi ý" subtitle="AM · Planner" padding={0}>
        <Empty icon="check" title="Mọi thứ ổn"
          subtitle="Không có cảnh báo nào cho khách hàng này."/>
      </Card>
    );
  }
  return (
    <Card title="Cảnh báo & gợi ý" subtitle={alerts.length + ' mục cần lưu ý · AM · Planner'} padding={0}>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {alerts.map((a, i) => <AlertRow key={i} a={a} last={i === alerts.length - 1}/>)}
      </div>
    </Card>
  );
}

function AlertRow({ a, last }) {
  const tone = a.severity === 'CRITICAL' ? {
    border: '#fecaca', bg: '#fef2f2', dot: '#dc2626', fg: '#b91c1c',
  } : a.severity === 'WARNING' ? {
    border: '#fde68a', bg: '#fefce8', dot: '#d97706', fg: '#92400e',
  } : {
    border: '#e0e7ff', bg: '#eff6ff', dot: '#2563eb', fg: '#1e40af',
  };
  return (
    <div style={{
      padding: '12px 14px',
      borderBottom: last ? 'none' : '1px solid var(--bx-border-muted)',
      display: 'flex', gap: 12, alignItems: 'flex-start',
    }}>
      <div style={{
        width: 28, height: 28, flexShrink: 0, borderRadius: 8,
        background: tone.bg, color: tone.fg, border: '1px solid ' + tone.border,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={a.icon} size={13}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--bx-text-heading)' }}>{a.title}</span>
          <span style={{
            fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em',
            padding: '2px 6px', borderRadius: 9999,
            background: 'var(--bx-surface-2)', color: 'var(--bx-text-muted)',
            textTransform: 'uppercase',
          }}>cho {a.actor}</span>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--bx-text-body)', marginTop: 4, lineHeight: 1.5 }}>{a.body}</div>
        {a.action && (
          <div style={{ marginTop: 8 }}>
            <Button size="sm" variant="ghost-primary" icon={a.action.icon}>{a.action.label}</Button>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================================
// Tùy chỉnh tab
// ============================================================
function CustomerConfigTab({ c }) {
  // Default productivity (UPH) per role, customer-specific
  const baseUph = c.tier === 'KEY' ? { PICKER: 110, PACKER: 140, CHECKER: 220 }
    : c.tier === 'MAJOR'    ? { PICKER: 120, PACKER: 155, CHECKER: 245 }
    :                         { PICKER: 132, PACKER: 168, CHECKER: 268 };
  // Default product mix by tier/segment
  const baseMix = c.tier === 'KEY' ? { SINGLE: 36, MIX: 28, BUNDLE: 22, HEAVY: 6,  FRAGILE: 8  }
    : c.tier === 'MAJOR'    ? { SINGLE: 44, MIX: 32, BUNDLE: 14, HEAVY: 6,  FRAGILE: 4  }
    :                         { SINGLE: 56, MIX: 24, BUNDLE: 12, HEAVY: 5,  FRAGILE: 3  };

  const [tier, setTier]   = React.useState(c.tier);
  const [uph,  setUph]    = React.useState(baseUph);
  const [mix,  setMix]    = React.useState(baseMix);
  const [field, setField] = React.useState(c.tier !== 'KEY'); // KEY default no
  const [fieldNote, setFieldNote] = React.useState('Cho phép trong tình huống quá tải > 130% năng lực. Không áp dụng cho SKU FRAGILE và HEAVY.');
  const [dirty, setDirty] = React.useState(false);

  React.useEffect(() => { setDirty(true); }, [tier, uph, mix, field, fieldNote]);
  // initial mount: not dirty
  React.useEffect(() => { setDirty(false); }, []);

  const mixTotal = Object.values(mix).reduce((s, v) => s + v, 0);
  const { isMobile, vw } = useViewport();

  function resetAll() {
    setTier(c.tier); setUph(baseUph); setMix(baseMix);
    setField(c.tier !== 'KEY');
    setFieldNote('Cho phép trong tình huống quá tải > 130% năng lực. Không áp dụng cho SKU FRAGILE và HEAVY.');
    setTimeout(() => setDirty(false), 0);
  }

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Save bar */}
      {dirty && (
        <div style={{
          padding: '10px 14px',
          background: 'color-mix(in oklab, #eff6ff 65%, #fff)',
          border: '1px solid #bfdbfe', borderRadius: 13,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <Icon name="info" size={14} style={{ color: 'var(--bx-primary)' }}/>
          <div style={{ flex: 1, fontSize: 12.5, color: 'var(--bx-text-body)' }}>
            Có thay đổi chưa lưu. Tham số mới sẽ áp dụng cho forecast & shift plan từ ca tiếp theo.
          </div>
          <Button size="sm" variant="ghost" onClick={resetAll}>Hoàn tác</Button>
          <Button size="sm" variant="primary" icon="check" onClick={() => setDirty(false)}>Lưu thay đổi</Button>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: vw < 1100 ? '1fr' : '1fr 1fr', gap: 16 }}>
        {/* Tier */}
        <Card title="Tier khách hàng" subtitle="Quyết định ưu tiên xếp ca, ngưỡng cảnh báo và độ ưu tiên duyệt forecast">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
            {[
              { id: 'KEY', label: 'Key', sub: 'Trọng điểm · cut-off 48h trước sale', tone: '#0b43ea', bg: '#eef2ff' },
              { id: 'MAJOR', label: 'Major', sub: 'Lớn · cut-off 24h trước sale',  tone: '#2563eb', bg: '#eff6ff' },
              { id: 'STANDARD', label: 'Standard', sub: 'Phổ thông · forecast tự động', tone: '#737373', bg: '#f5f5f5' },
            ].map(t => {
              const active = tier === t.id;
              return (
                <button key={t.id} onClick={() => setTier(t.id)} style={{
                  textAlign: 'left', padding: '12px 14px', borderRadius: 11,
                  background: active ? t.bg : '#fff',
                  border: '1.5px solid ' + (active ? t.tone : 'var(--bx-border)'),
                  cursor: 'pointer', fontFamily: 'var(--bx-font-sans)',
                  display: 'flex', flexDirection: 'column', gap: 4,
                }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 9999, background: t.tone }}/>
                    <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--bx-text-dark)' }}>{t.label}</span>
                    {active && <Icon name="check" size={11} style={{ color: t.tone, marginLeft: 'auto' }}/>}
                  </span>
                  <span style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{t.sub}</span>
                </button>
              );
            })}
          </div>
          <div style={{ marginTop: 14, padding: 10, background: 'var(--bx-surface-2)', borderRadius: 8, fontSize: 11.5, color: 'var(--bx-text-body)', lineHeight: 1.5 }}>
            <Icon name="info" size={11} style={{ marginRight: 4 }}/>
            <b>Khách hiện tại</b>: {c.tier} → {tier}. {tier === 'KEY'
              ? 'Khi đổi sang Key, mọi override > 2× baseline sẽ tự bật quy trình duyệt 2 cấp.'
              : tier === 'MAJOR' ? 'Major dùng quy trình duyệt 1 cấp; ngưỡng cảnh báo 2.5× baseline.'
              : 'Standard tự động duyệt nếu nằm trong band ±25% baseline.'}
          </div>
        </Card>

        {/* Field packing */}
        <Card title="Đóng gói hàng dã chiến"
          subtitle="Cho phép Packer dùng vật tư thay thế khi quá tải — tránh delay nhưng đổi lại chuẩn mỹ thuật">
          <div style={{
            display: 'flex', alignItems: 'flex-start', gap: 14,
            padding: 12, borderRadius: 10,
            background: field ? '#f0fdf4' : 'var(--bx-surface-2)',
            border: '1px solid ' + (field ? '#bbf7d0' : 'var(--bx-border-muted)'),
          }}>
            <Toggle on={field} onChange={() => setField(v => !v)}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--bx-text-dark)' }}>
                {field ? 'Cho phép' : 'Không cho phép'}
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--bx-text-muted)', marginTop: 3, lineHeight: 1.5 }}>
                {field ? 'Khi WLU vượt 130% năng lực, hệ thống sẽ đề xuất gói dã chiến tự động.'
                       : 'Mọi đơn phải dùng vật tư chuẩn brand. Khi quá tải → escalate sang điều phối ca.'}
              </div>
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <Field label="Ghi chú điều kiện áp dụng" hint="Hiển thị trong picking list cho trưởng ca">
              <textarea value={fieldNote} onChange={e => setFieldNote(e.target.value)}
                disabled={!field}
                rows={3} style={{
                  width: '100%', resize: 'vertical', minHeight: 56,
                  border: '1px solid var(--bx-border)', borderRadius: 10, padding: 10,
                  fontFamily: 'var(--bx-font-sans)', fontSize: 12.5, color: 'var(--bx-text-dark)',
                  background: field ? '#fff' : 'var(--bx-surface-2)',
                  opacity: field ? 1 : 0.6,
                }}/>
            </Field>
          </div>
          <div style={{ marginTop: 8, fontSize: 11, color: 'var(--bx-text-muted)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="shield" size={10}/>
            Đã xác nhận từ KAM ngày 12/04/2026 · giấy thỏa thuận #PKG-{c.code}-2026
          </div>
        </Card>

        {/* UPH defaults */}
        <Card title="Năng suất trung bình mặc định"
          subtitle="UPH (units / hour) áp dụng khi tính nhân lực cho khách này — ghi đè UPH global">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {Object.entries(uph).map(([role, val]) => (
              <UphRow key={role} role={role} value={val}
                onChange={v => setUph(prev => ({ ...prev, [role]: v }))}
                base={baseUph[role]}/>
            ))}
          </div>
          <div style={{ marginTop: 12, padding: 10, background: 'var(--bx-surface-2)', borderRadius: 8,
            fontSize: 11.5, color: 'var(--bx-text-body)', lineHeight: 1.5 }}>
            <Icon name="info" size={11} style={{ marginRight: 4 }}/>
            UPH mặc định cho khách <b>{c.tier}</b>: Picker {baseUph.PICKER}, Packer {baseUph.PACKER}, Checker {baseUph.CHECKER}.
            Khách này có SKU phức tạp hơn 12% trung bình → UPH thấp hơn baseline.
          </div>
        </Card>

        {/* Product group mix */}
        <Card title="Tỷ lệ nhóm ngành hàng"
          subtitle="Mix loại đơn ảnh hưởng độ phức tạp (WLU) — Heavy & Fragile tốn nhiều giờ hơn">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {WFP.PRODUCT_GROUPS.map(g => (
              <MixRow key={g.id} g={g} value={mix[g.id]}
                onChange={v => setMix(prev => ({ ...prev, [g.id]: v }))}/>
            ))}
          </div>
          <div style={{ marginTop: 12, padding: 10, borderRadius: 8,
            background: Math.abs(mixTotal - 100) <= 0.5 ? 'var(--bx-surface-2)' : '#fef2f2',
            border: Math.abs(mixTotal - 100) <= 0.5 ? 'none' : '1px solid #fecaca',
            fontSize: 12, color: 'var(--bx-text-body)',
            display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name={Math.abs(mixTotal - 100) <= 0.5 ? 'check' : 'warning'} size={11}
              style={{ color: Math.abs(mixTotal - 100) <= 0.5 ? 'var(--bx-success)' : 'var(--bx-error)' }}/>
            <span style={{ flex: 1 }}>Tổng tỷ lệ</span>
            <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700,
              color: Math.abs(mixTotal - 100) <= 0.5 ? 'var(--bx-success)' : 'var(--bx-error)' }}>
              {mixTotal.toFixed(0)}%
            </span>
            {Math.abs(mixTotal - 100) > 0.5 && (
              <Button size="sm" variant="ghost-primary" onClick={() => {
                // normalize
                const sum = mixTotal || 1;
                const next = {};
                WFP.PRODUCT_GROUPS.forEach(g => { next[g.id] = Math.round(mix[g.id] / sum * 100); });
                setMix(next);
              }}>Chuẩn hóa</Button>
            )}
          </div>
        </Card>
      </div>
    </div>
  );
}

// ---------- Sub-widgets ----------
function UphRow({ role, value, onChange, base }) {
  const label = role === 'PICKER' ? 'Nhặt hàng (Picker)' : role === 'PACKER' ? 'Đóng gói (Packer)' : 'Kiểm hàng (Checker)';
  const min = Math.round(base * 0.6), max = Math.round(base * 1.4);
  const delta = ((value - base) / base) * 100;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ width: 150, minWidth: 150 }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--bx-text-dark)' }}>{label}</div>
        <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)' }}>baseline {base} UPH</div>
      </div>
      <input type="range" min={min} max={max} value={value} step={1}
        onChange={e => onChange(+e.target.value)}
        style={{ flex: 1, accentColor: 'var(--bx-primary)' }}/>
      <div style={{ width: 78, minWidth: 78, textAlign: 'right' }}>
        <div style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 14, color: 'var(--bx-text-dark)' }}>{value}</div>
        <div style={{ fontSize: 10.5, fontFamily: 'var(--bx-font-mono)',
          color: Math.abs(delta) < 0.5 ? 'var(--bx-text-muted)'
            : delta > 0 ? 'var(--bx-success)' : 'var(--bx-error)' }}>
          {delta > 0 ? '+' : ''}{delta.toFixed(0)}% vs baseline
        </div>
      </div>
    </div>
  );
}

function MixRow({ g, value, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ width: 150, minWidth: 150, display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ width: 10, height: 10, borderRadius: 3, background: g.color, flexShrink: 0 }}/>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--bx-text-dark)' }}>{g.label}</div>
          <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)' }}>{g.sublabel}</div>
        </div>
      </div>
      <input type="range" min={0} max={100} value={value} step={1}
        onChange={e => onChange(+e.target.value)}
        style={{ flex: 1, accentColor: g.color }}/>
      <div style={{ width: 50, minWidth: 50, textAlign: 'right',
        fontFamily: 'var(--bx-font-mono)', fontWeight: 700, fontSize: 13, color: 'var(--bx-text-dark)' }}>
        {value}%
      </div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={onChange} role="switch" aria-checked={on} style={{
      width: 42, height: 24, borderRadius: 9999, position: 'relative',
      background: on ? 'var(--bx-success)' : 'var(--bx-border)',
      border: 'none', cursor: 'pointer', padding: 0, flexShrink: 0,
      transition: 'background 150ms var(--bx-ease)',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 20 : 2,
        width: 20, height: 20, borderRadius: '50%', background: '#fff',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
        transition: 'left 150ms var(--bx-ease)',
      }}/>
    </button>
  );
}

Object.assign(window, { CustomerConfigTab, ApprovalsCard, AlertsCard, AlertRow, UphRow, MixRow, Toggle });
