// mel.jsx — MEL deferral duration calculator (Cat A/B/C/D).
// Calendar days in UTC, day-of-record (Day 0) excluded per MMEL; valid through
// the end of the expiry date. Cat A = per MEL proviso (enter days). Exported to window.
const { useState: useMe } = React;

const MEL_DAY = 86400000;
const melNum = (v) => { const n = parseInt(v, 10); return isNaN(n) ? 0 : n; };
const MEL_CATS = [
  { c: "A", days: null, label: "per MEL" },
  { c: "B", days: 3, label: "3 cal. days" },
  { c: "C", days: 10, label: "10 cal. days" },
  { c: "D", days: 120, label: "120 cal. days" },
];
function melMid(s) { const m = /(\d{4})-(\d{2})-(\d{2})/.exec(s || ""); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : NaN; }
function melFmt(ms) { return isNaN(ms) ? "—" : new Date(ms).toLocaleDateString("en-GB", { weekday: "short", day: "2-digit", month: "short", year: "numeric", timeZone: "UTC" }); }

function MelScreen({ preset, onBack, onSave }) {
  const now = new Date();
  const nowMid = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
  const todayStr = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-${String(now.getUTCDate()).padStart(2, "0")}`;
  const pCat = preset && /^[ABCD]$/.test(preset.cat) ? preset.cat : null;
  const [cat, setCat] = useMe(pCat || "C");
  const [aDays, setADays] = useMe((preset && preset.aDays) || "3");
  const [date, setDate] = useMe((preset && preset.date) || todayStr);

  const catDef = MEL_CATS.find((x) => x.c === cat);
  const n = cat === "A" ? melNum(aDays) : catDef.days;
  const discMid = melMid(date);
  const valid = !isNaN(discMid) && n > 0;
  const startMid = discMid + MEL_DAY;
  const expiryMid = discMid + n * MEL_DAY;
  const remaining = valid ? Math.round((expiryMid - nowMid) / MEL_DAY) : null;
  const state = remaining == null ? "none" : remaining < 0 ? "expired" : remaining <= 3 ? "soon" : "ok";
  const remTxt = remaining == null ? "Complete the fields"
    : remaining < 0 ? `Expired ${-remaining} days ago` : remaining === 0 ? "Due today (end of day UTC)" : `${remaining} days remaining`;
  const stTxt = state === "expired" ? "Expired" : state === "soon" ? "Due soon" : state === "ok" ? "Valid" : "—";

  const save = () => valid && onSave({ cat, days: n, disc: melFmt(discMid), expiry: melFmt(expiryMid), remaining, expired: remaining < 0, reg: preset && preset.reg, item: preset && preset.item, mel: preset && preset.mel });

  return (
    <>
    <div className="screen-scroll mel">
      <TopBar title="MEL Calculator" sub="MEL expiry calculator · UTC" onBack={onBack}
        right={<span className="apipill"><i className="apipill-dot" />UTC</span>} />
      <div className="mel-body">
        {preset && (preset.item || preset.mel) && (
          <div className="mel-from">
            <div className="mel-from-h"><Ic.doc width="14" height="14" />From MR2 · {preset.reg || "—"} · MEL {preset.mel || "—"}{preset.sheetExpiry ? ` · sheet exp ${preset.sheetExpiry}` : ""}</div>
            {preset.item && <div className="mel-from-item">{preset.item}</div>}
          </div>
        )}
        <div className="mel-now mono">Now (UTC): {now.toUTCString().replace("GMT", "UTC")}</div>

        <Field label="Record / defer date (UTC)">
          <input type="date" className="inp inp--mono" value={date} onChange={(e) => setDate(e.target.value)} />
        </Field>

        <div>
          <span className="field-label">MEL Category</span>
          <div className="mel-cats">
            {MEL_CATS.map((x) => (
              <button key={x.c} className={"mel-cat" + (cat === x.c ? " mel-cat--on" : "")} onClick={() => setCat(x.c)}>
                <b>Cat {x.c}</b><span>{x.days != null ? x.days + " days" : "per MEL"}</span>
              </button>
            ))}
          </div>
        </div>

        {cat === "A" && (
          <Field label="Days (per MEL Cat A proviso)">
            <input className="inp inp--mono" inputMode="numeric" value={aDays} onChange={(e) => setADays(e.target.value)} placeholder="e.g. 5" />
          </Field>
        )}

        <Card className={"mel-result mel-result--" + state}>
          <div className="mel-r-head">
            <span>Result · Cat {cat}{n ? ` · ${n} days` : ""}</span>
            <span className={"mel-badge mel-badge--" + state}>{stTxt}</span>
          </div>
          <KV k="Record date (Day 0 — excluded)" v={melFmt(discMid)} mono />
          <KV k="Count starts (Day 1 · 00:00 UTC)" v={melFmt(startMid)} mono />
          <div className="mel-expiry">
            <span>Expiry — valid to end of day</span>
            <b className="mono">{melFmt(expiryMid)}</b>
          </div>
          <div className={"mel-rem mel-rem--" + state}>{remTxt}</div>
        </Card>

        <div className="mel-note"><Ic.warn width="15" height="15" /><span>Counted in <b>UTC calendar days</b> · record day (Day 0) excluded · valid to end of the expiry date · Cat A per item proviso — <b>always refer to the actual MEL/MMEL</b></span></div>
      </div>
      <div className="scroll-pad" />
    </div>

    <div className="savebar">
      <Btn kind="ghost" onClick={onBack}>Close</Btn>
      <Btn kind="primary" full onClick={save} icon={<Ic.check width="18" height="18" />}>Save to Work Log</Btn>
    </div>
    </>
  );
}

Object.assign(window, { MelScreen });
