/* ═══════════════════════════════════════════════════════════
   TransferModal (internal movements) + QuarantineSection
═══════════════════════════════════════════════════════════ */
(function () {
const { useState: useStateT } = React;
const {
  GUNS: GUNS_T, parseKey: parseKeyT, keyLabel: keyLabelT, ammoQtyBadge: badgeT,
  genId: genIdT, fmtDatetime: fmtT, Modal: ModalT, PasswordGate: PasswordGateT,
} = window;

function TransferModal({ state, dispatch, onClose }) {
  const [mode, setMode] = useStateT('p2g');
  const regs = state.registeredTypes;

  function P2GForm() {
    const [palletId, setPalletId] = useStateT('');
    const [gunSel, setGunSel] = useStateT({});
    const [qtys, setQtys] = useStateT({});
    const pallet = state.bunker.find(p => p.id === Number(palletId));
    const palletRegs = regs.filter(r => (pallet?.ammo[r.key] || 0) > 0);
    const selGuns = GUNS_T.filter(g => gunSel[g]);
    const setQty = (gun, key, v) => setQtys(p => ({ ...p, [gun + '::' + key]: Math.max(0, parseInt(v) || 0) }));
    const getQty = (gun, key) => qtys[gun + '::' + key] || 0;
    const sumForKey = key => selGuns.reduce((s, g) => s + getQty(g, key), 0);
    const keyValid = key => !pallet || sumForKey(key) <= (pallet.ammo[key] || 0);
    const canSub = selGuns.length > 0 && pallet && palletRegs.length > 0 && palletRegs.every(r => keyValid(r.key));
    const submit = () => {
      selGuns.forEach(gun => {
        const items = palletRegs.map(r => ({ key: r.key, qty: getQty(gun, r.key) })).filter(i => i.qty > 0);
        if (items.length) dispatch({ type: 'TRANSFER_PALLET_TO_GUN', palletId: Number(palletId), gun, items });
      });
      onClose();
    };
    return (
      <div>
        <div className="form-group" style={{ marginBottom: '.75rem', maxWidth: '250px' }}>
          <label>בחר משטח מקור</label>
          <select value={palletId} onChange={e => setPalletId(e.target.value)}>
            <option value="">— בחר —</option>
            {state.bunker.map(p => <option key={p.id} value={p.id}>משטח #{p.id}</option>)}
          </select>
        </div>
        {pallet && <>
          <div className="muted u-sm" style={{ marginBottom: '.5rem' }}>בחר צוותים מקבלים:</div>
          <div className="row" style={{ gap: '.4rem', flexWrap: 'wrap', marginBottom: '.75rem' }}>
            {GUNS_T.map(g => (
              <button key={g} className={'btn btn-sm ' + (gunSel[g] ? 'btn-amber' : 'btn-gray')}
                onClick={() => setGunSel(p => ({ ...p, [g]: !p[g] }))}>צוות {g}</button>
            ))}
          </div>
          {selGuns.length > 0 && palletRegs.length > 0 && (
            <div className="tbl-wrap" style={{ marginBottom: '.75rem' }}>
              <table>
                <thead><tr>
                  <th className="u-right">תחמושת</th><th>במשטח</th>
                  {selGuns.map(g => <th key={g}>צוות {g}</th>)}
                  <th>סה"כ חוסר</th>
                </tr></thead>
                <tbody>
                  {palletRegs.map(r => {
                    const avail = pallet.ammo[r.key] || 0;
                    const sum = sumForKey(r.key);
                    const over = sum > avail;
                    return (
                      <tr key={r.key}>
                        <td className="u-right">{r.label}</td>
                        <td>{badgeT(avail)}</td>
                        {selGuns.map(g => (
                          <td key={g}>
                            <input type="number" min="0" max={avail} value={getQty(g, r.key)}
                              onChange={e => setQty(g, r.key, e.target.value)}
                              style={{ width: '70px', textAlign: 'center', borderColor: over ? 'var(--danger)' : '' }} />
                          </td>
                        ))}
                        <td><span style={{ color: over ? 'var(--danger)' : 'var(--ok)', fontWeight: 700 }}>{sum}{over ? ' ⚠' : ''}</span></td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
          {selGuns.length === 0 && <div className="dim u-sm" style={{ marginBottom: '.75rem' }}>בחר לפחות צוות אחד ↑</div>}
          <button className="btn btn-blue" disabled={!canSub} onClick={submit}>↗ בצע העברה</button>
        </>}
      </div>
    );
  }

  function G2PForm() {
    const [palletId, setPalletId] = useStateT('');
    const [gunSel, setGunSel] = useStateT({});
    const [qtys, setQtys] = useStateT({});
    const selGuns = GUNS_T.filter(g => gunSel[g]);
    const setQty = (gun, key, v) => setQtys(p => ({ ...p, [gun + '::' + key]: Math.max(0, parseInt(v) || 0) }));
    const getQty = (gun, key) => qtys[gun + '::' + key] || 0;
    const availKeys = regs.filter(r => selGuns.some(g => (state.guns[g]?.[r.key] || 0) > 0));
    const gunValid = (gun, key) => getQty(gun, key) <= (state.guns[gun]?.[key] || 0);
    const canSub = palletId && selGuns.length > 0 && availKeys.length > 0
      && selGuns.every(g => availKeys.every(r => gunValid(g, r.key)))
      && selGuns.some(g => availKeys.some(r => getQty(g, r.key) > 0));
    const submit = () => {
      selGuns.forEach(gun => {
        const items = availKeys.map(r => ({ key: r.key, qty: getQty(gun, r.key) })).filter(i => i.qty > 0);
        if (items.length) dispatch({ type: 'TRANSFER_GUN_TO_PALLET', gun, palletId: Number(palletId), items });
      });
      onClose();
    };
    return (
      <div>
        <div className="form-group" style={{ marginBottom: '.75rem', maxWidth: '250px' }}>
          <label>בחר משטח יעד</label>
          <select value={palletId} onChange={e => setPalletId(e.target.value)}>
            <option value="">— בחר —</option>
            {state.bunker.map(p => <option key={p.id} value={p.id}>משטח #{p.id}</option>)}
          </select>
        </div>
        <div className="muted u-sm" style={{ marginBottom: '.5rem' }}>בחר צוותים מעבירים:</div>
        <div className="row" style={{ gap: '.4rem', flexWrap: 'wrap', marginBottom: '.75rem' }}>
          {GUNS_T.map(g => (
            <button key={g} className={'btn btn-sm ' + (gunSel[g] ? 'btn-amber' : 'btn-gray')}
              onClick={() => setGunSel(p => ({ ...p, [g]: !p[g] }))}>צוות {g}</button>
          ))}
        </div>
        {selGuns.length > 0 && availKeys.length > 0 && (
          <div className="tbl-wrap" style={{ marginBottom: '.75rem' }}>
            <table>
              <thead><tr><th className="u-right">תחמושת</th>{selGuns.map(g => <th key={g}>צוות {g} (זמין)</th>)}</tr></thead>
              <tbody>{availKeys.map(r => (
                <tr key={r.key}>
                  <td className="u-right">{r.label}</td>
                  {selGuns.map(g => {
                    const avail = state.guns[g]?.[r.key] || 0;
                    const over = getQty(g, r.key) > avail;
                    return (
                      <td key={g}>
                        <div className="row" style={{ gap: '.25rem', justifyContent: 'center' }}>
                          <span className="dim u-tiny mono">({avail})</span>
                          <input type="number" min="0" max={avail} value={getQty(g, r.key)}
                            onChange={e => setQty(g, r.key, e.target.value)}
                            style={{ width: '64px', textAlign: 'center', borderColor: over ? 'var(--danger)' : '' }} />
                        </div>
                      </td>
                    );
                  })}
                </tr>
              ))}</tbody>
            </table>
          </div>
        )}
        {selGuns.length === 0 && <div className="dim u-sm" style={{ marginBottom: '.75rem' }}>בחר לפחות צוות אחד ↑</div>}
        <button className="btn btn-teal" disabled={!canSub} onClick={submit}>↙ בצע החזרה למשטח</button>
      </div>
    );
  }

  function G2GForm() {
    const [src, setSrc] = useStateT('');
    const [dst, setDst] = useStateT('');
    const [qtys, setQtys] = useStateT({});
    const srcAmmo = src ? state.guns[src] || {} : {};
    const srcKeys = regs.filter(r => (srcAmmo[r.key] || 0) > 0);
    const setQty = (key, v) => setQtys(p => ({ ...p, [key]: Math.max(0, Math.min(srcAmmo[key] || 0, parseInt(v) || 0)) }));
    const items = srcKeys.map(r => ({ key: r.key, qty: qtys[r.key] || 0 })).filter(i => i.qty > 0);
    const canSub = src && dst && src !== dst && items.length > 0;
    const submit = () => { dispatch({ type: 'TRANSFER_GUN_TO_GUN', srcGun: src, dstGun: dst, items }); onClose(); };
    return (
      <div>
        <div className="form-row" style={{ marginBottom: '.75rem' }}>
          <div className="form-group grow">
            <label>צוות מקור</label>
            <select value={src} onChange={e => setSrc(e.target.value)}>
              <option value="">— בחר —</option>{GUNS_T.map(g => <option key={g} value={g}>צוות {g}</option>)}
            </select>
          </div>
          <div className="dim" style={{ alignSelf: 'flex-end', paddingBottom: '.4rem', fontSize: '1.2rem' }}>→</div>
          <div className="form-group grow">
            <label>צוות יעד</label>
            <select value={dst} onChange={e => setDst(e.target.value)}>
              <option value="">— בחר —</option>{GUNS_T.filter(g => g !== src).map(g => <option key={g} value={g}>צוות {g}</option>)}
            </select>
          </div>
        </div>
        {src && srcKeys.length === 0 && <div className="dim u-sm" style={{ marginBottom: '.75rem' }}>אין מלאי לצוות {src}</div>}
        {src && srcKeys.length > 0 && (
          <div className="stack" style={{ gap: '.35rem', marginBottom: '.75rem' }}>
            {srcKeys.map(r => (
              <div key={r.key} className="row" style={{ gap: '.5rem' }}>
                <span className="grow u-sm">{r.label}</span>
                <span className="dim u-tiny" style={{ width: '90px', textAlign: 'center' }}>זמין: {srcAmmo[r.key]} {r.unit}</span>
                <input type="number" min="0" max={srcAmmo[r.key]} value={qtys[r.key] || 0}
                  onChange={e => setQty(r.key, e.target.value)} style={{ width: '68px', textAlign: 'center' }} />
              </div>
            ))}
          </div>
        )}
        <button className="btn btn-purple" disabled={!canSub} onClick={submit}>↕ בצע ניוד צוות לצוות</button>
      </div>
    );
  }

  function QuarantineForm({ srcType }) {
    const [sel, setSel] = useStateT('');
    const [qtys, setQtys] = useStateT({});
    const [reason, setReason] = useStateT('');
    const [approver, setApprover] = useStateT('');
    const [imgB64, setImgB64] = useStateT('');
    const isGun = srcType === 'gun';
    const container = isGun ? (sel ? state.guns[sel] || {} : {}) : (state.bunker.find(p => p.id === Number(sel))?.ammo || {});
    const srcKeys = regs.filter(r => (container[r.key] || 0) > 0);
    const setQty = (key, v) => setQtys(p => ({ ...p, [key]: Math.max(0, Math.min(container[key] || 0, parseInt(v) || 0)) }));
    const items = srcKeys.map(r => ({ key: r.key, qty: qtys[r.key] || 0 })).filter(i => i.qty > 0);
    const canSub = sel && items.length > 0 && reason.trim() && approver.trim();
    const handleImg = e => { const f = e.target.files[0]; if (!f) return; const rd = new FileReader(); rd.onload = ev => setImgB64(ev.target.result); rd.readAsDataURL(f); };
    const submit = () => {
      dispatch(isGun
        ? { type: 'ADD_TO_QUARANTINE', srcType: 'gun', gunId: sel, items, reason: reason.trim(), approver: approver.trim(), imageB64: imgB64 }
        : { type: 'ADD_TO_QUARANTINE', srcType: 'pallet', palletId: Number(sel), items, reason: reason.trim(), approver: approver.trim(), imageB64: imgB64 });
      onClose();
    };
    return (
      <div>
        <div className="form-group" style={{ marginBottom: '.75rem', maxWidth: '250px' }}>
          <label>{isGun ? 'צוות מקור' : 'בחר משטח מקור'}</label>
          <select value={sel} onChange={e => { setSel(e.target.value); setQtys({}); }}>
            <option value="">— בחר —</option>
            {isGun ? GUNS_T.map(g => <option key={g} value={g}>צוות {g}</option>)
                   : state.bunker.map(p => <option key={p.id} value={p.id}>משטח #{p.id}</option>)}
          </select>
        </div>
        {sel && srcKeys.length === 0 && <div className="dim u-sm" style={{ marginBottom: '.75rem' }}>{isGun ? 'אין מלאי' : 'משטח ריק'}</div>}
        {sel && srcKeys.length > 0 && (
          <div className="stack" style={{ gap: '.35rem', marginBottom: '.75rem' }}>
            {srcKeys.map(r => (
              <div key={r.key} className="row" style={{ gap: '.5rem' }}>
                <span className="grow u-sm">{r.label}</span>
                <span className="dim u-tiny" style={{ width: '90px', textAlign: 'center' }}>זמין: {container[r.key]} {r.unit}</span>
                <input type="number" min="0" max={container[r.key]} value={qtys[r.key] || 0}
                  onChange={e => setQty(r.key, e.target.value)} style={{ width: '68px', textAlign: 'center' }} />
              </div>
            ))}
          </div>
        )}
        {sel && srcKeys.length > 0 && <>
          <div className="form-row" style={{ marginBottom: '.5rem' }}>
            <div className="form-group grow" style={{ flex: 2 }}>
              <label>סיבת הפסילה *</label>
              <input type="text" placeholder='פגז פגום, חנ"ה לחה...' value={reason} onChange={e => setReason(e.target.value)} />
            </div>
            <div className="form-group grow">
              <label>גורם מאשר *</label>
              <input type="text" placeholder="שם/תפקיד" value={approver} onChange={e => setApprover(e.target.value)} />
            </div>
          </div>
          <div className="form-group" style={{ marginBottom: '.75rem' }}>
            <label>צילום/תמונה (אופציונלי)</label>
            <input type="file" accept="image/*" capture="environment" onChange={handleImg} style={{ cursor: 'pointer' }} />
          </div>
        </>}
        <button className="btn btn-red" disabled={!canSub} onClick={submit}>⛔ העבר לפינת פסולים</button>
      </div>
    );
  }

  const modes = [
    { id: 'p2g', label: 'מרמסע לצוותים' },
    { id: 'g2p', label: 'צוותים לרמסע' },
    { id: 'g2g', label: 'צוות לצוות' },
    { id: 'g2q', label: 'מצוות לפינת פסולים' },
    { id: 'p2q', label: 'מרמסע לפינת פסולים' },
  ];
  return (
    <ModalT title="ניוד פנימי" icon="🔁" onClose={onClose} xl>
      <div className="seg" style={{ marginBottom: '1rem', width: '100%' }}>
        {modes.map(mo => (
          <button key={mo.id} className={mode === mo.id ? 'on' : ''} onClick={() => setMode(mo.id)}>{mo.label}</button>
        ))}
      </div>
      {mode === 'p2g' && <P2GForm />}
      {mode === 'g2p' && <G2PForm />}
      {mode === 'g2g' && <G2GForm />}
      {mode === 'g2q' && <QuarantineForm srcType="gun" />}
      {mode === 'p2q' && <QuarantineForm srcType="pallet" />}
    </ModalT>
  );
}

// ── Quarantine section (full panel) ──────────────────────────
function QuarantineSection({ state, regs, dispatch }) {
  const [viewImg, setViewImg] = useStateT(null);
  const [authPending, setAuthPending] = useStateT(null);
  const [actionPending, setActionPending] = useStateT(null);
  const [dstGun, setDstGun] = useStateT('');
  const log = state.quarantineLog || [];

  function confirmAction() {
    if (!actionPending) return;
    if (actionPending.type === 'return') {
      if (!dstGun) return;
      dispatch({ type: 'RETURN_FROM_QUARANTINE', entryId: actionPending.entry.id, dstGun });
    } else {
      dispatch({ type: 'SCRAP_QUARANTINE', entryId: actionPending.entry.id });
    }
    setActionPending(null); setDstGun('');
  }

  return (
    <div className="section-card">
      <div className="section-header">
        <span className="section-title" style={{ color: 'var(--danger)' }}>⛔ פינת פסולים</span>
        <span className="dim u-tiny">רשומות: {log.length}</span>
      </div>
      <div className="tbl-wrap">
        {log.length === 0 ? (
          <div className="empty"><div className="big">✓</div>אין תחמושת פסולה</div>
        ) : (
          <table>
            <thead><tr>
              <th>תאריך ושעה</th><th>מקור</th><th>תחמושת</th><th>סיבת פסילה</th><th>גורם מאשר</th><th>תמונה</th><th>פעולות בוחן</th>
            </tr></thead>
            <tbody>
              {[...log].reverse().map(r => (
                <tr key={r.id}>
                  <td className="u-nowrap mono u-tiny">{fmtT(r.datetime)}</td>
                  <td><span className="u-bold" style={{ color: 'var(--accent)' }}>{r.src}</span></td>
                  <td className="wrap u-right" style={{ minWidth: '160px' }}>
                    {(r.items || []).map((it, j) => (
                      <div key={j} className="u-sm">
                        <span className="muted">{keyLabelT(it.key, regs)}</span>
                        <span style={{ color: 'var(--danger)', fontWeight: 700 }}> ×{it.qty}</span>
                      </div>
                    ))}
                  </td>
                  <td className="wrap u-sm" style={{ color: 'var(--danger)', minWidth: '130px' }}>{r.reason}</td>
                  <td className="u-sm muted">{r.approver}</td>
                  <td>{r.imageB64 ? <button className="btn btn-gray btn-sm" onClick={() => setViewImg(r.imageB64)}>📷 הצג</button> : <span className="faint">—</span>}</td>
                  <td>
                    <div className="stack" style={{ gap: '.25rem' }}>
                      <button className="btn btn-green btn-sm" onClick={() => setAuthPending({ type: 'return', entry: r })}>✔ החזרה לשימוש</button>
                      <button className="btn btn-red btn-sm" onClick={() => setAuthPending({ type: 'scrap', entry: r })}>🗑 גריטת תחמושת</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {authPending && (
        <PasswordGateT onSuccess={() => { setActionPending(authPending); setAuthPending(null); setDstGun(''); }} onCancel={() => setAuthPending(null)} />
      )}

      {actionPending && (
        <ModalT title={actionPending.type === 'return' ? '✔ החזרה לשימוש — מאומת' : '🗑 גריטת תחמושת — מאומת'} onClose={() => { setActionPending(null); setDstGun(''); }}>
          <div className="stack" style={{ gap: '.75rem' }}>
            <div className="subpanel">
              <div className="dim u-tiny" style={{ marginBottom: '.3rem' }}>תחמושת מהרשומה:</div>
              {(actionPending.entry.items || []).map((it, j) => (
                <div key={j} className="u-sm">
                  <span>{keyLabelT(it.key, regs)}</span>
                  <span style={{ color: 'var(--danger)', fontWeight: 700 }}> ×{it.qty}</span>
                </div>
              ))}
              <div className="dim u-tiny" style={{ marginTop: '.35rem' }}>מקור מקורי: <span style={{ color: 'var(--accent)' }}>{actionPending.entry.src}</span></div>
            </div>
            {actionPending.type === 'return' && (
              <div className="form-group">
                <label>בחר צוות מקבל:</label>
                <select value={dstGun} onChange={e => setDstGun(e.target.value)} style={{ borderColor: 'var(--ok)' }}>
                  <option value="">— בחר —</option>{GUNS_T.map(g => <option key={g} value={g}>צוות {g}</option>)}
                </select>
              </div>
            )}
            {actionPending.type === 'scrap' && (
              <div className="callout callout-danger u-center u-bold">⚠ התחמושת תסולק לצמיתות מהמערכת.</div>
            )}
            <div className="row" style={{ gap: '.5rem', justifyContent: 'flex-end' }}>
              <button className="btn btn-gray" onClick={() => { setActionPending(null); setDstGun(''); }}>ביטול</button>
              <button className={actionPending.type === 'return' ? 'btn btn-green' : 'btn btn-red'}
                disabled={actionPending.type === 'return' && !dstGun} onClick={confirmAction}>
                {actionPending.type === 'return' ? '✔ אשר החזרה' : '🗑 אשר גריטה'}
              </button>
            </div>
          </div>
        </ModalT>
      )}

      {viewImg && (
        <div className="modal-overlay" onClick={() => setViewImg(null)}>
          <div className="card card-pad" style={{ maxWidth: '90vw', maxHeight: '90vh', overflow: 'auto' }} onClick={e => e.stopPropagation()}>
            <img src={viewImg} alt="תמונה" style={{ maxWidth: '100%', borderRadius: 'var(--r1)', display: 'block' }} />
            <div className="u-center" style={{ marginTop: '.6rem' }}>
              <button className="btn btn-gray btn-sm" onClick={() => setViewImg(null)}>✕ סגור</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.TransferModal = TransferModal;
window.QuarantineSection = QuarantineSection;
})();
