// check.jsx — Daily / Weekly check validity calculator.
// Enter when the check was signed (in LT **or** UTC — the toggle says which) and
// the expiry is computed in BOTH zones so it can be copied straight onto the
// tech log / MR1 either way.
//   DAILY  = 36 hours   ·   WEEKLY = 7 days (168 hours)
// Clock arithmetic (not calendar days) — an instant in time, so LT/UTC agree.
const { useState: useCk, useEffect: useCkEf } = React;

const CK_H = 3600000;
const CK_KINDS = [
  { k: "daily", label: "DAILY", hours: 36, sub: "36 hours", soon: 4 },
  { k: "weekly", label: "WEEKLY", hours: 168, sub: "7 days", soon: 24 },
];

// wall-clock strings → epoch ms, read as either local time or UTC
function ckParse(date, time, zone) {
  const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date || "");
  const t = /^(\d{2}):(\d{2})$/.exec(time || "");
  if (!d || !t) return NaN;
  const [y, mo, dy] = [+d[1], +d[2] - 1, +d[3]], [hh, mm] = [+t[1], +t[2]];
  return zone === "UTC" ? Date.UTC(y, mo, dy, hh, mm) : new Date(y, mo, dy, hh, mm).getTime();
}
const CK_FMT = { weekday: "short", day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit", hour12: false };
function ckLT(ms) { return isNaN(ms) ? "—" : new Date(ms).toLocaleString("en-GB", CK_FMT); }
function ckUTC(ms) { return isNaN(ms) ? "—" : new Date(ms).toLocaleString("en-GB", { ...CK_FMT, timeZone: "UTC" }); }
// station offset for the given instant (Thailand has no DST, but read it live anyway)
function ckOff(ms) {
  const o = -new Date(isNaN(ms) ? Date.now() : ms).getTimezoneOffset() / 60;
  return "UTC" + (o >= 0 ? "+" : "−") + (Number.isInteger(o) ? Math.abs(o) : Math.abs(o).toFixed(1));
}
function ckDur(ms) {
  const m = Math.floor(Math.abs(ms) / 60000);
  return Math.floor(m / 60) + "h " + String(m % 60).padStart(2, "0") + "m";
}
// current wall clock in the chosen zone, as [yyyy-mm-dd, HH:MM]
function ckNowFields(zone) {
  const n = new Date(), p = (v) => String(v).padStart(2, "0");
  return zone === "UTC"
    ? [`${n.getUTCFullYear()}-${p(n.getUTCMonth() + 1)}-${p(n.getUTCDate())}`, `${p(n.getUTCHours())}:${p(n.getUTCMinutes())}`]
    : [`${n.getFullYear()}-${p(n.getMonth() + 1)}-${p(n.getDate())}`, `${p(n.getHours())}:${p(n.getMinutes())}`];
}

/* one instant shown in both zones */
function CkTimes({ head, ms, big }) {
  return (
    <div className={"chk-times" + (big ? " chk-times--big" : "")}>
      {head && <div className="chk-times-h">{head}</div>}
      <div className="chk-t"><span className="chk-t-z">LT <i>{ckOff(ms)}</i></span><b className="mono">{ckLT(ms)}</b></div>
      <div className="chk-t"><span className="chk-t-z">UTC</span><b className="mono">{ckUTC(ms)}</b></div>
    </div>
  );
}

function CheckCalc({ onBack, onSave }) {
  const [zone, setZone] = useCk("LT");
  const [kind, setKind] = useCk("daily");
  const n0 = ckNowFields("LT");
  const [date, setDate] = useCk(n0[0]);
  const [time, setTime] = useCk(n0[1]);
  const [now, setNow] = useCk(Date.now());
  useCkEf(() => { const id = setInterval(() => setNow(Date.now()), 30000); return () => clearInterval(id); }, []);

  // switching zone keeps the same INSTANT — re-render the fields in the other zone
  const switchZone = (z) => {
    if (z === zone) return;
    const ms = ckParse(date, time, zone);
    setZone(z);
    if (!isNaN(ms)) {
      const d = new Date(ms), p = (v) => String(v).padStart(2, "0");
      if (z === "UTC") { setDate(`${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}`); setTime(`${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`); }
      else { setDate(`${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`); setTime(`${p(d.getHours())}:${p(d.getMinutes())}`); }
    }
  };
  const setNowFields = () => { const f = ckNowFields(zone); setDate(f[0]); setTime(f[1]); };

  const def = CK_KINDS.find((x) => x.k === kind);
  const doneMs = ckParse(date, time, zone);
  const valid = !isNaN(doneMs);
  const expMs = valid ? doneMs + def.hours * CK_H : NaN;
  const left = valid ? expMs - now : null;
  const state = left == null ? "none" : left < 0 ? "expired" : left <= def.soon * CK_H ? "soon" : "ok";
  const leftTxt = left == null ? "Complete the fields"
    : left < 0 ? `Expired ${ckDur(left)} ago` : `${ckDur(left)} remaining`;
  const stTxt = state === "expired" ? "Expired" : state === "soon" ? "Due soon" : state === "ok" ? "Valid" : "—";

  const save = () => valid && onSave({
    kind, label: def.label, hours: def.hours, zone,
    doneLT: ckLT(doneMs), doneUTC: ckUTC(doneMs), expiryLT: ckLT(expMs), expiryUTC: ckUTC(expMs),
    remaining: leftTxt, expired: left < 0,
  });

  return (
    <>
    <div className="screen-scroll mel chk">
      <TopBar title="Daily / Weekly Check" sub="Validity calculator · LT + UTC" onBack={onBack}
        right={<span className="apipill"><i className="apipill-dot" />LT+UTC</span>} />
      <div className="mel-body">
        <div className="mel-now mono">Now — {ckLT(now)} LT · {ckUTC(now)} UTC</div>

        <div>
          <span className="field-label">Check type</span>
          <div className="mel-cats">
            {CK_KINDS.map((x) => (
              <button key={x.k} className={"mel-cat" + (kind === x.k ? " mel-cat--on" : "")} onClick={() => setKind(x.k)}>
                <b>{x.label}</b><span>{x.sub}</span>
              </button>
            ))}
          </div>
        </div>

        <div>
          <span className="field-label">Check signed — entered in</span>
          <div className="chk-zone">
            {["LT", "UTC"].map((z) => (
              <button key={z} className={"chk-zbtn" + (zone === z ? " chk-zbtn--on" : "")} onClick={() => switchZone(z)}>
                {z}{z === "LT" && <i>{ckOff(doneMs)}</i>}
              </button>
            ))}
            <button className="chk-nowbtn" onClick={setNowFields}>Now</button>
          </div>
          <div className="chk-dt">
            <input type="date" className="inp inp--mono" value={date} onChange={(e) => setDate(e.target.value)} />
            <input type="time" className="inp inp--mono" value={time} onChange={(e) => setTime(e.target.value)} />
          </div>
        </div>

        <Card className={"mel-result mel-result--" + state}>
          <div className="mel-r-head">
            <span>{def.label} · {def.sub}</span>
            <span className={"mel-badge mel-badge--" + state}>{stTxt}</span>
          </div>
          <CkTimes head="Check signed" ms={doneMs} />
          <CkTimes head={`Expiry · +${def.hours} h`} ms={expMs} big />
          <div className={"mel-rem mel-rem--" + state}>{leftTxt}</div>
        </Card>

        <div className="mel-note"><Ic.clock width="15" height="15" /><span>
          Counted as <b>elapsed clock time</b> from the signature — DAILY <b>+36 h</b>, WEEKLY <b>+7 days</b> — so the LT and UTC
          expiries are the same instant. LT uses this device's time zone ({ckOff(doneMs)}) — <b>always confirm against the tech log / MPD</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, { CheckCalc });
