// ESS live clock: check in / break / check out — supports multiple sessions per day
function ClockCard({ emp }) {
  const { useState, useEffect } = React;
  const [now, setNow] = useState(new Date());
  const [ss, setSs] = useState([]);
  useEffect(() => { const t = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(t); }, []);
  useEffect(() => { API.hr.punchState().then(setSs).catch(() => {}); }, []);

  const hhmm = (d) => String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
  const secs = (s) => { const x = String(s).split(":"); return (+x[0] * 3600) + (+x[1] * 60) + (+x[2] || 0); };
  const cur = ss.length ? ss[ss.length - 1] : null;
  const openBreak = cur && !cur.out ? cur.breaks.find((b) => !b.to) : null;
  const state = !cur || cur.out ? (ss.length ? "done" : "out") : openBreak ? "break" : "in";

  const act = () => {
    const t = hhmm(now);
    const action = state === "out" || state === "done" ? "check_in" : state === "in" ? "break_start" : "break_end";
    const msg = action === "check_in" ? (ss.length ? T("clock.checkedBackInAt", { time: t }) : T("clock.checkedInAt", { time: t }))
      : action === "break_start" ? T("clock.breakStartedAt", { time: t }) : T("clock.breakEndedAt", { time: t });
    API.hr.punch(action).then((next) => { setSs(next); notify(msg); }).catch((ex) => notify(T("clock.error", { message: ex.message })));
  };
  const checkout = () => {
    const t = hhmm(now);
    API.hr.punch("check_out").then((next) => { setSs(next); notify(T("clock.checkedOutAt", { time: t })); }).catch((ex) => notify(T("clock.error", { message: ex.message })));
  };

  // Durations tick per second: punch times carry seconds, and the end of a
  // still-running session or break is the live clock.
  const nowSec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
  const liveEnd = (s) => (s.out ? secs(s.out) : nowSec);
  const breakOf = (s) => s.breaks.reduce((a, b) => a + ((b.to ? secs(b.to) : liveEnd(s)) - secs(b.from)), 0);
  const breakSec = ss.reduce((a, s) => a + breakOf(s), 0);
  const worked = ss.reduce((a, s) => a + Math.max(0, liveEnd(s) - secs(s.in) - breakOf(s)), 0);

  const label = state === "out" ? T("clock.checkIn") : state === "done" ? T("clock.checkInAgain") : state === "in" ? T("clock.startBreak") : T("clock.endBreak");
  const timeline = [];
  ss.forEach((s, i) => {
    timeline.push({ t: s.in, k: ss.length > 1 ? T("clock.inSession", { n: i + 1 }) : T("clock.checkedIn") });
    s.breaks.forEach((b) => { timeline.push({ t: b.from, k: T("clock.breakStart") }); if (b.to) timeline.push({ t: b.to, k: T("clock.breakEnd") }); });
    if (s.out) timeline.push({ t: s.out, k: ss.length > 1 ? T("clock.outSession", { n: i + 1 }) : T("clock.checkedOut") });
  });

  return (
    <section className="card pad clockcard">
      <div className="clock-main">
        <div className="clock-time">
          <span className="display mono">{hhmm(now)}<span className="clock-sec">:{String(now.getSeconds()).padStart(2, "0")}</span></span>
          <span className="dim">{now.toLocaleDateString(uiLocale(), { weekday: "long", month: "long", day: "numeric", year: "numeric" })}</span>
        </div>
        <div className="clock-act">
          <Btn variant="primary" onClick={act}>{label}</Btn>
          {state === "in" || state === "break" ? <Btn onClick={checkout}>{T("clock.checkOut")}</Btn> : null}
        </div>
        <div className="clock-tally">
          <span><b className="mono"><DurSec s={worked} /></b><small>{T("clock.workedToday")}</small></span>
          <span><b className="mono"><DurSec s={breakSec} /></b><small>{T("clock.break")}</small></span>
          {ss.length > 1 ? <span><b className="mono">{ss.length}</b><small>{T("clock.sessions")}</small></span> : null}
          <span><Badge tone={state === "in" ? "green" : state === "break" ? "amber" : state === "done" ? "blue" : undefined}>
            {state === "in" ? T("clock.onTheClock") : state === "break" ? T("clock.onBreak") : state === "done" ? T("clock.checkedOut") : T("clock.notCheckedIn")}
          </Badge></span>
        </div>
      </div>
      {timeline.length ? (
        <div className="clock-line">
          {timeline.map((x, i) => (
            <span className="clock-pt" key={i}><b className="mono"><TimeSec t={x.t} /></b><small>{x.k}</small></span>
          ))}
        </div>
      ) : null}
    </section>
  );
}
window.ClockCard = ClockCard;
