window.FB = window.FB || {};

FB.ClockTab = function ClockTab({ lang, user }) {
  const { useState, useEffect } = React;
  const L = (zh, vi, en) => (lang === "zh" ? zh : lang === "vi" ? vi : en);
  const [staff, setStaff] = useState([]);
  const [today, setToday] = useState([]);
  const [busy, setBusy] = useState(null);
  const [confirm, setConfirm] = useState(null);
  // C1 实时时钟: 按「签到」记的就是这个时间, 让员工看得见
  const [now, setNow] = useState(() => new Date());
  useEffect(() => { const id = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(id); }, []);

  function load() {
    FB.api.staffList().then(setStaff);
    FB.api.todayAttendance().then(setToday);
  }
  useEffect(() => { load(); }, []);

  const rec = (id) => today.find((r) => r.staff_id === id);
  // 下方嵌入的每日任务进度 (TaskList 回报)
  const [tStats, setTStats] = useState(null);
  // header 精华: 在班 1/2 · 任务 2/7 + 条(任务进度)
  useEffect(() => {
    if (!staff.length || !FB.setPageInfo) return;
    const working = today.filter((r) => !r.end_time && r.start_time).length;
    let text = L("在班", "Đang làm", "Working") + " " + working + " / " + staff.length;
    if (tStats) text += " · " + L("任务", "việc", "tasks") + " " + tStats[0] + " / " + tStats[1];
    FB.setPageInfo(tStats ? { text, num: tStats[0], den: tStats[1], color: "#4A7A1C" } : text);
  }, [staff, today, tStats, lang]);
  const hhmm = (t) => (t ? String(t).slice(0, 5) : "");
  const hours = (r) => {
    if (!r || !r.start_time || !r.end_time) return null;
    const [h1, m1] = String(r.start_time).split(":").map(Number);
    const [h2, m2] = String(r.end_time).split(":").map(Number);
    let d = (h2 * 60 + m2) - (h1 * 60 + m1);
    if (d < 0) d += 24 * 60;
    return Math.round((d / 60) * 10) / 10;
  };

  const d = new Date();
  const wd = [L("週日", "CN", "Sun"), L("週一", "T2", "Mon"), L("週二", "T3", "Tue"),
              L("週三", "T4", "Wed"), L("週四", "T5", "Thu"), L("週五", "T6", "Fri"), L("週六", "T7", "Sat")][d.getDay()];
  const isSunday = d.getDay() === 0;

  async function clock(sid) {
    setBusy(sid);
    await FB.api.clockAttendance({ action: "clock", staff_id: sid, by: user.name });
    setBusy(null); load();
  }
  async function undo(sid) {
    setBusy(sid); setConfirm(null);
    await FB.api.clockAttendance({ action: "undo", staff_id: sid });
    setBusy(null); load();
  }

  return (
    <div className="px-3 py-3 max-w-md mx-auto pb-20">
      {/* 紧凑版: 日期+时钟一行; 员工装进一张卡, 每人两排字 — 人多了任务也不会被推太远 */}
      <div className="flex items-baseline justify-between px-1 pt-1 pb-3">
        <p className="text-[19px] font-semibold text-stone-900 tabular-nums leading-none">
          {String(d.getDate()).padStart(2, "0")}/{String(d.getMonth() + 1).padStart(2, "0")}
          <span className="text-[12px] font-normal text-stone-400 ml-1.5">{wd}</span>
          {isSunday && <span className="text-[11px] font-normal ml-1.5" style={{ color: "#A07A06" }}>{L("休息日", "Nghỉ", "Off")}</span>}
        </p>
        <p className="text-[21px] font-semibold tabular-nums leading-none" style={{ color: "#B91C1C" }}>
          {String(now.getHours()).padStart(2, "0")}:{String(now.getMinutes()).padStart(2, "0")}
          <span className="opacity-40 text-[15px]">:{String(now.getSeconds()).padStart(2, "0")}</span>
        </p>
      </div>

      <div className="rounded-xl border border-stone-200 bg-white divide-y divide-stone-100 overflow-hidden">
        {staff.map((s) => {
          const r = rec(s.id);
          const state = !r ? "none" : (!r.end_time ? "in" : "out");
          const hr = hours(r);
          return (
            <div key={s.id} className="flex items-center gap-2.5 px-3 py-2"
              style={{ borderLeft: "3px solid " + (state === "in" ? "#4A7A1C" : "transparent"), background: state === "in" ? "#FDFEFB" : "#fff" }}>
              {/* 名字区: 按错了点这里撤销 (省掉第三排小字) */}
              <div className="flex-1 min-w-0" onClick={() => state !== "none" && setConfirm(s)}>
                <p className="text-[15px] font-semibold text-stone-900 leading-snug truncate">{lang === "vi" ? (s.name_vn || s.name) : s.name}</p>
                <p className="text-[11px] leading-snug" style={{ color: state === "in" ? "#4A7A1C" : "#A8A29E" }}>
                  {state === "none" && L("还没签到", "Chưa chấm công", "Not clocked in")}
                  {state === "in" && "▶ " + hhmm(r.start_time) + " " + L("上班中", "Đang làm", "working")}
                  {state === "out" && hhmm(r.start_time) + "–" + hhmm(r.end_time) + (hr ? " · " + hr + "h" : "")}
                </p>
              </div>
              {state === "out" ? (
                <button onClick={() => setConfirm(s)}
                  className="px-3.5 h-10 rounded-xl border border-stone-200 text-stone-400 text-[12.5px] flex items-center gap-1 shrink-0">
                  <FB.UI.Icon name="check" size={13} />{L("已收工", "Xong", "Done")}
                </button>
              ) : (
                <button onClick={() => clock(s.id)} disabled={busy === s.id}
                  className="px-5 h-10 rounded-xl text-white font-semibold text-[14px] active:scale-95 disabled:opacity-40 shrink-0"
                  style={{ background: state === "in" ? "#57534E" : "#B91C1C" }}>
                  {busy === s.id ? "…" : state === "in" ? L("收工", "Về", "Out") : L("签到", "Vào", "In")}
                </button>
              )}
            </div>
          );
        })}
      </div>

      <p className="text-[11px] text-stone-400 text-center mt-2">
        {L("按下去记当下时间 · 按错了点名字改", "Ghi giờ hiện tại · bấm tên nếu sai", "Records now · tap name to fix")}
      </p>

      {/* 签到下面 = 今天的任务清单 (和任务页同一份, 打勾同步) */}
      <div className="mt-4">
        <FB.TaskList lang={lang} user={user} embedded onStats={(d, tt) => setTStats([d, tt])} />
      </div>

      {confirm && (
        <div className="fixed inset-0 z-40 flex items-end" style={{ background: "rgba(28,25,23,.45)" }}>
          <div className="bg-white w-full rounded-t-3xl p-4 pb-safe">
            <p className="text-[16px] font-medium text-stone-900 mb-1">{confirm.name}</p>
            <p className="text-[13px] text-stone-500 mb-4">
              {L("要撤销刚才的记录吗?", "Hủy bản ghi vừa rồi?", "Undo last record?")}
            </p>
            <div className="flex gap-2">
              <button onClick={() => setConfirm(null)} className="flex-1 h-12 rounded-xl border border-stone-200 text-stone-500 text-sm">
                {L("不用", "Không", "No")}
              </button>
              <button onClick={() => undo(confirm.id)} className="flex-1 h-12 rounded-xl bg-red-700 text-white font-medium">
                {L("撤销", "Hủy", "Undo")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
