/* ═══════════════════════════════════════════════════════════
   History views — firing log (missions) + transfer log.
   Firing rows are editable (re-opens FireMissionModal in edit
   mode behind a password gate). CSV export for both logs.
═══════════════════════════════════════════════════════════ */
(function () {
const { useState: useStateH } = React;
const {
  GUNS: GUNS_H, parseKey: parseKeyH, keyLabel: keyLabelH, fmtDatetime: fmtH,
  csvExport: csvH, Modal: ModalH, PasswordGate: PasswordGateH,
} = window;

function comboSummary(items, regs) {
  // group ammoItems into "shell + charge + fuze ×N" readable lines
  return (items || []).map((it, i) => {
    const p = parseKeyH(it.key);
    const icon = p?.category === 'shell' ? '🔵' : p?.category === 'charge' ? '⚡' : '🟡';
    return <span key={i} className="u-tiny" style={{ display: 'inline-block', marginInlineEnd: '.5rem' }}>{icon} {keyLabelH(it.key, regs)} <b className="mono">×{it.qty}</b></span>;
  });
}

// ── Firing log ───────────────────────────────────────────────
function MissionsView({ state, dispatch }) {
  const regs = state.registeredTypes;
  const [editRow, setEditRow] = useStateH(null);
  const [authRow, setAuthRow] = useStateH(null);         // pending edit auth
  const [deleteRow, setDeleteRow] = useStateH(null);     // row waiting for delete auth
  const [deleteAuthRow, setDeleteAuthRow] = useStateH(null); // row after auth, waiting confirm
  const [q, setQ] = useStateH('');
  const log = state.firingLog || [];

  const filtered = log.filter(r => {
    if (!q.trim()) return true;
    const hay = [r.missionId, r.target, r.unit, r.gun, r.notes].join(' ').toLowerCase();
    return hay.includes(q.toLowerCase());
  });

  const exportCsv = () => {
    const regs = state.registeredTypes;

    // Build a unique sorted list of all ammo keys that appear in any mission
    const usedKeys = new Set();
    log.forEach(r => (r.ammoItems || []).forEach(it => usedKeys.add(it.key)));
    // Sort: shells first, then charges, then fuzes
    const catOrder = { shell: 0, charge: 1, fuze: 2 };
    const sortedKeys = [...usedKeys].sort((a, b) => {
      const pa = window.parseKey ? window.parseKey(a) : null;
      const pb = window.parseKey ? window.parseKey(b) : null;
      const oa = catOrder[pa?.category] ?? 9;
      const ob = catOrder[pb?.category] ?? 9;
      if (oa !== ob) return oa - ob;
      return keyLabelH(a, regs).localeCompare(keyLabelH(b, regs), 'he');
    });

    // Headers: fixed fields + one column per ammo type + category subtotals
    const fixedHeaders = ['מזהה משימה', 'תאריך', 'שעה', 'צוות', 'מסתייע', 'מטרה', 'mapiq', 'הערות'];
    const ammoHeaders = sortedKeys.map(k => keyLabelH(k, regs));
    const totalHeaders = ['סה"כ פגזים', 'סה"כ חנ"ה', 'סה"כ מרעומים', 'סה"כ כל התחמושת'];
    const headers = [...fixedHeaders, ...ammoHeaders, ...totalHeaders];

    const rows = log.map(r => {
      // Build qty map for this mission
      const qtyMap = {};
      (r.ammoItems || []).forEach(it => { qtyMap[it.key] = (qtyMap[it.key] || 0) + (it.qty || 0); });

      const fixed = [r.missionId, r.date, r.time, r.gun, r.unit || '', r.target || '', r.mapiq || '', r.notes || ''];
      const ammo  = sortedKeys.map(k => qtyMap[k] || 0);

      // Category subtotals
      let totalShells = 0, totalCharges = 0, totalFuzes = 0;
      sortedKeys.forEach(k => {
        const p = window.parseKey ? window.parseKey(k) : null;
        const q = qtyMap[k] || 0;
        if (p?.category === 'shell')  totalShells  += q;
        if (p?.category === 'charge') totalCharges += q;
        if (p?.category === 'fuze')   totalFuzes   += q;
      });
      const totals = [totalShells, totalCharges, totalFuzes, totalShells + totalCharges + totalFuzes];

      return [...fixed, ...ammo, ...totals];
    });

    csvH(headers, rows, `firing-log-${new Date().toISOString().slice(0, 10)}.csv`);
  };

  const doDelete = () => {
    if (!deleteAuthRow) return;
    dispatch({ type: 'DELETE_MISSION', rowId: deleteAuthRow.id });
    setDeleteAuthRow(null);
  };

  return (
    <div className="view-stack">
      <div className="card card-pad">
        <div className="spread" style={{ flexWrap: 'wrap', gap: '.6rem' }}>
          <div>
            <h3 style={{ marginBottom: '.2rem' }}>יומן משימות אש</h3>
            <span className="muted u-sm">{log.length} רשומות — ממוין מהחדש לישן</span>
          </div>
          <div className="row" style={{ gap: '.5rem', flexWrap: 'wrap' }}>
            <input type="text" placeholder="🔍 חיפוש מטרה / יחידה / מזהה..." value={q} onChange={e => setQ(e.target.value)} style={{ width: '240px', maxWidth: '60vw' }} />
            <button className="btn btn-outline btn-sm" onClick={exportCsv} disabled={!log.length}>⬇ ייצוא CSV</button>
          </div>
        </div>
      </div>

      <div className="section-card">
        <div className="tbl-wrap">
          {filtered.length === 0 ? (
            <div className="empty"><div className="big">🎯</div>{log.length ? 'אין תוצאות לחיפוש' : 'אין משימות אש עדיין'}</div>
          ) : (
            <table>
              <thead><tr>
                <th>מזהה</th><th>תאריך/שעה</th><th>צוות</th><th>מסתייע</th><th>מטרה</th>
                <th className="u-right" style={{ minWidth: '220px' }}>תחמושת</th>
                <th>הערות</th><th>פעולות</th>
              </tr></thead>
              <tbody>
                {filtered.map(r => (
                  <tr key={r.id}>
                    <td><span className="tag-key">{r.missionId}</span></td>
                    <td className="mono u-tiny u-nowrap">{r.date}<br /><span className="dim">{r.time}</span></td>
                    <td><span className="chip chip-accent">{r.gun}</span></td>
                    <td className="u-sm muted">{r.unit}</td>
                    <td className="u-sm u-bold">{r.target}</td>
                    <td className="u-right wrap">{comboSummary(r.ammoItems, regs)}</td>
                    <td className="u-sm dim wrap" style={{ maxWidth: '160px' }}>{r.notes || '—'}</td>
                    <td>
                      <div className="row" style={{ gap: '.3rem', justifyContent: 'center' }}>
                        <button className="btn btn-ghost btn-sm" title="ערוך משימה" onClick={() => setAuthRow(r)}>✎</button>
                        <button className="btn btn-ghost btn-sm" title="מחק משימה (נדרש קוד מנהל)"
                          style={{ color: 'var(--danger)' }}
                          onClick={() => setDeleteRow(r)}>🗑</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* Edit auth gate */}
      {authRow && <PasswordGateH onSuccess={() => { setEditRow(authRow); setAuthRow(null); }} onCancel={() => setAuthRow(null)} />}
      {editRow && <window.FireMissionModal state={state} dispatch={dispatch} editRow={editRow} onClose={() => setEditRow(null)} />}

      {/* Delete auth gate — uses PasswordGate (same AUTH_PASSWORD) */}
      {deleteRow && (
        <PasswordGateH
          onSuccess={() => { setDeleteAuthRow(deleteRow); setDeleteRow(null); }}
          onCancel={() => setDeleteRow(null)}
        />
      )}

      {/* Delete confirmation modal */}
      {deleteAuthRow && (
        <ModalH title="מחיקת משימת אש" icon="🗑" onClose={() => setDeleteAuthRow(null)}>
          <div className="stack" style={{ gap: '.85rem' }}>
            <div className="callout callout-danger">
              ⚠ משימה <b>{deleteAuthRow.missionId}</b> תימחק לצמיתות.<br />
              התחמושת שנוצלה ({(deleteAuthRow.ammoItems || []).map(it => `${keyLabelH(it.key, regs)} ×${it.invDeduction || it.qty}`).join(', ')}) <b>תוחזר</b> למלאי צוות <b>{deleteAuthRow.gun}</b>.
            </div>
            <div className="subpanel">
              <div className="spread"><span className="muted">מזהה</span><span className="mono u-bold">{deleteAuthRow.missionId}</span></div>
              <div className="spread"><span className="muted">מטרה</span><span className="u-bold">{deleteAuthRow.target}</span></div>
              <div className="spread"><span className="muted">תאריך</span><span className="mono">{deleteAuthRow.date} {deleteAuthRow.time}</span></div>
            </div>
            <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
              <button className="btn btn-gray" onClick={() => setDeleteAuthRow(null)}>ביטול</button>
              <button className="btn btn-red" onClick={doDelete}>🗑 אשר מחיקה והחזר מלאי</button>
            </div>
          </div>
        </ModalH>
      )}
    </div>
  );
}

// ── Transfer log ─────────────────────────────────────────────
function TransfersView({ state }) {
  const regs = state.registeredTypes;
  const [q, setQ] = useStateH('');
  const log = [...(state.transferLog || [])].reverse();

  const filtered = log.filter(r => {
    if (!q.trim()) return true;
    const hay = [r.src, r.dst].join(' ').toLowerCase();
    return hay.includes(q.toLowerCase());
  });

  const exportCsv = () => {
    const headers = ['תאריך ושעה', 'מקור', 'יעד', 'תחמושת'];
    const rows = log.map(r => [
      fmtH(r.datetime), r.src, r.dst,
      (r.items || []).map(it => `${keyLabelH(it.key, regs)} x${it.qty}`).join(' + '),
    ]);
    csvH(headers, rows, `transfer-log-${new Date().toISOString().slice(0, 10)}.csv`);
  };

  return (
    <div className="view-stack">
      <div className="card card-pad">
        <div className="spread" style={{ flexWrap: 'wrap', gap: '.6rem' }}>
          <div>
            <h3 style={{ marginBottom: '.2rem' }}>יומן תנועות מלאי</h3>
            <span className="muted u-sm">{log.length} תנועות — קליטות, ניודים, פסילות</span>
          </div>
          <div className="row" style={{ gap: '.5rem', flexWrap: 'wrap' }}>
            <input type="text" placeholder="🔍 חיפוש מקור / יעד..." value={q} onChange={e => setQ(e.target.value)} style={{ width: '220px', maxWidth: '60vw' }} />
            <button className="btn btn-outline btn-sm" onClick={exportCsv} disabled={!log.length}>⬇ ייצוא CSV</button>
          </div>
        </div>
      </div>

      <div className="section-card">
        <div className="tbl-wrap">
          {filtered.length === 0 ? (
            <div className="empty"><div className="big">🔁</div>{log.length ? 'אין תוצאות' : 'אין תנועות מלאי'}</div>
          ) : (
            <table>
              <thead><tr><th>תאריך ושעה</th><th>מקור</th><th></th><th>יעד</th><th className="u-right" style={{ minWidth: '200px' }}>תחמושת</th></tr></thead>
              <tbody>
                {filtered.map(r => (
                  <tr key={r.id}>
                    <td className="mono u-tiny u-nowrap">{fmtH(r.datetime)}</td>
                    <td className="u-sm"><span className="muted">{r.src}</span></td>
                    <td className="faint">←</td>
                    <td className="u-sm u-bold" style={{ color: 'var(--accent)' }}>{r.dst}</td>
                    <td className="u-right wrap">
                      {(r.items || []).map((it, j) => (
                        <span key={j} className="u-tiny" style={{ display: 'inline-block', marginInlineEnd: '.5rem' }}>{keyLabelH(it.key, regs)} <b className="mono">×{it.qty}</b></span>
                      ))}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

window.MissionsView = MissionsView;
window.TransfersView = TransfersView;
})();
