/* ═══════════════════════════════════════════════════════════
   FireMissionModal + EditGunStockModal
   Full combo/validation logic preserved; colors tokenized.
═══════════════════════════════════════════════════════════ */
(function () {
const { useState: useStateF } = React;
const {
  GUNS: GUNS_F, CHARGE_BEHAVIORS: CB_F, CHARGE_TYPE_NAMES: CTN_F,
  parseKey: parseKeyF, chargeInvDeduction: cidF, genId: genIdF, genMissionId: gmiF,
  makeShellKey: mskF, makeFuzeKey: mfkF, makeChargeKey: mckF,
  keyLabel: keyLabelF,
  ammoQtyBadge: badgeF, Modal: ModalF, PasswordGate: PasswordGateF,
} = window;

function emptyCombo() { return { id: genIdF(), shellKey: '', chargeKey: '', chargeSubOpt: '', fuzeKey: '', shellQty: '' }; }

function legacyCombos(ammoItems) {
  const shells = ammoItems.filter(i => parseKeyF(i.key)?.category === 'shell');
  const charges = ammoItems.filter(i => parseKeyF(i.key)?.category === 'charge');
  const fuzes = ammoItems.filter(i => parseKeyF(i.key)?.category === 'fuze');
  const count = Math.max(shells.length, charges.length, fuzes.length, 1);
  return Array.from({ length: count }, (_, i) => ({
    id: genIdF(),
    shellKey: shells[i]?.key || '', chargeKey: charges[i]?.key || '',
    chargeSubOpt: charges[i]?.subOpt || '', fuzeKey: fuzes[i]?.key || '',
    shellQty: String(shells[i]?.qty || charges[i]?.qty || fuzes[i]?.qty || ''),
  }));
}

function FireMissionModal({ state, dispatch, onClose, editRow }) {
  const isEdit = !!editRow;
  const today = new Date().toISOString().split('T')[0];
  const nowT = new Date().toTimeString().slice(0, 5);

  const CHECKLIST = [
    { id: 'c1', label: 'שם משימה ונ.צ' }, { id: 'c2', label: 'הזנת נתונים' }, { id: 'c3', label: 'מברק' },
    { id: 'c4', label: 'תיקון / נקייה' }, { id: 'c5', label: 'תחמושת' }, { id: 'c6', label: 'השוואת קו טווח' },
    { id: 'c7', label: 'זווית נפילה' }, { id: 'c8', label: "טמפ' מטען" }, { id: 'c9', label: 'בדיקה בלתי תלויה' },
  ];

  function newTab() {
    return {
      id: genIdF(), date: today, time: nowT, unit: '', target: '', selGuns: [], gunCombos: {}, notes: '',
      localGuns: JSON.parse(JSON.stringify(state.guns)),
      borrowSrc: '', borrowDst: '', borrowQtys: {}, checks: {}, firstFiredAt: null,
    };
  }

  const [tabs, setTabs] = useStateF(() => {
    if (isEdit) {
      const combos = editRow.combos?.length ? editRow.combos : legacyCombos(editRow.ammoItems || []);
      return [{
        id: genIdF(), date: editRow.date, time: editRow.time, unit: editRow.unit, target: editRow.target,
        selGuns: [editRow.gun], gunCombos: { [editRow.gun]: combos }, notes: editRow.notes || '',
        localGuns: JSON.parse(JSON.stringify(state.guns)),
        borrowSrc: '', borrowDst: '', borrowQtys: {}, checks: {}, firstFiredAt: null,
      }];
    }
    return [newTab()];
  });
  const [activeIdx, setActiveIdx] = useStateF(0);

  const updateTab = (idx, fn) => setTabs(prev => prev.map((t, i) => i === idx ? fn(t) : t));
  const updateActive = fn => updateTab(activeIdx, fn);
  const m = tabs[activeIdx] || tabs[0];

  const setDate = v => updateActive(t => ({ ...t, date: v }));
  const setTime = v => updateActive(t => ({ ...t, time: v }));
  const setUnit = v => updateActive(t => ({ ...t, unit: v }));
  const setTarget = v => updateActive(t => ({ ...t, target: v }));
  const setNotes = v => updateActive(t => ({ ...t, notes: v }));
  const toggleCheck = id => updateActive(t => ({ ...t, checks: { ...t.checks, [id]: !t.checks[id] } }));
  const checkAll = () => updateActive(t => ({ ...t, checks: Object.fromEntries(CHECKLIST.map(c => [c.id, true])) }));
  const clearAll = () => updateActive(t => ({ ...t, checks: {} }));
  const markFirstFired = () => updateActive(t => ({ ...t, time: new Date().toTimeString().slice(0, 5), firstFiredAt: new Date().toTimeString().slice(0, 5) }));

  const toggleGun = g => updateActive(t => {
    const selGuns = t.selGuns.includes(g) ? t.selGuns.filter(x => x !== g) : [...t.selGuns, g];
    const gunCombos = t.gunCombos[g] ? { ...t.gunCombos } : { ...t.gunCombos, [g]: [emptyCombo()] };
    return { ...t, selGuns, gunCombos };
  });
  const addCombo = g => updateActive(t => ({ ...t, gunCombos: { ...t.gunCombos, [g]: [...(t.gunCombos[g] || []), emptyCombo()] } }));
  const rmCombo = (g, id) => updateActive(t => ({ ...t, gunCombos: { ...t.gunCombos, [g]: (t.gunCombos[g] || []).filter(c => c.id !== id) } }));
  const setC = (g, id, field, val) => updateActive(t => {
    const combos = (t.gunCombos[g] || []).map(c => {
      if (c.id !== id) return c;
      const u = { ...c, [field]: val };
      if (field === 'chargeKey') u.chargeSubOpt = '';
      return u;
    });
    return { ...t, gunCombos: { ...t.gunCombos, [g]: combos } };
  });

  function comboChargeBeh(c) { const p = parseKeyF(c.chargeKey); if (!p || p.category !== 'charge') return null; return CB_F[p.chargeType] || null; }
  function comboChargeInvDed(c) {
    const qty = parseInt(c.shellQty) || 0;
    if (!qty || !c.chargeKey) return 0;
    const p = parseKeyF(c.chargeKey);
    if (!p || p.category !== 'charge') return qty;
    return cidF(p.chargeType, c.chargeSubOpt, qty);
  }
  function avail(mi, g, key, excludeId) {
    const base = mi.localGuns[g]?.[key] || 0;
    const used = (mi.gunCombos[g] || []).filter(c => c.id !== excludeId).reduce((s, c) => {
      const qty = parseInt(c.shellQty) || 0;
      if (!qty) return s;
      if (c.shellKey === key || c.fuzeKey === key) return s + qty;
      if (c.chargeKey === key) return s + comboChargeInvDed(c);
      return s;
    }, 0);
    return Math.max(0, base - used);
  }
  function comboMaxQty(mi, g, c) {
    if (!c.shellKey && !c.chargeKey && !c.fuzeKey) return 9999;
    const beh = comboChargeBeh(c);
    const shellAv = c.shellKey ? avail(mi, g, c.shellKey, c.id) : Infinity;
    const fuzeAv = c.fuzeKey ? avail(mi, g, c.fuzeKey, c.id) : Infinity;
    let chargeAv = c.chargeKey ? avail(mi, g, c.chargeKey, c.id) : Infinity;
    if (beh?.kind === 'modular' && c.chargeSubOpt === 'M231/2') chargeAv = Math.floor(chargeAv / 2);
    return Math.min(shellAv, fuzeAv, chargeAv);
  }
  function comboIsValid(mi, g, c) {
    const qty = parseInt(c.shellQty) || 0;
    if (!c.shellKey || !c.chargeKey || !c.fuzeKey || qty <= 0) return false;
    const beh = comboChargeBeh(c);
    if (beh && (beh.kind === 'separate' || beh.kind === 'modular') && !c.chargeSubOpt) return false;
    const shellOk = qty <= avail(mi, g, c.shellKey, c.id);
    const fuzeOk = qty <= avail(mi, g, c.fuzeKey, c.id);
    const ded = comboChargeInvDed(c);
    const chargeOk = ded <= avail(mi, g, c.chargeKey, c.id);
    return shellOk && fuzeOk && chargeOk;
  }
  const ammoValidForTab = mi => {
    if (!mi.unit || !mi.target || !mi.date || !mi.time || mi.selGuns.length === 0) return false;
    for (const g of mi.selGuns) {
      const combos = mi.gunCombos[g] || [];
      if (!combos.length) return false;
      if (combos.some(c => !comboIsValid(mi, g, c))) return false;
    }
    return true;
  };
  const checksComplete = mi => CHECKLIST.every(c => mi.checks[c.id]);
  const canSubmitTab = mi => ammoValidForTab(mi) && checksComplete(mi);

  const buildAmmoItems = (mi, g) => (mi.gunCombos[g] || []).flatMap(c => {
    const qty = parseInt(c.shellQty) || 0;
    if (!qty) return [];
    const items = [];
    if (c.shellKey) items.push({ key: c.shellKey, qty, subOpt: null, invDeduction: qty });
    if (c.fuzeKey) items.push({ key: c.fuzeKey, qty, subOpt: null, invDeduction: qty });
    if (c.chargeKey) items.push({ key: c.chargeKey, qty, subOpt: c.chargeSubOpt || null, invDeduction: comboChargeInvDed(c) });
    return items;
  });

  const submitEdit = () => {
    const mi = tabs[0];
    dispatch({ type: 'EDIT_MISSION_ROW', rowId: editRow.id, gun: editRow.gun,
      oldAmmoItems: editRow.ammoItems, newAmmoItems: buildAmmoItems(mi, editRow.gun),
      newCombos: mi.gunCombos[editRow.gun] || [], newNotes: mi.notes, newDate: mi.date, newTime: mi.time });
    onClose();
  };
  const submitTab = idx => {
    const mi = tabs[idx];
    const missionId = gmiF(mi.date, state.nextMissionSeq || 1);
    const entries = mi.selGuns.map(g => ({ gun: g, ammoItems: buildAmmoItems(mi, g), combos: mi.gunCombos[g] || [] }));
    dispatch({ type: 'FIRE_MISSION', entries, meta: { date: mi.date, time: mi.time, unit: mi.unit, target: mi.target, missionId, notes: mi.notes } });
    const nt = tabs.filter((_, j) => j !== idx);
    if (nt.length === 0) { onClose(); return; }
    setTabs(nt); setActiveIdx(Math.min(idx, nt.length - 1));
  };

  const borrowSrcAmmo = m.borrowSrc ? m.localGuns[m.borrowSrc] || {} : {};
  const borrowAvailRegs = state.registeredTypes.filter(r => (borrowSrcAmmo[r.key] || 0) > 0);
  const setBQ = (key, v) => updateActive(t => ({ ...t, borrowQtys: { ...t.borrowQtys, [key]: Math.max(0, Math.min(t.localGuns[t.borrowSrc]?.[key] || 0, parseInt(v) || 0)) } }));
  const setBorrowSrc = v => updateActive(t => ({ ...t, borrowSrc: v, borrowQtys: {} }));
  const setBorrowDst = v => updateActive(t => ({ ...t, borrowDst: v }));
  const applyBorrow = () => {
    if (!m.borrowSrc || !m.borrowDst || m.borrowSrc === m.borrowDst) return;
    const items = borrowAvailRegs.map(r => ({ key: r.key, qty: m.borrowQtys[r.key] || 0 })).filter(i => i.qty > 0);
    if (!items.length) return;
    updateActive(t => {
      const n = JSON.parse(JSON.stringify(t.localGuns));
      items.forEach(({ key, qty }) => { n[t.borrowSrc][key] = Math.max(0, (n[t.borrowSrc][key] || 0) - qty); n[t.borrowDst][key] = (n[t.borrowDst][key] || 0) + qty; });
      return { ...t, localGuns: n, borrowSrc: '', borrowDst: '', borrowQtys: {} };
    });
    dispatch({ type: 'TRANSFER_GUN_TO_GUN', srcGun: m.borrowSrc, dstGun: m.borrowDst, items });
  };

  const tabLabel = (t, i) => t.target ? t.target : `משימה ${i + 1}`;
  const addTab = () => { setTabs(p => [...p, newTab()]); setActiveIdx(tabs.length); };
  const closeTab = i => { const nt = tabs.filter((_, j) => j !== i); if (nt.length === 0) { onClose(); return; } setTabs(nt); setActiveIdx(Math.min(activeIdx, nt.length - 1)); };

  const allChecked = checksComplete(m);
  const ammoReady = ammoValidForTab(m);

  return (
    <ModalF title={isEdit ? 'עריכת משימת אש' : 'משימת אש חדשה'} icon="🎯" onClose={onClose} xl>
      {!isEdit && (
        <div className="row" style={{ gap: '.3rem', flexWrap: 'wrap', rowGap: '.35rem', marginBottom: '.85rem', background: 'var(--inset)', border: '1px solid var(--border)', borderRadius: 'var(--r1)', padding: '.45rem' }}>
          {tabs.map((t, i) => (
            <div key={t.id} className="row" style={{ marginInlineStart: '.3rem' }}>
              <button onClick={() => setActiveIdx(i)}
                style={{ padding: '.34rem .75rem', borderRadius: '7px 0 0 7px', fontSize: '.82rem', fontWeight: 700, cursor: 'pointer',
                  border: '1px solid ' + (i === activeIdx ? 'var(--accent)' : 'var(--border-2)'), borderRight: 'none',
                  background: i === activeIdx ? 'var(--accent-soft)' : 'transparent', color: i === activeIdx ? 'var(--text)' : 'var(--text-2)', whiteSpace: 'nowrap' }}>
                {canSubmitTab(t) && <span style={{ color: 'var(--ok)', marginInlineEnd: '.3rem', fontSize: '.65rem' }}>✓ </span>}
                {tabLabel(t, i)}
              </button>
              {tabs.length > 1 && (
                <button onClick={() => closeTab(i)} title="הסר משימה"
                  style={{ padding: '.34rem .45rem', borderRadius: '0 7px 7px 0', fontSize: '.72rem', fontWeight: 700, cursor: 'pointer',
                    border: '1px solid ' + (i === activeIdx ? 'var(--accent)' : 'var(--border-2)'), background: 'transparent', color: 'var(--danger)' }}>✕</button>
              )}
            </div>
          ))}
          <button onClick={addTab} style={{ marginInlineStart: 'auto', padding: '.34rem .85rem', borderRadius: '7px', fontSize: '.8rem', fontWeight: 700, border: '1px dashed var(--info)', background: 'transparent', color: 'var(--info)', cursor: 'pointer', whiteSpace: 'nowrap' }}>＋ משימה מקבילה חדשה</button>
          {tabs.length > 1 && <span className="dim u-tiny" style={{ display: 'flex', alignItems: 'center', padding: '0 .5rem' }}>{tabs.filter(canSubmitTab).length}/{tabs.length} מוכנות</span>}
        </div>
      )}

      {isEdit && (
        <div className="callout callout-info" style={{ marginBottom: '.65rem', display: 'flex', alignItems: 'center', gap: '.5rem' }}>
          <span className="u-bold" style={{ color: 'var(--info)' }}>⏱ עריכת בדיעבד:</span>
          שנה תאריך ושעה כדי לעדכן את מיקום הרשומה בציר הזמן. המיון מתבצע אוטומטית עם השמירה.
        </div>
      )}

      <div className="form-row" style={{ marginBottom: '.75rem' }}>
        <div className="form-group grow" style={{ minWidth: '130px' }}><label>תאריך</label><input type="date" value={m.date} onChange={e => setDate(e.target.value)} /></div>
        <div className="form-group" style={{ minWidth: '100px' }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: '.4rem' }}>שעה
            {!isEdit && m.firstFiredAt && <span className="chip" style={{ fontSize: '.6rem', padding: '.05rem .35rem', color: 'var(--info)' }}>🔒 ראשון נורה</span>}
            {isEdit && <span className="chip" style={{ fontSize: '.6rem', padding: '.05rem .35rem', color: 'var(--accent)' }}>✎ ניתן לעריכה</span>}
          </label>
          <input type="time" value={m.time} onChange={e => { if (!m.firstFiredAt || isEdit) setTime(e.target.value); }} readOnly={!!m.firstFiredAt && !isEdit}
            style={{ color: m.firstFiredAt && !isEdit ? 'var(--info)' : isEdit ? 'var(--ok)' : undefined, fontWeight: (m.firstFiredAt && !isEdit) || isEdit ? 700 : undefined }} />
        </div>
        {!isEdit && (
          <div className="form-group" style={{ minWidth: '120px', alignSelf: 'flex-end' }}>
            <button onClick={markFirstFired} disabled={!!m.firstFiredAt} title={m.firstFiredAt ? `נעול — ראשון נורה ${m.firstFiredAt}` : 'לחץ בעת ירי ראשון לנעילת השעה'}
              className="btn" style={{ width: '100%', fontWeight: 800, border: '1px solid var(--info)', background: m.firstFiredAt ? 'var(--info-soft)' : 'transparent', color: 'var(--info)', opacity: m.firstFiredAt ? .8 : 1 }}>
              {m.firstFiredAt ? `⏱ ${m.firstFiredAt}` : '⏱ ראשון נורה'}
            </button>
          </div>
        )}
        <div className="form-group grow" style={{ flex: 2, minWidth: '140px' }}><label>מסתייע</label><input type="text" placeholder="שם יחידה" value={m.unit} onChange={e => setUnit(e.target.value)} /></div>
        <div className="form-group grow" style={{ flex: 2, minWidth: '140px' }}><label>מטרה</label><input type="text" placeholder="תיאור מטרה" value={m.target} onChange={e => setTarget(e.target.value)} /></div>
      </div>

      {!isEdit && <>
        <div className="u-sm u-bold" style={{ color: 'var(--accent)', marginBottom: '.35rem' }}>בחר צוותים מתנערים:</div>
        <div className="row" style={{ flexWrap: 'wrap', gap: '.4rem', marginBottom: '.75rem' }}>
          {GUNS_F.map(g => <button key={g} className={'btn btn-sm ' + (m.selGuns.includes(g) ? 'btn-amber' : 'btn-gray')} onClick={() => toggleGun(g)}>צוות {g}</button>)}
        </div>
      </>}

      {state.registeredTypes.length > 0 && (
        <div className="panel" style={{ marginBottom: '.75rem', overflowX: 'auto' }}>
          <div className="u-tiny u-bold" style={{ padding: '.4rem .75rem', borderBottom: '1px solid var(--border)', color: 'var(--info)' }}>📋 מלאי צוותים — חי (מתעדכן בעת השאלה)</div>
          <table style={{ fontSize: '.7rem' }}>
            <thead><tr>
              <th className="u-right" style={{ minWidth: '145px' }}>תחמושת</th>
              {GUNS_F.map(g => <th key={g} style={{ color: m.selGuns.includes(g) ? 'var(--accent)' : 'var(--text-2)' }}>צוות {g}{m.selGuns.includes(g) ? ' ✓' : ''}</th>)}
            </tr></thead>
            <tbody>
              {[...state.registeredTypes.filter(r => r.category === 'shell'), ...state.registeredTypes.filter(r => r.category === 'charge'), ...state.registeredTypes.filter(r => r.category === 'fuze')].map(r => (
                <tr key={r.key}><td className="u-right muted">{r.label}</td>{GUNS_F.map(g => <td key={g}>{badgeF(m.localGuns[g]?.[r.key] || 0)}</td>)}</tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {m.selGuns.map(g => {
        const combos = m.gunCombos[g] || [];
        const gShells = state.registeredTypes.filter(r => r.category === 'shell' && (m.localGuns[g]?.[r.key] || 0) > 0);
        const gCharges = state.registeredTypes.filter(r => r.category === 'charge' && (m.localGuns[g]?.[r.key] || 0) > 0);
        const gFuzes = state.registeredTypes.filter(r => r.category === 'fuze' && (m.localGuns[g]?.[r.key] || 0) > 0);
        return (
          <div key={g} className="subpanel" style={{ marginBottom: '.75rem' }}>
            <div className="spread" style={{ marginBottom: '.6rem' }}>
              <span className="u-bold" style={{ color: 'var(--accent)' }}>צוות {g} — תצורות ירי</span>
              <button className="btn btn-green btn-sm" onClick={() => addCombo(g)}>＋ תצורה נוספת</button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr auto 1fr 80px 32px', gap: '.35rem', marginBottom: '.3rem' }}>
              {['פגז', 'חנ"ה', 'מטען', 'מרעום', 'כמות', ''].map((h, i) => <div key={i} className="u-tiny u-bold u-center dim">{h}</div>)}
            </div>
            {combos.map(c => {
              const qty = parseInt(c.shellQty) || 0;
              const beh = comboChargeBeh(c);
              const needSub = beh && (beh.kind === 'separate' || beh.kind === 'modular');
              const ded = comboChargeInvDed(c);
              const maxQ = comboMaxQty(m, g, c);
              const shellAv = c.shellKey ? avail(m, g, c.shellKey, c.id) : 0;
              const fuzeAv = c.fuzeKey ? avail(m, g, c.fuzeKey, c.id) : 0;
              const chargeAv = c.chargeKey ? avail(m, g, c.chargeKey, c.id) : 0;
              const shellOk = !c.shellKey || qty <= shellAv;
              const fuzeOk = !c.fuzeKey || qty <= fuzeAv;
              const chargeOk = !c.chargeKey || ded <= chargeAv;
              const allOk = shellOk && fuzeOk && chargeOk;
              const isValid = comboIsValid(m, g, c);
              return (
                <div key={c.id} style={{ background: 'var(--inset)', border: `1px solid ${isValid || allOk ? 'var(--border)' : 'var(--danger-line)'}`, borderRadius: 'var(--r1)', padding: '.4rem .5rem', marginBottom: '.5rem' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr auto 1fr 80px 32px', gap: '.35rem', alignItems: 'center' }}>
                    <select value={c.shellKey} onChange={e => setC(g, c.id, 'shellKey', e.target.value)} style={{ fontSize: '.78rem' }}>
                      <option value="">— פגז —</option>{gShells.map(r => <option key={r.key} value={r.key}>{r.label} ({m.localGuns[g]?.[r.key] || 0})</option>)}
                    </select>
                    <select value={c.chargeKey} onChange={e => setC(g, c.id, 'chargeKey', e.target.value)} style={{ fontSize: '.78rem' }}>
                      <option value="">— חנ"ה —</option>{gCharges.map(r => <option key={r.key} value={r.key}>{r.label} ({m.localGuns[g]?.[r.key] || 0} {r.unit})</option>)}
                    </select>
                    <div style={{ minWidth: '88px' }}>
                      {needSub ? (
                        <select value={c.chargeSubOpt} onChange={e => setC(g, c.id, 'chargeSubOpt', e.target.value)} style={{ fontSize: '.78rem' }}>
                          <option value="">— מטען —</option>{(beh.subOpts || []).map(o => <option key={o} value={o}>{o}</option>)}
                        </select>
                      ) : <div className="u-center faint u-tiny">—</div>}
                    </div>
                    <select value={c.fuzeKey} onChange={e => setC(g, c.id, 'fuzeKey', e.target.value)} style={{ fontSize: '.78rem' }}>
                      <option value="">— מרעום —</option>{gFuzes.map(r => <option key={r.key} value={r.key}>{r.label} ({m.localGuns[g]?.[r.key] || 0})</option>)}
                    </select>
                    <input type="number" min="1" max={maxQ || 9999} value={c.shellQty} placeholder="כמות" onChange={e => setC(g, c.id, 'shellQty', e.target.value)} style={{ textAlign: 'center' }} disabled={needSub && !c.chargeSubOpt} />
                    {combos.length > 1 ? <button className="btn btn-red btn-sm" style={{ padding: '.25rem .4rem' }} onClick={() => rmCombo(g, c.id)}>✕</button> : <div />}
                  </div>
                  {qty > 0 && c.shellKey && c.chargeKey && c.fuzeKey && (
                    <div className="row" style={{ gap: '.9rem', flexWrap: 'wrap', marginTop: '.3rem', fontSize: '.68rem' }}>
                      <span style={{ color: shellOk ? 'var(--ok)' : 'var(--danger)' }}>🔵 פגז ×{qty} (זמין:{shellAv})</span>
                      <span style={{ color: fuzeOk ? 'var(--ok)' : 'var(--danger)' }}>🟡 מרעום ×{qty} (זמין:{fuzeAv})</span>
                      <span style={{ color: chargeOk ? 'var(--ok)' : 'var(--danger)' }}>⚡ חנ"ה {beh?.kind === 'modular' ? `${ded} מודולים (${c.chargeSubOpt || '?'} × ${qty})` : `×${ded}`} (זמין:{chargeAv})</span>
                    </div>
                  )}
                  {qty > 0 && (!allOk || (!isValid && (c.shellKey || c.chargeKey || c.fuzeKey))) && (
                    <div className="u-tiny" style={{ color: 'var(--danger)', marginTop: '.2rem' }}>
                      ⚠{!shellOk ? ` פגז חסר ${qty - shellAv}` : ''}{!fuzeOk ? ` | מרעום חסר ${qty - fuzeAv}` : ''}{!chargeOk ? ` | חנ"ה חסר ${ded - chargeAv}` : ''}{needSub && !c.chargeSubOpt ? ' | נדרש לבחור אזור חנ"ה' : ''}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        );
      })}

      {!isEdit && m.selGuns.length > 0 && (
        <div className="subpanel" style={{ marginBottom: '.75rem', borderColor: 'var(--accent-line)' }}>
          <div className="u-bold u-sm" style={{ color: 'var(--accent)', marginBottom: '.5rem' }}>↕ משוך חוסר מצוות אחר (השאלה)</div>
          <div className="form-row" style={{ marginBottom: '.5rem' }}>
            <div className="form-group grow"><label>צוות נותן</label>
              <select value={m.borrowSrc} onChange={e => setBorrowSrc(e.target.value)}><option value="">בחר</option>{GUNS_F.map(g => <option key={g} value={g}>צוות {g}</option>)}</select>
            </div>
            <div className="form-group grow"><label>צוות מקבל</label>
              <select value={m.borrowDst} onChange={e => setBorrowDst(e.target.value)}><option value="">בחר</option>{m.selGuns.filter(g => g !== m.borrowSrc).map(g => <option key={g} value={g}>צוות {g}</option>)}</select>
            </div>
          </div>
          {m.borrowSrc && borrowAvailRegs.length > 0 && (
            <div style={{ maxHeight: '150px', overflowY: 'auto', marginBottom: '.4rem' }}>
              {borrowAvailRegs.map(r => (
                <div key={r.key} className="row" style={{ gap: '.4rem', marginBottom: '.3rem' }}>
                  <span className="grow u-sm">{r.label}</span>
                  <span className="dim u-tiny" style={{ width: '75px', textAlign: 'center' }}>זמין: {borrowSrcAmmo[r.key]}</span>
                  <input type="number" min="0" max={borrowSrcAmmo[r.key]} value={m.borrowQtys[r.key] || 0} onChange={e => setBQ(r.key, e.target.value)} style={{ width: '60px', textAlign: 'center' }} />
                </div>
              ))}
            </div>
          )}
          <button className="btn btn-purple btn-sm" disabled={!m.borrowSrc || !m.borrowDst || !borrowAvailRegs.some(r => (m.borrowQtys[r.key] || 0) > 0)} onClick={applyBorrow}>↗ בצע השאלה</button>
          <span className="dim u-tiny" style={{ marginInlineStart: '.5rem' }}>מעדכן מלאי ורושם בהיסטוריה מיד</span>
        </div>
      )}

      <div className="form-group" style={{ marginBottom: '.75rem' }}>
        <label>הערות (אופציונלי)</label>
        <textarea rows={2} placeholder="הגדרות מיוחדות, הערות מבצעיות..." value={m.notes} onChange={e => setNotes(e.target.value)} style={{ resize: 'vertical', minHeight: '56px' }} />
      </div>

      {!isEdit && (
        <div className="panel" style={{ padding: '.85rem 1rem', marginBottom: '1rem', border: `2px solid ${allChecked ? 'var(--ok-line)' : 'var(--warn-line)'}` }}>
          <div className="row" style={{ gap: '.6rem', marginBottom: '.65rem', flexWrap: 'wrap' }}>
            <span>📋</span>
            <span className="u-bold" style={{ color: allChecked ? 'var(--ok)' : 'var(--warn)' }}>בדיקות הכרחיות במהלך האש</span>
            <span className="chip" style={{ background: allChecked ? 'var(--ok-soft)' : 'var(--warn-soft)', color: allChecked ? 'var(--ok)' : 'var(--warn)' }}>{CHECKLIST.filter(c => m.checks[c.id]).length} / {CHECKLIST.length}</span>
            <div className="row" style={{ marginInlineStart: 'auto', gap: '.35rem' }}>
              <button className="btn btn-green btn-sm" onClick={checkAll} disabled={allChecked}>✔ סמן הכל</button>
              <button className="btn btn-red btn-sm" onClick={clearAll} disabled={!CHECKLIST.some(c => m.checks[c.id])}>✕ הסר הכל</button>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: '.4rem .75rem' }}>
            {CHECKLIST.map((item, ci) => {
              const checked = !!m.checks[item.id];
              return (
                <label key={item.id} className="row" style={{ gap: '.55rem', padding: '.4rem .65rem', borderRadius: 'var(--r1)', background: checked ? 'var(--ok-soft)' : 'var(--inset)', border: `1px solid ${checked ? 'var(--ok-line)' : 'var(--border)'}`, cursor: 'pointer' }}>
                  <input type="checkbox" checked={checked} onChange={() => toggleCheck(item.id)} style={{ width: '16px', height: '16px', flexShrink: 0 }} />
                  <span className="u-sm" style={{ fontWeight: checked ? 700 : 400, color: checked ? 'var(--ok)' : 'var(--text)' }}>{ci + 1}. {item.label}</span>
                </label>
              );
            })}
          </div>
          {!allChecked && ammoReady && <div className="u-tiny u-center u-bold" style={{ marginTop: '.6rem', color: 'var(--warn)' }}>⚠ יש לסמן את כל 9 הבדיקות לפני השיגור</div>}
        </div>
      )}

      <div className="row" style={{ gap: '.75rem', justifyContent: 'flex-end', marginTop: '.25rem' }}>
        <button className="btn btn-gray" onClick={onClose}>ביטול</button>
        {isEdit ? (
          <button className="btn btn-red" disabled={!ammoValidForTab(tabs[0])} onClick={submitEdit}>💾 שמור עריכה</button>
        ) : (
          <button className="btn btn-red" disabled={!canSubmitTab(m)} onClick={() => submitTab(activeIdx)} title={!ammoReady ? 'השלם פרטי משימה ותחמושת' : !allChecked ? 'סמן את כל הבדיקות' : ''} style={{ minWidth: '165px' }}>
            🎯 אחרון נורה / סיום משימה{m.target ? ` — ${m.target}` : ''}
          </button>
        )}
      </div>
    </ModalF>
  );
}

// ── Edit gun stock ───────────────────────────────────────────
const CUSTOM_SENTINEL = '__OTHER__';
const CAT_OPTIONS = [{ value: 'shell', label: 'פגז', unit: 'יח"' }, { value: 'charge', label: 'חנ"ה', unit: 'מטען' }, { value: 'fuze', label: 'מרעום', unit: 'יח"' }];

function EditGunStockModal({ state, dispatch, onClose }) {
  const regs = state.registeredTypes;
  const [showAuth, setShowAuth] = useStateF(!!(window.APP_CONFIG?.requireEditAuth ?? true));
  const [gun, setGun] = useStateF('');
  const [rows, setRows] = useStateF([]);

  const loadGun = g => {
    setGun(g);
    if (!g) { setRows([]); return; }
    const inv = state.guns[g] || {};
    // Include all keys that have qty > 0, even if not in regs catalog
    const invKeys = Object.entries(inv).filter(([, v]) => v > 0);
    setRows(invKeys.map(([key, qty]) => {
      const reg = regs.find(r => r.key === key);
      return { id: genIdF(), key, qty: String(qty), isNew: false, isCustom: false,
        customLabel: '', customCat: 'shell', customSubType: '', customSeries: '',
        _fallbackLabel: reg?.label || keyLabelF(key) };
    }));
  };
  const usedKeys = new Set(rows.filter(r => r.key && r.key !== CUSTOM_SENTINEL).map(r => r.key));
  const availableToAdd = regs.filter(r => !usedKeys.has(r.key));
  const updateQty = (id, v) => setRows(p => p.map(r => r.id === id ? { ...r, qty: v } : r));
  const removeRow = id => setRows(p => p.filter(r => r.id !== id));
  const addRow = () => setRows(p => [...p, { id: genIdF(), key: '', qty: '', isNew: true, isCustom: false, customLabel: '', customCat: 'shell', customSubType: '', customSeries: '' }]);
  const setCustomLabel = (id, v) => setRows(p => p.map(r => r.id === id ? { ...r, customLabel: v } : r));
  const setCustomCat = (id, v) => setRows(p => p.map(r => r.id === id ? { ...r, customCat: v, customSubType: '', customSeries: '' } : r));
  const setCustomSubType = (id, v) => setRows(p => p.map(r => r.id === id ? { ...r, customSubType: v } : r));
  const setCustomSeries = (id, v) => setRows(p => p.map(r => r.id === id ? { ...r, customSeries: v } : r));
  const setNewKey = (id, k) => {
    if (k === CUSTOM_SENTINEL) setRows(p => p.map(r => r.id === id ? { ...r, key: CUSTOM_SENTINEL, isCustom: true, customLabel: '', customCat: 'shell', customSubType: '', customSeries: '' } : r));
    else setRows(p => p.map(r => r.id === id ? { ...r, key: k, isCustom: false, customLabel: '', customCat: 'shell', customSubType: '', customSeries: '' } : r));
  };
  const rowIsValid = r => {
    if (!r.isNew) return r.key && parseInt(r.qty) >= 0;
    if (r.isCustom) {
      const q = parseInt(r.qty);
      if (!r.customCat || !q) return false;
      if (r.customCat === 'charge') return !!r.customSubType && !!r.customSeries.trim();
      return !!r.customLabel.trim();
    }
    return r.key && r.key !== CUSTOM_SENTINEL && parseInt(r.qty) >= 0;
  };
  const canSubmit = gun && rows.length > 0 && rows.every(rowIsValid);

  const handleSubmit = () => {
    const ammo = {}, newTypes = [];
    rows.forEach(r => {
      const q = parseInt(r.qty) || 0;
      if (!q) return;
      if (r.isCustom) {
        const cat = r.customCat || 'shell';
        let key, displayLabel, unit;
        if (cat === 'charge') {
          const cType = r.customSubType; const series = r.customSeries.trim();
          if (!cType || !series) return;
          key = mckF(cType, series); displayLabel = `${cType} סדרה ${series}`; unit = CB_F[cType]?.unit || 'מטען';
        } else if (cat === 'fuze') { const label = r.customLabel.trim(); if (!label) return; key = mfkF(label); displayLabel = label; unit = 'יח"'; }
        else { const label = r.customLabel.trim(); if (!label) return; key = mskF(label); displayLabel = label; unit = 'יח"'; }
        ammo[key] = q;
        if (!regs.find(x => x.key === key)) newTypes.push({ key, label: displayLabel, category: cat, unit, chargeType: cat === 'charge' ? r.customSubType : null, series: cat === 'charge' ? r.customSeries.trim() : null });
      } else if (r.key && r.key !== CUSTOM_SENTINEL) ammo[r.key] = q;
    });
    dispatch({ type: 'EDIT_GUN_STOCK', gun, ammo, newTypes });
    onClose();
  };

  if (showAuth) return <PasswordGateF onSuccess={() => setShowAuth(false)} onCancel={onClose} />;

  // Stepper helpers — increment/decrement without losing focus
  const stepQty = (id, delta) => setRows(p => p.map(r => {
    if (r.id !== id) return r;
    const current = parseInt(r.qty) || 0;
    const next = Math.max(0, current + delta);
    return { ...r, qty: String(next) };
  }));

  return (
    <ModalF title="עריכת ערום קרקע" icon="📦" onClose={onClose} xl>
      <div className="form-group" style={{ marginBottom: '1rem' }}>
        <label>בחר צוות לעריכה</label>
        <select value={gun} onChange={e => loadGun(e.target.value)} style={{ fontWeight: 700 }}>
          <option value="">— בחר צוות —</option>{GUNS_F.map(g => <option key={g} value={g}>צוות {g}</option>)}
        </select>
      </div>
      {gun && (
        <>
          <div className="panel" style={{ marginBottom: '.75rem', overflow: 'hidden' }}>
            <div className="u-tiny u-bold" style={{ padding: '.4rem .75rem', borderBottom: '1px solid var(--border)', color: 'var(--info)' }}>📦 ערום צוות {gun} — ערוך כמויות</div>
            {rows.length === 0 && <div className="empty u-sm">אין פריטים — הוסף בעזרת הכפתור למטה</div>}
            {rows.map(r => {
              const reg = regs.find(x => x.key === r.key);
              return (
                <div key={r.id} style={{ borderBottom: '1px solid var(--border-soft)' }}>
                  {!r.isNew && (
                    <div className="row" style={{ gap: '.5rem', padding: '.5rem .75rem', alignItems: 'center' }}>
                      {/* Label — grows to fill space */}
                      <span className="grow u-sm u-bold" style={{ minWidth: 0 }}>{r._fallbackLabel || regs.find(x => x.key === r.key)?.label || keyLabelF(r.key) || r.key}</span>
                      <span className="dim u-tiny" style={{ minWidth: '36px', textAlign: 'center' }}>{regs.find(x => x.key === r.key)?.unit || ''}</span>
                      {/* Stepper: − input + */}
                      <div className="row" style={{ gap: 0, border: '1px solid var(--border-2)', borderRadius: 'var(--r1)', overflow: 'hidden', flexShrink: 0 }}>
                        <button tabIndex={-1} onClick={() => stepQty(r.id, -1)}
                          style={{ padding: '.35rem .55rem', background: 'var(--surface-2)', border: 'none', cursor: 'pointer', fontSize: '1rem', color: 'var(--text-2)', lineHeight: 1 }}>−</button>
                        <input type="number" min="0" value={r.qty}
                          onChange={e => updateQty(r.id, e.target.value)}
                          onFocus={e => e.target.select()}
                          style={{ width: '72px', textAlign: 'center', fontWeight: 800, fontSize: '.95rem',
                            border: 'none', borderLeft: '1px solid var(--border-2)', borderRight: '1px solid var(--border-2)',
                            borderRadius: 0, background: 'var(--inset)' }} />
                        <button tabIndex={-1} onClick={() => stepQty(r.id, 1)}
                          style={{ padding: '.35rem .55rem', background: 'var(--surface-2)', border: 'none', cursor: 'pointer', fontSize: '1rem', color: 'var(--text-2)', lineHeight: 1 }}>＋</button>
                      </div>
                      <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)', padding: '.2rem .4rem', flexShrink: 0 }} onClick={() => removeRow(r.id)}>✕</button>
                    </div>
                  )}
                  {r.isNew && !r.isCustom && (
                    <div className="row" style={{ gap: '.5rem', padding: '.5rem .75rem', alignItems: 'center' }}>
                      <select value={r.key} onChange={e => setNewKey(r.id, e.target.value)} className="grow" style={{ fontSize: '.8rem' }}>
                        <option value="">— בחר סוג תחמושת —</option>
                        {regs.filter(x => !usedKeys.has(x.key) || x.key === r.key).map(x => (
                          <option key={x.key} value={x.key}>{x.label}</option>
                        ))}
                        <option value={CUSTOM_SENTINEL}>✏ אחר (הזנה חופשית)</option>
                      </select>
                      <span className="dim u-tiny" style={{ minWidth: '36px', textAlign: 'center' }}>
                        {r.key && r.key !== CUSTOM_SENTINEL ? (regs.find(x => x.key === r.key)?.unit || '') : '—'}
                      </span>
                      <div className="row" style={{ gap: 0, border: '1px solid var(--border-2)', borderRadius: 'var(--r1)', overflow: 'hidden', flexShrink: 0 }}>
                        <button tabIndex={-1} onClick={() => stepQty(r.id, -1)}
                          style={{ padding: '.35rem .55rem', background: 'var(--surface-2)', border: 'none', cursor: 'pointer', fontSize: '1rem', color: 'var(--text-2)', lineHeight: 1 }}>−</button>
                        <input type="number" min="0" value={r.qty}
                          onChange={e => updateQty(r.id, e.target.value)}
                          onFocus={e => e.target.select()}
                          placeholder="0"
                          style={{ width: '72px', textAlign: 'center', fontWeight: 800, fontSize: '.95rem',
                            border: 'none', borderLeft: '1px solid var(--border-2)', borderRight: '1px solid var(--border-2)',
                            borderRadius: 0, background: 'var(--inset)', opacity: !r.key ? .4 : 1 }} />
                        <button tabIndex={-1} onClick={() => stepQty(r.id, 1)}
                          style={{ padding: '.35rem .55rem', background: 'var(--surface-2)', border: 'none', cursor: 'pointer', fontSize: '1rem', color: 'var(--text-2)', lineHeight: 1 }}>＋</button>
                      </div>
                      <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)', padding: '.2rem .4rem', flexShrink: 0 }} onClick={() => removeRow(r.id)}>✕</button>
                    </div>
                  )}
                  {r.isNew && r.isCustom && (
                    <div style={{ padding: '.6rem .75rem', background: 'var(--surface-3)', borderInlineEnd: '3px solid var(--info)' }}>
                      <div style={{ display: 'grid', gridTemplateColumns: r.customCat === 'charge' ? '120px 1fr 100px 140px 32px' : '120px 1fr 140px 32px', gap: '.5rem', alignItems: 'end' }}>
                        <div><div className="u-tiny u-bold u-center dim" style={{ marginBottom: '.2rem' }}>קטגוריה</div>
                          <select value={r.customCat || 'shell'} onChange={e => setCustomCat(r.id, e.target.value)} style={{ fontSize: '.78rem' }}>{CAT_OPTIONS.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}</select>
                        </div>
                        <div><div className="u-tiny u-bold u-center dim" style={{ marginBottom: '.2rem' }}>{r.customCat === 'charge' ? 'סוג חנ"ה' : 'שם פריט'}</div>
                          {r.customCat === 'charge' ? (
                            <select value={r.customSubType || ''} onChange={e => setCustomSubType(r.id, e.target.value)} style={{ fontSize: '.78rem' }}><option value="">— סוג חנ"ה —</option>{CTN_F.map(ct => <option key={ct} value={ct}>{ct}</option>)}</select>
                          ) : (
                            <input type="text" placeholder={r.customCat === 'fuze' ? 'שם מרעום...' : 'שם פגז...'} value={r.customLabel} onChange={e => setCustomLabel(r.id, e.target.value)} style={{ fontSize: '.8rem' }} />
                          )}
                        </div>
                        {r.customCat === 'charge' && (
                          <div><div className="u-tiny u-bold u-center dim" style={{ marginBottom: '.2rem' }}>סדרה</div>
                            <input type="text" placeholder="למשל 02-26" value={r.customSeries || ''} onChange={e => setCustomSeries(r.id, e.target.value)} style={{ fontSize: '.8rem', textAlign: 'center' }} />
                          </div>
                        )}
                        <div><div className="u-tiny u-bold u-center dim" style={{ marginBottom: '.2rem' }}>כמות</div>
                          <div className="row" style={{ gap: 0, border: '1px solid var(--border-2)', borderRadius: 'var(--r1)', overflow: 'hidden' }}>
                            <button tabIndex={-1} onClick={() => stepQty(r.id, -1)}
                              style={{ padding: '.3rem .45rem', background: 'var(--surface-2)', border: 'none', cursor: 'pointer', fontSize: '.9rem', color: 'var(--text-2)', lineHeight: 1 }}>−</button>
                            <input type="number" min="1" value={r.qty} onChange={e => updateQty(r.id, e.target.value)}
                              onFocus={e => e.target.select()}
                              placeholder="0" style={{ width: '60px', textAlign: 'center', fontWeight: 800,
                                border: 'none', borderLeft: '1px solid var(--border-2)', borderRight: '1px solid var(--border-2)',
                                borderRadius: 0, background: 'var(--inset)' }} />
                            <button tabIndex={-1} onClick={() => stepQty(r.id, 1)}
                              style={{ padding: '.3rem .45rem', background: 'var(--surface-2)', border: 'none', cursor: 'pointer', fontSize: '.9rem', color: 'var(--text-2)', lineHeight: 1 }}>＋</button>
                          </div>
                        </div>
                        <div style={{ paddingBottom: '.05rem' }}><button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)', padding: '.28rem .4rem', width: '100%' }} onClick={() => removeRow(r.id)}>✕</button></div>
                      </div>
                      {(r.customCat === 'charge' ? r.customSubType && r.customSeries : r.customLabel) && (
                        <div className="u-tiny" style={{ color: 'var(--info)', marginTop: '.2rem' }}>🔖 שם סופי: {r.customCat === 'charge' ? `${r.customSubType} סדרה ${r.customSeries}` : r.customLabel}</div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
          <button className="btn btn-outline btn-sm" style={{ marginBottom: '.75rem' }} onClick={addRow}>＋ הוסף סוג תחמושת לערום</button>
          <div className="callout callout-warn" style={{ marginBottom: '.75rem' }}>⚠ פעולה זו תדרוס את כמויות הערום לצוות {gun}. פינת פסולים לא תושפע.</div>
        </>
      )}
      <div className="row" style={{ gap: '.75rem', justifyContent: 'flex-end' }}>
        <button className="btn btn-gray" onClick={onClose}>ביטול</button>
        <button className="btn btn-red" disabled={!canSubmit} onClick={handleSubmit}>✔ אשר עדכון ערום לצוות {gun || '...'}</button>
      </div>
    </ModalF>
  );
}

window.FireMissionModal = FireMissionModal;
window.EditGunStockModal = EditGunStockModal;
})();
