/* ═══════════════════════════════════════════════════════════
   Barrel-wear view — cleaning interval, muzzle-brake life,
   barrel lifetime. M10 charges advance muzzle + barrel wear;
   every shell advances the cleaning counter.
   ─────────────────────────────────────────────────────────
   Thresholds below are operational placeholders — adjust to
   your unit's doctrine in one place.
═══════════════════════════════════════════════════════════ */
(function () {
const { useState: useStateB } = React;
const {
  GUNS: GUNS_B, fmtDatetime: fmtB, Modal: ModalB, PasswordGate: PasswordGateB,
} = window;

const WEAR_LIMITS = {
  clean:  100,   // פגזים עד נקיון קנה
  muzzle: 350,   // M10 עד החלפת בולם לוע
  barrel: 1500,  // M10 עד תום חיי קנה
};

function wearZone(v, max) {
  const pct = max ? (v / max) * 100 : 0;
  if (pct >= 90) return { cls: 'danger', color: 'var(--danger)', soft: 'var(--danger-soft)', label: 'קריטי' };
  if (pct >= 70) return { cls: 'warn', color: 'var(--warn)', soft: 'var(--warn-soft)', label: 'התראה' };
  return { cls: 'ok', color: 'var(--ok)', soft: 'var(--ok-soft)', label: 'תקין' };
}

function WearMeter({ label, value, max, hint, color }) {
  const pct = Math.min(100, max ? (value / max) * 100 : 0);
  const z = wearZone(value, max);
  const c = color || z.color;
  return (
    <div className="stack" style={{ gap: '.35rem' }}>
      <div className="spread">
        <span className="u-sm muted">{label}</span>
        <span className="mono u-bold" style={{ color: c }}>{value}<span className="faint" style={{ fontWeight: 400 }}> / {max}</span></span>
      </div>
      <div className="bar"><i style={{ width: pct + '%', background: c }} /></div>
      <div className="spread">
        <span className="u-tiny faint">{hint}</span>
        <span className="u-tiny u-bold" style={{ color: c }}>{Math.round(pct)}%</span>
      </div>
    </div>
  );
}

function BarrelCard({ gun, data, onReset }) {
  const bd = data || {};
  const muzzle = bd.muzzle || { count: 0, lastResetTs: null };
  const barrel = bd.barrel || { count: 0, lastResetTs: null };
  const sinceClean = bd.shellsSinceClean || 0;
  const cleanZone = wearZone(sinceClean, WEAR_LIMITS.clean);

  return (
    <div className="card card-pad stack" style={{ gap: '.9rem' }}>
      <div className="spread">
        <div className="row" style={{ gap: '.6rem' }}>
          <span className="gun-id">{gun}</span>
          <span className={'chip chip-' + cleanZone.cls} style={{ background: cleanZone.soft, color: cleanZone.color, borderColor: 'transparent' }}>{cleanZone.label}</span>
        </div>
        <span className="dim u-tiny mono">סה"כ {bd.totalShells || 0} פגזים</span>
      </div>

      <WearMeter label="🧽 פגזים עד נקיון" value={sinceClean} max={WEAR_LIMITS.clean} hint={'נקיון אחרון: ' + (bd.lastCleanTs ? fmtB(bd.lastCleanTs) : 'מעולם')} />
      <WearMeter label="🔩 בולם לוע (M10)" value={muzzle.count || 0} max={WEAR_LIMITS.muzzle} hint={'איפוס אחרון: ' + (muzzle.lastResetTs ? fmtB(muzzle.lastResetTs) : 'מעולם')} />
      <WearMeter label="🛢 חיי קנה (M10)" value={barrel.count || 0} max={WEAR_LIMITS.barrel} hint={'איפוס אחרון: ' + (barrel.lastResetTs ? fmtB(barrel.lastResetTs) : 'מעולם')} />

      <div className="row" style={{ gap: '.4rem', flexWrap: 'wrap', paddingTop: '.6rem', borderTop: '1px solid var(--border-soft)' }}>
        <button className="btn btn-outline btn-sm grow" onClick={() => onReset('clean', gun)}>🧽 בוצע נקיון</button>
        <button className="btn btn-outline btn-sm grow" onClick={() => onReset('muzzle', gun)}>🔩 הוחלף בולם</button>
        <button className="btn btn-outline btn-sm grow" onClick={() => onReset('barrel', gun)}>🛢 קנה חדש</button>
      </div>
    </div>
  );
}

function BarrelView({ state, dispatch }) {
  const [pending, setPending] = useStateB(null); // {kind, gun}
  const [authed, setAuthed] = useStateB(null);

  const RESET_LABELS = {
    clean:  { title: 'אישור נקיון קנה', verb: 'איפוס מונה נקיון', action: 'RESET_BARREL', note: 'מונה הפגזים שמאז הנקיון יאופס.' },
    muzzle: { title: 'החלפת בולם לוע', verb: 'איפוס מונה בולם לוע', action: 'RESET_MUZZLE', note: 'מונה ה-M10 של בולם הלוע יאופס.' },
    barrel: { title: 'התקנת קנה חדש', verb: 'איפוס חיי קנה', action: 'RESET_BARREL_WEAR', note: 'מונה ה-M10 של חיי הקנה יאופס. פעולה משמעותית.' },
  };

  const requestReset = (kind, gun) => setPending({ kind, gun });
  const doReset = () => {
    if (!authed) return;
    dispatch({ type: RESET_LABELS[authed.kind].action, gun: authed.gun });
    setAuthed(null);
  };

  return (
    <div className="view-stack">
      <div className="card card-pad">
        <div className="spread" style={{ flexWrap: 'wrap', gap: '.6rem' }}>
          <div>
            <h3 style={{ marginBottom: '.25rem' }}>בלאי קנה</h3>
            <p className="muted u-sm" style={{ margin: 0 }}>כל פגז מקדם את מונה הנקיון. מטעני M10 בלבד מקדמים את בלאי בולם הלוע וחיי הקנה.</p>
          </div>
          <div className="row" style={{ gap: '.5rem', flexWrap: 'wrap' }}>
            <span className="chip"><span className="dot dot-ok" />תקין</span>
            <span className="chip"><span className="dot dot-warn" />התראה ≥70%</span>
            <span className="chip"><span className="dot dot-danger" />קריטי ≥90%</span>
          </div>
        </div>
      </div>

      <div className="grid-teams" style={{ gridTemplateColumns: 'repeat(auto-fill,minmax(300px,1fr))' }}>
        {GUNS_B.map(g => <BarrelCard key={g} gun={g} data={state.barrelData?.[g]} onReset={requestReset} />)}
      </div>

      {pending && (
        <PasswordGateB onSuccess={() => { setAuthed(pending); setPending(null); }} onCancel={() => setPending(null)} />
      )}
      {authed && (
        <ModalB title={RESET_LABELS[authed.kind].title} icon="🔧" onClose={() => setAuthed(null)}>
          <div className="stack" style={{ gap: '.85rem' }}>
            <div className="subpanel">
              <div className="spread"><span className="muted">צוות</span><span className="u-bold mono" style={{ fontSize: '1.1rem' }}>{authed.gun}</span></div>
            </div>
            <div className="callout callout-warn u-center">{RESET_LABELS[authed.kind].note}</div>
            <div className="row" style={{ gap: '.6rem', justifyContent: 'flex-end' }}>
              <button className="btn btn-gray" onClick={() => setAuthed(null)}>ביטול</button>
              <button className="btn btn-primary" onClick={doReset}>✔ {RESET_LABELS[authed.kind].verb}</button>
            </div>
          </div>
        </ModalB>
      )}
    </div>
  );
}

window.BarrelView = BarrelView;
})();
