/* ═══════════════════════════════════════════════════════════
   Shared modal shell + inventory modals
   (Modal, PasswordGate, AddPalletModal, TransferModal, Quarantine)
═══════════════════════════════════════════════════════════ */
(function () {
const { useState, useEffect, useRef } = React;
const {
  GUNS, CHARGE_BEHAVIORS, CHARGE_TYPE_NAMES,
  makeShellKey, makeFuzeKey, makeChargeKey, makeTypeRecord,
  parseKey, keyLabel, ammoQtyBadge, genId, fmtDatetime,
} = window;

// ── Shared shell ─────────────────────────────────────────────
function Modal({ title, onClose, children, xl, icon }) {
  return (
    <div className="modal-overlay" onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className={'modal-box' + (xl ? ' modal-box-xl' : '')}>
        <div className="section-header">
          <span className="section-title">{icon && <span>{icon}</span>}{title}</span>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>✕ סגור</button>
        </div>
        <div className="modal-body">{children}</div>
      </div>
    </div>
  );
}

function SepRow({ label, cols }) {
  return <tr className="sep-row"><td colSpan={cols}>{label}</td></tr>;
}

// ── Password gate (server-verified) ──────────────────────────
// If the user is already operator or admin (session cached), skip automatically.
function PasswordGate({ onSuccess, onCancel }) {
  const [code, setCode] = useState('');
  const [err, setErr]   = useState(false);
  const [busy, setBusy] = useState(false);

  // Auto-pass if already operator or admin
  useEffect(() => {
    if (window.api?.canEdit()) { onSuccess(); }
  }, []);

  const attempt = async () => {
    if (!code || busy) return;
    setBusy(true); setErr(false);
    try {
      const d = await window.api.login(code);
      if (d.role === 'viewer') {
        // Re-logged in as viewer — not enough
        setErr(true); setCode('');
        setTimeout(() => setErr(false), 2500);
      } else {
        onSuccess();
      }
    } catch (e) {
      setErr(true); setCode('');
      setTimeout(() => setErr(false), 2500);
    } finally { setBusy(false); }
  };

  // If canEdit already (rendered after auto-pass fires), show nothing
  if (window.api?.canEdit()) return null;

  return (
    <Modal title="אימות מפקד" icon="🔒" onClose={onCancel}>
      <div className="stack" style={{ gap: '.85rem' }}>
        <div className="muted u-center" style={{ fontSize: '.9rem' }}>נדרש קוד מפעיל / מנהל לביצוע עריכה</div>
        {err && <div className="callout callout-danger u-center u-bold">קוד שגוי — הפעולה נחסמה ⛔</div>}
        <input type="password" value={code} onChange={e => setCode(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && attempt()}
          placeholder="הקלד קוד..." autoFocus
          style={{ textAlign: 'center', fontSize: '1rem', letterSpacing: '.15em' }} />
        <div className="row" style={{ gap: '.5rem', justifyContent: 'center' }}>
          <button className="btn btn-green" disabled={busy || !code} onClick={attempt}>{busy ? 'מאמת...' : '✔ אישור'}</button>
          <button className="btn btn-gray" onClick={onCancel}>ביטול</button>
        </div>
      </div>
    </Modal>
  );
}

// ── Add pallet (external intake) ─────────────────────────────
function AddPalletModal({ nextId, registeredTypes, onClose, onSubmit }) {
  const emptyLine = () => ({ id: genId(), cat: 'shell', shellName: '', fuzeName: '', chargeType: 'M7 אחוד', series: '', qty: '' });
  const [lines, setLines] = useState([emptyLine()]);

  const setF = (id, f, v) => setLines(p => p.map(l => l.id === id ? { ...l, [f]: v } : l));
  const addLine = () => setLines(p => [...p, emptyLine()]);
  const rmLine = id => setLines(p => p.filter(l => l.id !== id));

  function lineKey(l) {
    if (l.cat === 'shell')  return l.shellName.trim() ? makeShellKey(l.shellName) : null;
    if (l.cat === 'fuze')   return l.fuzeName.trim()  ? makeFuzeKey(l.fuzeName)   : null;
    if (l.cat === 'charge') return l.series.trim()    ? makeChargeKey(l.chargeType, l.series) : null;
    return null;
  }
  const canSubmit = lines.some(l => lineKey(l) && parseInt(l.qty) > 0);

  const submit = () => {
    const ammo = {}, newTypeMap = {};
    lines.forEach(l => {
      const key = lineKey(l); const qty = parseInt(l.qty) || 0;
      if (!key || !qty) return;
      ammo[key] = (ammo[key] || 0) + qty;
      if (!registeredTypes.find(r => r.key === key) && !newTypeMap[key]) newTypeMap[key] = makeTypeRecord(key);
    });
    if (!Object.keys(ammo).length) return;
    onSubmit(ammo, Object.values(newTypeMap).filter(Boolean));
  };

  return (
    <Modal title={'קליטת תחמושת — משטח #' + nextId} icon="📦" onClose={onClose} xl>
      <div className="dim u-sm" style={{ marginBottom: '.6rem' }}>הוסף שורות. כל סוג חדש יירשם אוטומטית.</div>
      <div className="stack" style={{ gap: '.45rem' }}>
        {lines.map(l => (
          <div key={l.id} className="subpanel">
            <div className="form-row">
              <div className="form-group" style={{ minWidth: '110px' }}>
                <label>קטגוריה</label>
                <select value={l.cat} onChange={e => setF(l.id, 'cat', e.target.value)}>
                  <option value="shell">פגז</option>
                  <option value="charge">חנ"ה</option>
                  <option value="fuze">מרעום</option>
                </select>
              </div>
              {l.cat === 'shell' && (
                <div className="form-group grow" style={{ minWidth: '120px' }}>
                  <label>שם פגז</label>
                  <input type="text" placeholder="OF-540" value={l.shellName} onChange={e => setF(l.id, 'shellName', e.target.value)} />
                </div>
              )}
              {l.cat === 'fuze' && (
                <div className="form-group grow" style={{ minWidth: '120px' }}>
                  <label>שם מרעום</label>
                  <input type="text" placeholder="ET-M84" value={l.fuzeName} onChange={e => setF(l.id, 'fuzeName', e.target.value)} />
                </div>
              )}
              {l.cat === 'charge' && (<>
                <div className="form-group grow" style={{ minWidth: '150px' }}>
                  <label>סוג חנ"ה</label>
                  <select value={l.chargeType} onChange={e => setF(l.id, 'chargeType', e.target.value)}>
                    {CHARGE_TYPE_NAMES.map(n => <option key={n} value={n}>{n}</option>)}
                  </select>
                </div>
                <div className="form-group" style={{ minWidth: '85px' }}>
                  <label>סדרה</label>
                  <input type="text" placeholder="א" value={l.series} onChange={e => setF(l.id, 'series', e.target.value)} />
                </div>
              </>)}
              <div className="form-group" style={{ minWidth: '90px' }}>
                <label>כמות{l.cat === 'charge' && l.chargeType === 'M231' ? ' (מודולים)' : ''}</label>
                <input type="number" min="0" value={l.qty} onChange={e => setF(l.id, 'qty', e.target.value)} />
              </div>
              {lines.length > 1 && <button className="btn btn-red btn-sm" onClick={() => rmLine(l.id)}>✕</button>}
            </div>
            {l.cat === 'charge' && CHARGE_BEHAVIORS[l.chargeType]?.kind === 'modular' && (
              <div className="u-tiny" style={{ color: 'var(--ok)', marginTop: '.4rem' }}>
                M231: נספר בתתי מטענים. M231/1 = מודול אחד לפגז | M231/2 = שניים לפגז
              </div>
            )}
          </div>
        ))}
      </div>
      <div className="row" style={{ gap: '.5rem', marginTop: '.8rem' }}>
        <button className="btn btn-outline btn-sm" onClick={addLine}>＋ הוסף שורה</button>
        <button className="btn btn-green" onClick={submit} disabled={!canSubmit}>✔ קלוט משטח #{nextId}</button>
      </div>
    </Modal>
  );
}

window.Modal = Modal;
window.SepRow = SepRow;
window.PasswordGate = PasswordGate;
window.AddPalletModal = AddPalletModal;
})();
