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

FB.AttendanceTab = function AttendanceTab({ lang, user }) {
  const { useState, useEffect } = React;
  const t = FB.makeT(lang);
  const L = (zh, en) => (lang === "zh" ? zh : en);

  const now = new Date();
  const [ym, setYm] = useState(now.toISOString().slice(0, 7));
  const [staff, setStaff] = useState([]);
  const [rows, setRows] = useState([]);
  const [salary, setSalary] = useState([]);
  const [view, setView] = useState("log");       // log | pay
  const [form, setForm] = useState(() => FB.draft.get("att_form", null));
  const [busy, setBusy] = useState(false);
  const [copied, setCopied] = useState(false);

  function load() {
    FB.api.attendanceMonth(ym).then(setRows);
    FB.api.salaryMonth(ym).then(setSalary);
  }
  useEffect(() => { FB.api.staffList().then(setStaff); }, []);
  useEffect(() => { load(); }, [ym]);
  useEffect(() => {
    if (FB.setPageInfo) FB.setPageInfo(ym + " · " + rows.length + " " + L("笔", "records"));
  }, [ym, rows.length, lang]);
  useEffect(() => { if (form) FB.draft.set("att_form", form); else FB.draft.clear("att_form"); }, [form]);

  const sName = (id) => (staff.find((s) => s.id === id) || {}).name || id;
  const daysIn = new Date(Number(ym.slice(0, 4)), Number(ym.slice(5, 7)), 0).getDate();
  const byStaff = {};
  rows.forEach((r) => { (byStaff[r.staff_id] = byStaff[r.staff_id] || []).push(r); });

  function shiftMonth(d) {
    const [y, m] = ym.split("-").map(Number);
    const nd = new Date(y, m - 1 + d, 1);
    setYm(nd.toISOString().slice(0, 7));
  }

  function openNew(sid, date) {
    setForm({ id: null, staff_id: sid || (staff[0] && staff[0].id), work_date: date || FB.todayLocal(), start_time: "09:00", end_time: "18:00", note: "" });
  }
  function openEdit(r) {
    setForm({ id: r.id, staff_id: r.staff_id, work_date: r.work_date, start_time: (r.start_time || "").slice(0, 5), end_time: (r.end_time || "").slice(0, 5), note: r.note || "" });
  }
  async function save() {
    setBusy(true);
    await FB.api.submitAttendance({ rows: [form], recorded_by: user.name });
    setBusy(false); setForm(null); load();
  }
  async function del() {
    if (!form.id) { setForm(null); return; }
    setBusy(true);
    await FB.api.submitAttendance({ action: "delete", id: form.id });
    setBusy(false); setForm(null); load();
  }

  const payText = salary.map((s) =>
    `${s.name} RM ${Number(s.total_pay).toFixed(2)} ${s.bank_name} ${s.bank_account}`).join("\n");
  const fullText = "central kitchen\n" + payText;

  return (
    <div className="px-3 py-3 max-w-md mx-auto pb-28">
      <div className="flex items-center justify-between mb-3">
        <button onClick={() => shiftMonth(-1)} className="w-10 h-10 rounded-xl border border-stone-200 bg-white text-stone-500 flex items-center justify-center"><FB.UI.Icon name="back" size={16} /></button>
        <div className="text-center">
          <p className="text-[17px] font-semibold text-stone-900">{ym}</p>
          <p className="text-[11px] text-stone-400">{rows.length} {L("笔记录", "records")}</p>
        </div>
        <button onClick={() => shiftMonth(1)} className="w-10 h-10 rounded-xl border border-stone-200 bg-white text-stone-500 flex items-center justify-center"><FB.UI.Icon name="chev" size={16} /></button>
      </div>

      <div className="mb-3">
        <FB.UI.Seg options={[["log", L("考勤", "Log")], ["pay", L("工资", "Pay")]]} value={view} onChange={setView} />
      </div>

      {view === "log" && (
        <>
          {staff.map((s) => {
            const list = (byStaff[s.id] || []).sort((a, b) => a.work_date.localeCompare(b.work_date));
            return (
              <div key={s.id} className="mb-4">
                <div className="flex items-center justify-between px-1 mb-1.5">
                  <p className="text-[14px] font-medium text-stone-800">{s.name}</p>
                  <span className="text-[12px] text-stone-500 tabular-nums">
                    {list.length} {L("天", "d")}
                    {list.length > s.std_days && <span className="text-[#C2540A] ml-1">+{list.length - s.std_days} OT</span>}
                  </span>
                </div>
                <div className="grid grid-cols-7 gap-1">
                  {Array.from({ length: daysIn }, (_, i) => {
                    const d = String(i + 1).padStart(2, "0");
                    const date = ym + "-" + d;
                    const rec = list.find((x) => x.work_date === date);
                    const isSun = new Date(date + "T00:00:00").getDay() === 0;
                    const isToday = date === FB.todayLocal();
                    return (
                      <button key={d} onClick={() => (rec ? openEdit(rec) : openNew(s.id, date))}
                        className="aspect-square rounded-lg text-[11px] flex items-center justify-center border tabular-nums"
                        style={rec
                          ? { background: "#B91C1C", color: "#fff", borderColor: isToday ? "#1C1917" : "#B91C1C", borderWidth: isToday ? 2 : 1 }
                          : { background: isSun ? "#FBF6E4" : "#fff", color: isSun ? "#A07A06" : "#D6D3D1",
                              borderColor: isToday ? "#B91C1C" : "#F5F5F4", borderWidth: isToday ? 2 : 1 }}>
                        {i + 1}
                      </button>
                    );
                  })}
                </div>
              </div>
            );
          })}
          <p className="text-[11px] text-stone-400 px-1">
            {L("点格子记上班 · 点红格改或删", "Tap to log · tap red to edit")}
          </p>
        </>
      )}

      {view === "pay" && (
        <>
          {salary.length === 0 && (
            <div className="rounded-xl border border-stone-200 bg-white p-6 text-center text-sm text-stone-400">
              {L("这个月还没有考勤记录", "No records this month")}
            </div>
          )}
          {salary.map((s) => (
            <div key={s.staff_id} className="rounded-xl border border-stone-200 bg-white p-3 mb-2">
              <div className="flex justify-between items-baseline">
                <p className="text-[15px] font-medium text-stone-800">{s.name}</p>
                <p className="text-[20px] font-semibold text-stone-900 tabular-nums">RM {Number(s.total_pay).toFixed(2)}</p>
              </div>
              <div className="mt-2 space-y-0.5 text-[12px] text-stone-500">
                <div className="flex justify-between">
                  <span>{L("正常", "Regular")} {s.regular_days} × {Number(s.daily_rate).toFixed(2)}</span>
                  <span className="tabular-nums">{Number(s.regular_pay).toFixed(2)}</span>
                </div>
                {s.ot_days > 0 && (
                  <div className="flex justify-between text-[#C2540A]">
                    <span>OT {s.ot_days} × 100</span>
                    <span className="tabular-nums">{Number(s.ot_pay).toFixed(2)}</span>
                  </div>
                )}
                <div className="flex justify-between text-stone-400 pt-1 border-t border-stone-100">
                  <span>{s.bank_name} {s.bank_account}</span>
                  {s.total_hours != null && <span>{s.total_hours}h</span>}
                </div>
              </div>
            </div>
          ))}
          {salary.length > 0 && (
            <>
              <div className="rounded-xl bg-stone-900 p-3 mt-3">
                <p className="text-[11px] font-semibold text-stone-400 mb-1.5">{L("转账文本", "Transfer text")}</p>
                <pre className="text-[12px] text-white whitespace-pre-wrap leading-relaxed" style={{ fontFamily: "ui-monospace,monospace" }}>{fullText}</pre>
              </div>
              <button onClick={() => { navigator.clipboard.writeText(fullText); setCopied(true); setTimeout(() => setCopied(false), 1500); }}
                className="w-full h-11 rounded-xl border border-stone-300 text-stone-600 text-sm mt-2">
                {copied ? "✓ " + L("已复制", "Copied") : "📋 " + L("复制", "Copy")}
              </button>
            </>
          )}
        </>
      )}

      {form && (
        <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-semibold text-stone-900 mb-3">
              {form.id ? L("改记录", "Edit") : L("记上班", "Log")}
            </p>
            <select value={form.staff_id} onChange={(e) => setForm({ ...form, staff_id: Number(e.target.value) })}
              className="w-full h-11 px-3 rounded-xl border border-stone-300 text-sm mb-2">
              {staff.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
            </select>
            <input type="date" value={form.work_date} onChange={(e) => setForm({ ...form, work_date: e.target.value })}
              className="w-full h-11 px-3 rounded-xl border border-stone-300 text-sm mb-2" />
            <div className="flex gap-2 mb-2">
              <input type="time" value={form.start_time} onChange={(e) => setForm({ ...form, start_time: e.target.value })}
                className="flex-1 h-11 px-3 rounded-xl border border-stone-300 text-sm" />
              <input type="time" value={form.end_time} onChange={(e) => setForm({ ...form, end_time: e.target.value })}
                className="flex-1 h-11 px-3 rounded-xl border border-stone-300 text-sm" />
            </div>
            <input value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })}
              placeholder={L("备注（选填）", "Note")} className="w-full h-11 px-3 rounded-xl border border-stone-300 text-sm mb-3" />
            <div className="flex gap-2">
              <button onClick={() => setForm(null)} className="px-4 h-12 rounded-xl border border-stone-200 text-stone-500 text-sm">
                {L("取消", "Cancel")}
              </button>
              {form.id && (
                <button onClick={del} disabled={busy} className="px-4 h-12 rounded-xl border border-red-200 text-red-600 text-sm">
                  {L("删除", "Delete")}
                </button>
              )}
              <button onClick={save} disabled={busy} className="flex-1 h-12 rounded-xl bg-red-700 text-white font-medium disabled:opacity-40">
                {busy ? "…" : L("保存", "Save")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
