/* screens-pph-ppo-profile.jsx — PPH / PPO Calibration Profile catalog (US-09).
   Hai tab: WH Productivity Profile (PPH) + WH PPO Profile.
   "Calibrate now" button simulate recalc; override toggle skip job lần sau. */

function PphPpoProfileScreen({ warehouseId, navigate, addToast }) {
  const P = window.WFP_POINTS;
  const [tab, setTab] = React.useState('PPH');
  const [pph, setPph] = React.useState(P.PPH_PROFILES.slice());
  const [ppo, setPpo] = React.useState(P.PPO_PROFILES.slice());
  const [fcFilter, setFcFilter] = React.useState('LMX');
  const [etFilter, setEtFilter] = React.useState('all');
  const [taskFilter, setTaskFilter] = React.useState('all');

  const fcOpts = [{ value: 'all', label: 'Tất cả FC' }, ...P.BRANCHES.map(b => ({ value: b.id, label: b.label }))];
  const etOpts = [{ value: 'all', label: 'Tất cả employment' }, ...P.EMPLOYMENT_TYPES.map(e => ({ value: e.id, label: e.label }))];
  const taskOpts = [{ value: 'all', label: 'Tất cả task' }, ...P.TASK_TYPES.map(t => ({ value: t.id, label: t.label }))];

  function calibrateAllPPH() {
    setPph(prev => prev.map(r => P.recalibratePPHRow(Object.assign({}, r))));
    if (addToast) addToast({ kind: 'SUCCESS', title: 'PPH calibration done', body: `${pph.filter(r => !r.override).length} rows updated` });
  }
  function calibrateAllPPO() {
    setPpo(prev => prev.map(r => P.recalibratePPORow(Object.assign({}, r))));
    if (addToast) addToast({ kind: 'SUCCESS', title: 'PPO calibration done', body: `${ppo.filter(r => !r.override).length} rows updated` });
  }
  function toggleOverridePPH(idx) {
    setPph(prev => prev.map((r, i) => i === idx ? Object.assign({}, r, { override: r.override ? 0 : 1 }) : r));
  }
  function toggleOverridePPO(idx) {
    setPpo(prev => prev.map((r, i) => i === idx ? Object.assign({}, r, { override: r.override ? 0 : 1 }) : r));
  }

  const pphVisible = pph
    .map((r, i) => Object.assign({}, r, { _idx: i }))
    .filter(r => (fcFilter === 'all' || r.fulfillment_center === fcFilter)
              && (etFilter === 'all' || r.employment_type === etFilter)
              && (taskFilter === 'all' || r.task_type === taskFilter));

  const ppoVisible = ppo
    .map((r, i) => Object.assign({}, r, { _idx: i }))
    .filter(r => (fcFilter === 'all' || r.fulfillment_center === fcFilter)
              && (taskFilter === 'all' || r.task_type === taskFilter));

  return (
    <div style={{ padding: 20, overflowY: 'auto' }}>
      <PageHeader title="PPH / PPO Calibration Profile"
                  subtitle="Catalog năng suất + định mức điểm — calibrate hàng tháng từ WH KPI Summary + BigQuery"/>

      <Tabs value={tab} onChange={setTab} tabs={[
        { value: 'PPH', label: 'WH Productivity Profile (PPH)' },
        { value: 'PPO', label: 'WH PPO Profile' },
      ]}/>

      <Card title="Filters" padding={12} style={{ marginTop: 12, marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'flex-end' }}>
          <Field label="Fulfillment Center" style={{ minWidth: 200 }}>
            <Select value={fcFilter} onChange={setFcFilter} options={fcOpts}/>
          </Field>
          {tab === 'PPH' && (
            <Field label="Employment Type" style={{ minWidth: 180 }}>
              <Select value={etFilter} onChange={setEtFilter} options={etOpts}/>
            </Field>
          )}
          <Field label="Task" style={{ minWidth: 160 }}>
            <Select value={taskFilter} onChange={setTaskFilter} options={taskOpts}/>
          </Field>
          <div style={{ flex: 1 }}/>
          {tab === 'PPH'
            ? <Button variant="primary" icon="zap" onClick={calibrateAllPPH}>Calibrate PPH now</Button>
            : <Button variant="primary" icon="zap" onClick={calibrateAllPPO}>Calibrate PPO now</Button>}
        </div>
      </Card>

      {tab === 'PPH' && (
        <Card title={`PPH rows (${pphVisible.length})`} padding={0}>
          <table style={{ width: '100%', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bx-page-bg)', color: 'var(--bx-text-muted)' }}>
                <th style={{ padding: 8, textAlign: 'left' }}>Designation</th>
                <th style={{ padding: 8 }}>Employment</th>
                <th style={{ padding: 8 }}>FC</th>
                <th style={{ padding: 8 }}>Task</th>
                <th style={{ padding: 8, textAlign: 'right' }}>PPH p25</th>
                <th style={{ padding: 8, textAlign: 'right' }}>Median</th>
                <th style={{ padding: 8, textAlign: 'right' }}>p75</th>
                <th style={{ padding: 8, textAlign: 'right' }}>Sample</th>
                <th style={{ padding: 8 }}>Last calibrated</th>
                <th style={{ padding: 8 }}>Override</th>
              </tr>
            </thead>
            <tbody>
              {pphVisible.map(r => (
                <tr key={r.name}>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}><strong>{r.designation}</strong></td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>{r.employment_type}</td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>{r.fulfillment_center}</td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>{r.task_type}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace', color: 'var(--bx-color-red)' }}>{r.pph_p25.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace', fontWeight: 700 }}>{r.pph_median.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace', color: 'var(--bx-color-green)' }}>{r.pph_p75.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)' }}>{r.sample_size}</td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)', fontSize: 12 }}>{r.last_calibrated}<br/><span style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>{r.calibration_period}</span></td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>
                    <Button size="sm" variant={r.override ? 'secondary' : 'ghost'} onClick={() => toggleOverridePPH(r._idx)}>
                      {r.override ? '🔒 Override' : 'Auto'}
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {tab === 'PPO' && (
        <Card title={`PPO rows (${ppoVisible.length})`} padding={0}>
          <table style={{ width: '100%', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bx-page-bg)', color: 'var(--bx-text-muted)' }}>
                <th style={{ padding: 8, textAlign: 'left' }}>FC</th>
                <th style={{ padding: 8 }}>Task</th>
                <th style={{ padding: 8, textAlign: 'right' }}>PPO median (pts/order)</th>
                <th style={{ padding: 8, textAlign: 'right' }}>Sample pts</th>
                <th style={{ padding: 8, textAlign: 'right' }}>Sample orders</th>
                <th style={{ padding: 8 }}>Last calibrated</th>
                <th style={{ padding: 8 }}>Override</th>
              </tr>
            </thead>
            <tbody>
              {ppoVisible.map(r => (
                <tr key={r.name}>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}><strong>{r.fulfillment_center}</strong></td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>{r.task_type}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace', fontWeight: 700 }}>{r.ppo_median.toFixed(2)}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{r.sample_size_pts.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, textAlign: 'right', borderTop: '1px solid var(--bx-border-soft)', fontFamily: 'monospace' }}>{r.sample_size_orders.toLocaleString('vi-VN')}</td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)', fontSize: 12 }}>{r.last_calibrated}<br/><span style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>{r.calibration_period}</span></td>
                  <td style={{ padding: 8, borderTop: '1px solid var(--bx-border-soft)' }}>
                    <Button size="sm" variant={r.override ? 'secondary' : 'ghost'} onClick={() => toggleOverridePPO(r._idx)}>
                      {r.override ? '🔒 Override' : 'Auto'}
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      <Card padding={12} style={{ marginTop: 12, background: 'var(--bx-page-bg)' }}>
        <div style={{ fontSize: 12, color: 'var(--bx-text-muted)' }}>
          <strong>Calibration logic (proposal §FR-2.3, §FR-3.3):</strong><br/>
          • PPH per (designation × employment_type × fc × task) = median(primary_point / working_hours) cho employees có attendance_ratio ≥ 80% và working_hours ≥ 80.<br/>
          • PPO per (fc × task) = Σ(KPI Detail.total_point) / Σ(orders_rev.total_order) tháng trước.<br/>
          • Override = 1 → job calibration tháng kế bỏ qua row này.
        </div>
      </Card>
    </div>
  );
}

window.PphPpoProfileScreen = PphPpoProfileScreen;
