/* ═══════════════════════════════════════════════════════════
   Views — Teams (inventory matrix), Bunker, Settings (catalog)

   FIXES:
   - Catalog delete now works even when ammo is in use:
     shows confirmation modal, removes from all guns + bunker
   - Rename/remap: merge one ammo type into another (fixes
     name mismatches after import)
   - Reset single gun: zero out all ammo for one gun
   - Delete buttons always clickable (no longer disabled when inUse)
═══════════════════════════════════════════════════════════ */
(function () {
const { useState: useStateV } = React;
const {
  GUNS: GUNS_V, CHARGE_BEHAVIORS: CB_V, CHARGE_TYPE_NAMES: CTN_V,
  parseKey: parseKeyV, keyLabel: keyLabelV, ammoQtyBadge: badgeV,
  totalAmmo: totalAmmoV, totalAmmoGuns: totalAmmoGunsV, totalAmmoBunker: totalAmmoBunkerV,
  calcGroupTotal: calcGroupTotalV,
  makeShellKey: mskV, makeFuzeKey: mfkV, makeChargeKey: mckV, makeTypeRecord: mtrV,
  genId: genIdV, Modal: ModalV,
} = window;

// go/GoGitMerge icon
function MergeIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
      <path d="M5 3.254V3.25v.005a.75.75 0 1 1 0-.005v.004zm.45 1.9a2.25 2.25 0 1 0-1.95.218v5.256a2.25 2.25 0 1 0 1.5 0V7.123A4.25 4.25 0 0 0 8.322 10.8l.117.005A2.25 2.25 0 1 0 10.5 8.972V7.808a4.25 4.25 0 0 0-3.05-4.083l-.001-.001zM9.25 9a.75.75 0 1 1 0 1.5A.75.75 0 0 1 9.25 9zM5 11.75a.75.75 0 1 1 0 1.5.75.75 0 0 1 0-1.5z"/>
    </svg>
  );
}

const CAT_META = {
  shell:  { label: 'פגזים',  one: 'פגז',   icon: '🎯', unit: 'פגזים' },
  charge: { label: 'חנ"ה',   one: 'חנ"ה',  icon: '⚡', unit: 'יחידות' },
  fuze:   { label: 'מרעומים', one: 'מרעום', icon: '🟡', unit: 'מרעומים' },
};
const CAT_ORDER = ['shell', 'charge', 'fuze'];

function readinessTier(state, g) {
  if (state.readiness?.red === g)    return { cls: 'dot-danger', label: 'כוננות צוות אדום' };
  if (state.readiness?.yellow === g) return { cls: 'dot-warn',   label: 'כוננות צוות צהוב' };
  return { cls: 'dot-ok', label: 'כוננות צוות ירוק' };
}

// ── Teams / inventory matrix ─────────────────────────────────
function TeamsView({ state, dispatch }) {
  const regs = state.registeredTypes;
  const totals    = totalAmmoV(state);       // all (guns + bunker)
  const totalsGun = totalAmmoGunsV(state);   // on-ground only
  const totalsRamsav = totalAmmoBunkerV(state); // רמסע/bunker only
  const setRedLine = (key, v) => dispatch({ type: 'SET_RED_LINE', key, value: Math.max(0, parseInt(v) || 0) });
  const setReadiness = (level, gun) => dispatch({ type: 'SET_READINESS', level, gun });

  const [filter, setFilter] = useStateV('all');
  const [resetGun, setResetGun] = useStateV(null);
  const doResetGun = () => {
    if (!resetGun) return;
    dispatch({ type: 'RESET_GUN_INVENTORY', gun: resetGun });
    setResetGun(null);
  };

  // ── Single gun card view ──────────────────────────────────
  function GunDetailView({ gun }) {
    const inv = state.guns[gun] || {};
    const tier = readinessTier(state, gun);
    return (
      <div className="view-stack">
        <div className="card card-pad">
          <div className="spread" style={{ flexWrap: 'wrap', gap: '.6rem' }}>
            <div className="row" style={{ gap: '.75rem', alignItems: 'center' }}>
              <span style={{ fontSize: '1.6rem', fontWeight: 800, fontFamily: 'var(--font-mono)', color: 'var(--accent)' }}>צוות {gun}</span>
              <span className={'chip chip-' + tier.cls} style={{ fontSize: '.85rem', padding: '.3rem .7rem' }}>
                <span className={'dot ' + tier.cls} style={{ marginInlineEnd: '.35rem' }} />{tier.label}
              </span>
            </div>
            <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)' }} onClick={() => setResetGun(gun)}>↺ אפס מלאי</button>
          </div>
        </div>

        {CAT_ORDER.map(cat => {
          const rows = regs.filter(r => r.category === cat);
          if (!rows.length) return null;
          return (
            <div key={cat} className="section-card">
              <div className="section-header">
                <span className="section-title">{CAT_META[cat].icon} {CAT_META[cat].label}</span>
              </div>
              <div className="card-pad">
                <table style={{ width: '100%' }}>
                  <thead>
                    <tr>
                      <th className="u-right">סוג תחמושת</th>
                      <th style={{ width: '90px', textAlign: 'center' }}>ערום קרקע</th>
                      <th style={{ width: '90px', textAlign: 'center' }}>קו אדום</th>
                      <th style={{ width: '90px', textAlign: 'center' }}>סה"כ קרקע</th>
                      <th style={{ width: '90px', textAlign: 'center' }}>רמסע</th>
                      <th style={{ width: '90px', textAlign: 'center' }}>סה"כ כולל</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map(r => {
                      const qty     = inv[r.key] || 0;
                      const allGuns = totalsGun[r.key] || 0;
                      const ramsav  = totalsRamsav[r.key] || 0;
                      const total   = allGuns + ramsav;
                      const rl      = state.redLines?.[r.key] || 0;
                      const crit    = rl > 0 && qty < rl;
                      return (
                        <tr key={r.key} style={crit ? { background: 'var(--danger-soft)' } : undefined}>
                          <td className="u-right u-bold">
                            {r.label} {crit && <span style={{ color: 'var(--danger)' }}>⚠</span>}
                          </td>
                          <td style={{ textAlign: 'center' }}><span style={{ fontSize: '1.1rem' }}>{badgeV(qty)}</span></td>
                          <td style={{ textAlign: 'center' }}>
                            <input type="number" min="0" value={rl || ''} placeholder="—"
                              onChange={e => setRedLine(r.key, e.target.value)}
                              style={{ width: '70px', textAlign: 'center' }} />
                          </td>
                          <td style={{ textAlign: 'center' }}><span className="mono u-bold dim">{allGuns}</span></td>
                          <td style={{ textAlign: 'center' }}><span className="mono" style={{ color: 'var(--info)' }}>{ramsav}</span></td>
                          <td style={{ textAlign: 'center' }}><span className="mono u-bold">{total}</span></td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  // ── Full matrix: guns as rows, ammo as columns ────────────
  function AllGunsMatrix() {
    return (
      <div className="view-stack">
        {CAT_ORDER.map(cat => {
          const cols = regs.filter(r => r.category === cat);
          if (!cols.length) return null;
          return (
            <div key={cat} className="section-card">
              <div className="section-header">
                <span className="section-title">{CAT_META[cat].icon} {CAT_META[cat].label}</span>
                <span className="dim u-tiny">{cols.length} סוגים</span>
              </div>
              <div style={{ overflowX: 'auto' }}>
                <table style={{ fontSize: '.82rem', minWidth: '100%' }}>
                  <thead>
                    <tr>
                      <th className="u-right" style={{ minWidth: '90px', position: 'sticky', right: 0, background: 'var(--surface-2)', zIndex: 1 }}>צוות</th>
                      {cols.map(r => {
                        const rl = state.redLines?.[r.key] || 0;
                        const crit = rl > 0 && (totalsGun[r.key] || 0) < rl;
                        return (
                          <th key={r.key} style={{ textAlign: 'center', minWidth: '80px', color: crit ? 'var(--danger)' : undefined }}>
                            {r.label}{crit ? ' ⚠' : ''}
                          </th>
                        );
                      })}
                      <th style={{ textAlign: 'center', minWidth: '60px', color: 'var(--text-3)' }}>סה"כ</th>
                    </tr>
                  </thead>
                  <tbody>
                    {GUNS_V.map(g => {
                      const inv = state.guns[g] || {};
                      const tier = readinessTier(state, g);
                      const gunTotal = cols.reduce((s, r) => s + (inv[r.key] || 0), 0);
                      return (
                        <tr key={g}>
                          <td style={{ position: 'sticky', right: 0, background: 'var(--surface)', zIndex: 1, fontWeight: 700 }}>
                            <div className="row" style={{ gap: '.35rem', alignItems: 'center' }}>
                              <span className={'dot ' + tier.cls} />{g}
                            </div>
                          </td>
                          {cols.map(r => {
                            const qty = inv[r.key] || 0;
                            const rl = state.redLines?.[r.key] || 0;
                            const crit = rl > 0 && qty < rl;
                            return (
                              <td key={r.key} style={{ textAlign: 'center', background: crit ? 'var(--danger-soft)' : undefined }}>
                                {badgeV(qty)}
                              </td>
                            );
                          })}
                          <td style={{ textAlign: 'center' }}>
                            <span className="mono u-bold" style={{ color: 'var(--text-2)' }}>{gunTotal}</span>
                          </td>
                        </tr>
                      );
                    })}

                    {/* Totals: on-ground */}
                    <tr style={{ borderTop: '2px solid var(--border-2)', background: 'var(--surface-2)' }}>
                      <td style={{ position: 'sticky', right: 0, background: 'var(--surface-2)', fontWeight: 700, fontSize: '.75rem' }}>
                        סה"כ ערום קרקע
                      </td>
                      {cols.map(r => (
                        <td key={r.key} style={{ textAlign: 'center' }}>
                          <span className="mono u-bold">{totalsGun[r.key] || 0}</span>
                        </td>
                      ))}
                      <td />
                    </tr>

                    {/* Totals: רמסע/bunker */}
                    <tr style={{ background: 'var(--info-soft)' }}>
                      <td style={{ position: 'sticky', right: 0, background: 'var(--info-soft)', fontWeight: 700, fontSize: '.75rem', color: 'var(--info)' }}>
                        רמסע
                      </td>
                      {cols.map(r => (
                        <td key={r.key} style={{ textAlign: 'center' }}>
                          <span className="mono" style={{ color: 'var(--info)' }}>{totalsRamsav[r.key] || 0}</span>
                        </td>
                      ))}
                      <td />
                    </tr>

                    {/* Totals: grand total */}
                    <tr style={{ background: 'var(--accent-soft)', borderTop: '1px solid var(--accent-line)' }}>
                      <td style={{ position: 'sticky', right: 0, background: 'var(--accent-soft)', fontWeight: 800, fontSize: '.75rem', color: 'var(--accent)' }}>
                        סה"כ כולל
                      </td>
                      {cols.map(r => {
                        const total = (totalsGun[r.key] || 0) + (totalsRamsav[r.key] || 0);
                        const rl = state.redLines?.[r.key] || 0;
                        return (
                          <td key={r.key} style={{ textAlign: 'center' }}>
                            <span className="mono u-bold" style={{ color: 'var(--accent)' }}>{total}</span>
                            {rl > 0 && <div style={{ fontSize: '.6rem', color: 'var(--text-4)' }}>קו: {rl}</div>}
                          </td>
                        );
                      })}
                      <td />
                    </tr>

                    {/* Red line inputs */}
                    <tr style={{ background: 'var(--inset)' }}>
                      <td style={{ position: 'sticky', right: 0, background: 'var(--inset)', fontSize: '.72rem', color: 'var(--danger)' }}>קו אדום</td>
                      {cols.map(r => (
                        <td key={r.key} style={{ textAlign: 'center', padding: '.25rem' }}>
                          <input type="number" min="0" value={state.redLines?.[r.key] || ''} placeholder="—"
                            onChange={e => setRedLine(r.key, e.target.value)}
                            style={{ width: '58px', textAlign: 'center', fontSize: '.75rem' }} />
                        </td>
                      ))}
                      <td />
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <div className="view-stack">
      {/* ── Readiness + filter tabs in one bar ── */}
      <div className="card card-pad">
        <div className="spread" style={{ flexWrap: 'wrap', gap: '.75rem', marginBottom: '.75rem' }}>
          <h3 style={{ margin: 0 }}>מטריצת מלאי צוותים</h3>
          {/* Filter tabs */}
          <div className="row" style={{ gap: '.3rem', flexWrap: 'wrap' }}>
            <button onClick={() => setFilter('all')}
              className={'btn btn-sm ' + (filter === 'all' ? 'btn-primary' : 'btn-outline')}>
              כל הצוותים
            </button>
            {GUNS_V.map(g => {
              const t = readinessTier(state, g);
              const isActive = filter === g;
              return (
                <button key={g} onClick={() => setFilter(g)}
                  className={'btn btn-sm ' + (isActive ? 'btn-amber' : 'btn-ghost')}
                  style={{ borderColor: isActive ? 'var(--accent)' : 'var(--border)' }}>
                  <span className={'dot ' + t.cls} />
                  {g}
                </button>
              );
            })}
          </div>
        </div>
        {/* Readiness selectors */}
        <div className="form-row">
          <div className="form-group grow"><label>🔴 כוננות אדומה</label>
            <select value={state.readiness?.red || ''} onChange={e => setReadiness('red', e.target.value)}>
              <option value="">— ללא —</option>{GUNS_V.map(g => <option key={g} value={g}>צוות {g}</option>)}
            </select>
          </div>
          <div className="form-group grow"><label>🟡 כוננות צהובה</label>
            <select value={state.readiness?.yellow || ''} onChange={e => setReadiness('yellow', e.target.value)}>
              <option value="">— ללא —</option>{GUNS_V.map(g => <option key={g} value={g}>צוות {g}</option>)}
            </select>
          </div>
        </div>
      </div>

      {/* ── Content: single gun or full matrix ── */}
      {filter === 'all' ? <AllGunsMatrix /> : <GunDetailView gun={filter} />}

      {/* Reset gun confirmation */}
      {resetGun && (
        <ModalV title={`איפוס מלאי צוות ${resetGun}`} icon="↺" onClose={() => setResetGun(null)}>
          <div className="callout callout-danger" style={{ marginBottom: '1rem' }}>
            ⚠ כל התחמושת של צוות <b>{resetGun}</b> תאופס לאפס. פינת פסולים לא תושפע. פעולה זו אינה הפיכה.
          </div>
          <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
            <button className="btn btn-gray" onClick={() => setResetGun(null)}>ביטול</button>
            <button className="btn btn-red" onClick={doResetGun}>↺ אפס מלאי צוות {resetGun}</button>
          </div>
        </ModalV>
      )}
    </div>
  );
}

// ── Bunker / pallets ─────────────────────────────────────────
function EditPalletModal({ pallet, regs, dispatch, onClose }) {
  const [qtys, setQtys] = useStateV(() => { const o = {}; regs.forEach(r => { o[r.key] = String(pallet.ammo[r.key] || 0); }); return o; });
  const submit = () => {
    const ammo = {};
    regs.forEach(r => { const q = parseInt(qtys[r.key]) || 0; if (q > 0) ammo[r.key] = q; });
    dispatch({ type: 'EDIT_PALLET_STOCK', palletId: pallet.id, ammo });
    onClose();
  };
  return (
    <ModalV title={`עריכת מלאי — משטח #${pallet.id}`} icon="📦" onClose={onClose}>
      <div className="stack" style={{ gap: '.35rem', marginBottom: '.85rem' }}>
        {regs.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: '70px', textAlign: 'center' }}>{r.unit}</span>
            <input type="number" min="0" value={qtys[r.key]} onChange={e => setQtys(p => ({ ...p, [r.key]: e.target.value }))} style={{ width: '78px', textAlign: 'center' }} />
          </div>
        ))}
      </div>
      <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
        <button className="btn btn-gray" onClick={onClose}>ביטול</button>
        <button className="btn btn-primary" onClick={submit}>💾 שמור</button>
      </div>
    </ModalV>
  );
}

function BunkerView({ state, dispatch, onAddPallet }) {
  const regs = state.registeredTypes;
  const [editing, setEditing] = useStateV(null);
  const [confirmClear, setConfirmClear] = useStateV(null);

  return (
    <div className="view-stack">
      <div className="spread">
        <h3>מחסן ומשטחים</h3>
        <button className="btn btn-primary btn-sm" onClick={onAddPallet}>＋ קליטת משטח</button>
      </div>
      {state.bunker.length === 0 ? (
        <div className="card"><div className="empty"><div className="big">📦</div>אין משטחים במחסן — קלוט משטח חדש</div></div>
      ) : (
        <div className="grid-teams" style={{ gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))' }}>
          {state.bunker.map(p => {
            const items = regs.filter(r => (p.ammo[r.key] || 0) > 0);
            const sum = items.reduce((s, r) => s + (p.ammo[r.key] || 0), 0);
            return (
              <div key={p.id} className="card card-pad stack" style={{ gap: '.7rem' }}>
                <div className="spread">
                  <span className="u-bold mono" style={{ fontSize: '1.05rem' }}>משטח #{p.id}</span>
                  <span className="chip">{sum} פריטים</span>
                </div>
                <div className="stack" style={{ gap: '.25rem', minHeight: '40px' }}>
                  {items.length === 0 ? <span className="dim u-sm">ריק</span> : items.map(r => (
                    <div key={r.key} className="spread u-sm"><span className="muted">{r.label}</span>{badgeV(p.ammo[r.key])}</div>
                  ))}
                </div>
                <div className="row" style={{ gap: '.4rem', paddingTop: '.5rem', borderTop: '1px solid var(--border-soft)' }}>
                  <button className="btn btn-outline btn-sm grow" onClick={() => setEditing(p)}>✎ ערוך</button>
                  <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)' }} onClick={() => setConfirmClear(p)}>🗑 רוקן</button>
                </div>
              </div>
            );
          })}
        </div>
      )}
      {editing && <EditPalletModal pallet={editing} regs={regs} dispatch={dispatch} onClose={() => setEditing(null)} />}
      {confirmClear && (
        <ModalV title={`רוקון משטח #${confirmClear.id}`} icon="🗑" onClose={() => setConfirmClear(null)}>
          <div className="callout callout-danger u-center" style={{ marginBottom: '1rem' }}>המשטח יוסר לצמיתות מהמחסן. פעולה זו אינה הפיכה.</div>
          <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
            <button className="btn btn-gray" onClick={() => setConfirmClear(null)}>ביטול</button>
            <button className="btn btn-red" onClick={() => { dispatch({ type: 'CLEAR_PALLET', palletId: confirmClear.id }); setConfirmClear(null); }}>🗑 אשר רוקון</button>
          </div>
        </ModalV>
      )}
    </div>
  );
}

// ── Settings / central catalog ───────────────────────────────
function AddTypeRow({ cat, regs, dispatch }) {
  const [shellName, setShellName] = useStateV('');
  const [fuzeName, setFuzeName] = useStateV('');
  const [chargeType, setChargeType] = useStateV(CTN_V[0]);
  const [series, setSeries] = useStateV('');

  const buildRecord = () => {
    if (cat === 'shell') { const n = shellName.trim(); if (!n) return null; return mtrV(mskV(n)); }
    if (cat === 'fuze') { const n = fuzeName.trim(); if (!n) return null; return mtrV(mfkV(n)); }
    const s = series.trim(); if (!s) return null; return mtrV(mckV(chargeType, s));
  };
  const rec = buildRecord();
  const exists = rec && regs.find(r => r.key === rec.key);
  const add = () => { if (!rec || exists) return; dispatch({ type: 'ADD_REGISTERED_TYPE', record: rec }); setShellName(''); setFuzeName(''); setSeries(''); };

  return (
    <div className="subpanel" style={{ marginTop: '.5rem' }}>
      <div className="form-row">
        {cat === 'shell' && <div className="form-group grow" style={{ minWidth: '160px' }}><label>שם פגז חדש</label><input type="text" placeholder="OF-540" value={shellName} onChange={e => setShellName(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()} /></div>}
        {cat === 'fuze' && <div className="form-group grow" style={{ minWidth: '160px' }}><label>שם מרעום חדש</label><input type="text" placeholder="ET-M84" value={fuzeName} onChange={e => setFuzeName(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()} /></div>}
        {cat === 'charge' && <>
          <div className="form-group grow" style={{ minWidth: '150px' }}><label>סוג חנ"ה</label><select value={chargeType} onChange={e => setChargeType(e.target.value)}>{CTN_V.map(n => <option key={n} value={n}>{n}</option>)}</select></div>
          <div className="form-group" style={{ minWidth: '90px' }}><label>סדרה</label><input type="text" placeholder="א" value={series} onChange={e => setSeries(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()} /></div>
        </>}
        <button className="btn btn-green" disabled={!rec || !!exists} onClick={add}>＋ הוסף</button>
      </div>
      {exists && <div className="u-tiny" style={{ color: 'var(--warn)', marginTop: '.35rem' }}>⚠ סוג זה כבר קיים בקטלוג</div>}
    </div>
  );
}

// ── Remap modal: merge srcKey inventory into dstKey ──────────
// Used to fix name mismatches after import. Moves all qty from
// src to dst across all guns + bunker, then removes src from catalog.
function RemapModal({ srcRec, regs, dispatch, onClose }) {
  const [dstKey, setDstKey] = useStateV('');
  const samecat = regs.filter(r => r.key !== srcRec.key && r.category === srcRec.category);
  const canSubmit = !!dstKey;

  const doRemap = () => {
    if (!dstKey) return;
    dispatch({ type: 'REMAP_AMMO_TYPE', srcKey: srcRec.key, dstKey });
    onClose();
  };

  return (
    <ModalV title="מיזוג / שינוי שם תחמושת" icon="🔀" onClose={onClose}>
      <div className="stack" style={{ gap: '.85rem' }}>
        <div className="callout callout-info">
          כל הכמויות של <b>{srcRec.label}</b> (בצוותים + מחסן) יועברו לסוג היעד שתבחר, ו-<b>{srcRec.label}</b> יוסר מהקטלוג. שימושי לתיקון שמות לאחר ייבוא.
        </div>
        <div className="form-group">
          <label>העבר אל (סוג יעד — אותה קטגוריה)</label>
          <select value={dstKey} onChange={e => setDstKey(e.target.value)}>
            <option value="">— בחר סוג יעד —</option>
            {samecat.map(r => <option key={r.key} value={r.key}>{r.label}</option>)}
          </select>
        </div>
        {!samecat.length && (
          <div className="callout callout-warn">אין סוגים אחרים באותה קטגוריה. הוסף קודם את סוג היעד לקטלוג.</div>
        )}
        <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
          <button className="btn btn-gray" onClick={onClose}>ביטול</button>
          <button className="btn btn-primary" disabled={!canSubmit} onClick={doRemap}>🔀 בצע מיזוג</button>
        </div>
      </div>
    </ModalV>
  );
}

// ── Delete confirmation modal (force-delete even if in use) ──
function DeleteConfirmModal({ rec, totals, dispatch, onClose }) {
  const qty = totals[rec.key] || 0;
  const doDelete = () => {
    dispatch({ type: 'FORCE_DELETE_TYPE', key: rec.key });
    onClose();
  };
  return (
    <ModalV title="מחיקת סוג תחמושת" icon="🗑" onClose={onClose}>
      <div className="stack" style={{ gap: '.85rem' }}>
        {qty > 0 ? (
          <div className="callout callout-danger">
            ⚠ קיים מלאי פעיל: <b>{qty} יח'</b> של <b>{rec.label}</b> בצוותים ובמחסן.<br />
            המחיקה תסיר את הסוג מהקטלוג <b>ותמחק את כל הכמויות</b> מכל הצוותים והמשטחים.
          </div>
        ) : (
          <div className="callout callout-warn">
            מחיקת <b>{rec.label}</b> מהקטלוג. אין מלאי פעיל.
          </div>
        )}
        <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
          <button className="btn btn-gray" onClick={onClose}>ביטול</button>
          <button className="btn btn-red" onClick={doDelete}>🗑 אשר מחיקה</button>
        </div>
      </div>
    </ModalV>
  );
}

function ConfigView({ state, dispatch }) {
  const regs = state.registeredTypes;
  const totals = totalAmmoV(state);
  const [editKey, setEditKey] = useStateV(null);
  const [draft, setDraft] = useStateV('');
  const [deleteRec, setDeleteRec] = useStateV(null);
  const [remapRec, setRemapRec] = useStateV(null);
  const M85 = window.M85_DEFAULT.key;

  const startEdit = r => { setEditKey(r.key); setDraft(r.label); };
  const saveEdit = () => { if (draft.trim()) dispatch({ type: 'UPDATE_REGISTERED_TYPE', key: editKey, label: draft.trim() }); setEditKey(null); };

  return (
    <div className="view-stack">
      <div className="card card-pad">
        <h3 style={{ marginBottom: '.3rem' }}>קטלוג תחמושת מרכזי</h3>
        <p className="muted u-sm" style={{ margin: 0 }}>
          זהו המקור היחיד לשמות הפגזים, החנ"ות והמרעומים. כל הטפסים, החישובים והדוחות במערכת יורשים את הקטלוג הזה.
        </p>
      </div>

      {CAT_ORDER.map(cat => {
        const rows = regs.filter(r => r.category === cat);
        return (
          <div key={cat} className="section-card">
            <div className="section-header">
              <span className="section-title">{CAT_META[cat].icon} {CAT_META[cat].label}</span>
              <span className="chip">{rows.length} סוגים</span>
            </div>
            <div className="card-pad">
              {rows.length === 0 ? <div className="dim u-sm u-center" style={{ padding: '.8rem' }}>אין סוגים — הוסף למטה</div> : (
                <div className="tbl-wrap">
                  <table>
                    <thead><tr><th className="u-right">שם / תווית</th><th>מפתח מערכת</th><th>יחידה</th><th>במלאי</th><th>פעולות</th></tr></thead>
                    <tbody>
                      {rows.map(r => {
                        const inUse = (totals[r.key] || 0) > 0;
                        const protectedRow = r.key === M85;
                        return (
                          <tr key={r.key}>
                            <td className="u-right">
                              {editKey === r.key ? (
                                <input type="text" value={draft} autoFocus onChange={e => setDraft(e.target.value)}
                                  onKeyDown={e => { if (e.key === 'Enter') saveEdit(); if (e.key === 'Escape') setEditKey(null); }}
                                  style={{ maxWidth: '220px' }} />
                              ) : <span className="u-bold">{r.label}</span>}
                            </td>
                            <td><span className="tag-key">{r.key}</span></td>
                            <td className="dim u-sm">{r.unit}</td>
                            <td>{inUse ? <span className="badge badge-green">{totals[r.key]}</span> : <span className="badge-zero">—</span>}</td>
                            <td>
                              <div className="row" style={{ gap: '.3rem', justifyContent: 'center' }}>
                                {editKey === r.key ? (
                                  <>
                                    <button className="btn btn-green btn-sm" onClick={saveEdit}>✔</button>
                                    <button className="btn btn-ghost btn-sm" onClick={() => setEditKey(null)}>✕</button>
                                  </>
                                ) : (
                                  <>
                                    <button className="btn btn-outline btn-sm" onClick={() => startEdit(r)}
                                      title="שנה תווית תצוגה">✎ שם</button>
                                    <button className="btn btn-outline btn-sm" style={{ color: 'var(--info)' }}
                                      onClick={() => setRemapRec(r)}
                                      disabled={protectedRow}
                                      title="מזג/העבר כמויות לסוג אחר"><MergeIcon size={13} /> מזג</button>
                                    <button className="btn btn-ghost btn-sm"
                                      style={{ color: protectedRow ? 'var(--text-4)' : 'var(--danger)' }}
                                      disabled={protectedRow}
                                      title={protectedRow ? 'רשומת בסיס מוגנת' : inUse ? 'מחק (יסיר גם מלאי)' : 'מחק מהקטלוג'}
                                      onClick={() => !protectedRow && setDeleteRec(r)}>🗑</button>
                                  </>
                                )}
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
              <AddTypeRow cat={cat} regs={regs} dispatch={dispatch} />
            </div>
          </div>
        );
      })}

      {deleteRec && (
        <DeleteConfirmModal rec={deleteRec} totals={totals} dispatch={dispatch} onClose={() => setDeleteRec(null)} />
      )}
      {remapRec && (
        <RemapModal srcRec={remapRec} regs={regs} dispatch={dispatch} onClose={() => setRemapRec(null)} />
      )}

      {/* ── Ammo groups panel ── */}
      <AmmoGroupsPanel state={state} dispatch={dispatch} />
    </div>
  );
}

// ── Ammo groups management ───────────────────────────────────
// Groups let you define a named collection of ammo types
// (e.g. "פגזי שדה" = OF-540 + M107) and set a red line on
// the COMBINED total (on-ground + רמסע).
function AmmoGroupsPanel({ state, dispatch }) {
  const regs  = state.registeredTypes;
  const groups = state.ammoGroups || [];
  const [editing, setEditing] = useStateV(null);   // group being edited
  const [adding, setAdding]   = useStateV(false);  // show add form

  return (
    <div className="section-card">
      <div className="section-header">
        <span className="section-title">📦 קבוצות תחמושת</span>
        <button className="btn btn-outline btn-sm" onClick={() => setAdding(true)}>＋ קבוצה חדשה</button>
      </div>
      <div className="card-pad">
        <p className="muted u-sm" style={{ margin: '0 0 .85rem' }}>
          הגדר קבוצות של סוגי תחמושת לניטור מצטבר עם קו אדום על הסה"כ (קרקע + רמסע).
        </p>

        {groups.length === 0 && !adding && (
          <div className="dim u-sm u-center" style={{ padding: '.8rem' }}>אין קבוצות — הוסף קבוצה חדשה</div>
        )}

        {groups.map(g => {
          const { gunTotal, bunkerTotal, total } = calcGroupTotalV(g, state);
          const crit = g.redLine > 0 && total < g.redLine;
          return editing?.id === g.id
            ? <GroupEditForm key={g.id} group={g} regs={regs} dispatch={dispatch} onClose={() => setEditing(null)} />
            : (
              <div key={g.id} className="subpanel" style={{ marginBottom: '.6rem', borderColor: crit ? 'var(--danger-line)' : undefined, background: crit ? 'var(--danger-soft)' : undefined }}>
                <div className="spread" style={{ flexWrap: 'wrap', gap: '.5rem' }}>
                  <div className="stack" style={{ gap: '.2rem' }}>
                    <span className="u-bold">{g.label} {crit && <span style={{ color: 'var(--danger)' }}>⚠ מתחת לקו</span>}</span>
                    <span className="dim u-tiny">{(g.keys || []).map(k => keyLabelV(k, regs)).join(' · ')}</span>
                  </div>
                  <div className="row" style={{ gap: '1rem', alignItems: 'center' }}>
                    <div className="row" style={{ gap: '.75rem' }}>
                      <div className="stack" style={{ gap: '.1rem', alignItems: 'center' }}>
                        <span className="mono u-bold" style={{ fontSize: '1.15rem' }}>{gunTotal}</span>
                        <span className="dim u-tiny">קרקע</span>
                      </div>
                      <div className="stack" style={{ gap: '.1rem', alignItems: 'center' }}>
                        <span className="mono" style={{ fontSize: '1.15rem', color: 'var(--info)' }}>{bunkerTotal}</span>
                        <span className="dim u-tiny">רמסע</span>
                      </div>
                      <div className="stack" style={{ gap: '.1rem', alignItems: 'center' }}>
                        <span className="mono u-bold" style={{ fontSize: '1.3rem', color: crit ? 'var(--danger)' : 'var(--accent)' }}>{total}</span>
                        <span className="dim u-tiny">סה"כ{g.redLine > 0 ? ` / קו ${g.redLine}` : ''}</span>
                      </div>
                    </div>
                    <div className="row" style={{ gap: '.3rem' }}>
                      <button className="btn btn-outline btn-sm" onClick={() => setEditing(g)}>✎ ערוך</button>
                      <button className="btn btn-ghost btn-sm" style={{ color: 'var(--danger)' }}
                        onClick={() => dispatch({ type: 'DELETE_AMMO_GROUP', id: g.id })}>🗑</button>
                    </div>
                  </div>
                </div>
              </div>
            );
        })}

        {adding && (
          <GroupEditForm regs={regs} dispatch={dispatch} onClose={() => setAdding(false)} isNew />
        )}
      </div>
    </div>
  );
}

function GroupEditForm({ group, regs, dispatch, onClose, isNew }) {
  const [label, setLabel]   = useStateV(group?.label || '');
  const [keys, setKeys]     = useStateV(group?.keys  || []);
  const [redLine, setRedLine] = useStateV(String(group?.redLine || 0));

  const toggleKey = k => setKeys(prev => prev.includes(k) ? prev.filter(x => x !== k) : [...prev, k]);

  const save = () => {
    if (!label.trim() || keys.length === 0) return;
    const rl = parseInt(redLine) || 0;
    if (isNew) {
      dispatch({ type: 'ADD_AMMO_GROUP', label: label.trim(), keys, redLine: rl });
    } else {
      dispatch({ type: 'EDIT_AMMO_GROUP', id: group.id, label: label.trim(), keys, redLine: rl });
    }
    onClose();
  };

  return (
    <div className="subpanel" style={{ marginBottom: '.6rem' }}>
      <div className="stack" style={{ gap: '.75rem' }}>
        <div className="form-row">
          <div className="form-group grow">
            <label>שם הקבוצה</label>
            <input type="text" value={label} onChange={e => setLabel(e.target.value)} placeholder="לדוגמה: פגזי שדה" autoFocus />
          </div>
          <div className="form-group" style={{ minWidth: '110px' }}>
            <label>קו אדום (סה"כ)</label>
            <input type="number" min="0" value={redLine} onChange={e => setRedLine(e.target.value)} style={{ fontFamily: 'var(--font-mono)' }} placeholder="0 = כבוי" />
          </div>
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '.4rem' }}>סוגי תחמושת בקבוצה</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '.35rem' }}>
            {regs.map(r => {
              const selected = keys.includes(r.key);
              return (
                <button key={r.key} onClick={() => toggleKey(r.key)}
                  className={'btn btn-sm ' + (selected ? 'btn-primary' : 'btn-outline')}
                  style={{ fontSize: '.75rem' }}>
                  {selected ? '✓ ' : ''}{r.label}
                </button>
              );
            })}
          </div>
          {keys.length === 0 && <span className="dim u-tiny" style={{ marginTop: '.3rem', display: 'block' }}>בחר לפחות סוג אחד</span>}
        </div>

        <div className="row" style={{ gap: '.5rem', justifyContent: 'flex-end' }}>
          <button className="btn btn-gray" onClick={onClose}>ביטול</button>
          <button className="btn btn-primary" disabled={!label.trim() || keys.length === 0} onClick={save}>
            {isNew ? '＋ צור קבוצה' : '💾 שמור'}
          </button>
        </div>
      </div>
    </div>
  );
}

window.TeamsView  = TeamsView;
window.BunkerView = BunkerView;
window.ConfigView = ConfigView;
window.AmmoGroupsPanel = AmmoGroupsPanel;
})();
