// «Движения по сотруднику» — карточка: нагрузка, эффективность, отсутствия, штрафы,
// зарплата + история (таймлайн). Задел под рекомендации ИИ-чата.

const TL_META = {
  payroll:    { label: "Зарплата",     color: "var(--ok)",            icon: I.Coins },
  fine:       { label: "Взыскание",    color: "var(--err)",           icon: I.Shield },
  efficiency: { label: "Эффективность", color: "var(--accent-strong)", icon: I.Gauge },
  absence:    { label: "Отсутствие",   color: "var(--warn)",          icon: I.Calendar },
  task:       { label: "Задача",       color: "var(--ink-400)",       icon: I.Check },
};

function profMoney(n) { return Math.round(n || 0).toLocaleString("ru-RU") + " ₽"; }

function PersonProfileModal({ person, onClose }) {
  const [data, setData] = React.useState(null);
  const [tab, setTab] = React.useState("all");
  const [editPay, setEditPay] = React.useState(false);
  const canManage = window.ME && (window.ME.role === "admin" || window.ME.role === "controller");

  const load = React.useCallback(() => {
    if (!window.API || !window.API.personProfile) return;
    window.API.personProfile(person).then(setData).catch(() => setData({ timeline: [] }));
  }, [person]);
  React.useEffect(() => { load(); }, [load]);

  const tl = (data && data.timeline) || [];
  const shown = tab === "all" ? tl : tl.filter(e => e.type === tab);
  const load_ = (data && data.load) || {};
  const avail = (data && data.availability) || {};
  const pay = (data && data.payroll) || {};
  const cur = pay.current || {};

  return (
    <div className="tg-overlay open" style={{ background: "rgba(13,22,32,.5)", display: "grid", placeItems: "center", zIndex: 280 }} onClick={onClose}>
      <div className="card" style={{ width: 680, maxWidth: "95vw", maxHeight: "92vh", display: "flex", flexDirection: "column", boxShadow: "var(--sh-3)" }} onClick={e => e.stopPropagation()}>
        <div className="card-head">
          <Avatar name={person} size={38} />
          <div style={{ flex: 1, minWidth: 0, marginLeft: 10 }}>
            <h3 className="card-title">{person}</h3>
            <p className="card-sub">{(data && data.person && data.person.dept) || "—"}{avail.absentNow ? ` · сейчас: ${ABSENCE_LABEL[avail.kind] || "отсутствует"} до ${avail.until}` : ""}</p>
          </div>
          <button className="icon-btn" style={{ color: "var(--ink-400)" }} onClick={onClose}><I.X size={18} /></button>
        </div>

        <div className="card-body" style={{ overflowY: "auto", display: "flex", flexDirection: "column", gap: 14 }}>
          {!data ? <div style={{ color: "var(--ink-400)", fontSize: 13 }}>Загрузка…</div> : (
            <>
              {/* load + efficiency summary */}
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(120px,1fr))", gap: 10 }}>
                <MiniStat label="Пик/день" value={load_.peakDay ? `${load_.peakHours || 0} ч` : "—"} color={load_.overLimit ? "var(--err)" : "var(--ink-700)"} />
                <MiniStat label="Активных" value={load_.activeTasks || 0} />
                <MiniStat label="Выработка" value={`${load_.perWeek || 0}/нед`} />
                <MiniStat label="К выплате" value={cur.base != null ? profMoney((cur.base || 0) + (cur.accruals || 0)) : "—"} />
              </div>
              {load_.overLimit && <div style={{ fontSize: 12, color: "var(--err)", background: "#fbecec", borderRadius: "var(--r-md)", padding: "6px 10px" }}><I.Alert size={11} /> Перегружен в пиковый день ({load_.peakDay}: {load_.peakHours} ч при норме {load_.workdayHours} ч) — стоит перенести или передать задачу.</div>}

              {/* salary + history */}
              <Card title="Зарплата" subtitle={cur.updated ? `обновлено ${cur.updated}` : "демо-данные"} bodyStyle={{ padding: 0 }}
                action={canManage ? <button className="btn btn-ghost" style={{ padding: "4px 10px", fontSize: 12 }} onClick={() => setEditPay(v => !v)}><I.Edit size={12} /> {editPay ? "Отмена" : "Изменить"}</button> : null}
                style={{ boxShadow: "none", border: "1px solid var(--ink-100)" }}>
                {editPay
                  ? <PayrollEdit cur={cur} person={person} onSaved={() => { setEditPay(false); load(); }} />
                  : (
                    <div style={{ padding: "10px 16px", display: "flex", gap: 18, fontSize: 13, flexWrap: "wrap" }}>
                      <div><span style={{ color: "var(--ink-400)" }}>Оклад: </span><b>{profMoney(cur.base || 0)}</b></div>
                      <div><span style={{ color: "var(--ink-400)" }}>Надбавки: </span><b>{profMoney(cur.accruals || 0)}</b></div>
                      <div><span style={{ color: "var(--ink-400)" }}>Изменений: </span>{(pay.history || []).length}</div>
                    </div>
                  )}
              </Card>

              {/* timeline */}
              <div>
                <div className="filter-row" style={{ marginBottom: 8 }}>
                  {["all", "payroll", "fine", "efficiency", "absence", "task"].map(k => (
                    <button key={k} className={`field ${tab === k ? "active" : ""}`} onClick={() => setTab(k)}>{k === "all" ? "Все" : TL_META[k].label}</button>
                  ))}
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {shown.length === 0 && <div style={{ fontSize: 12.5, color: "var(--ink-300)" }}>Нет записей.</div>}
                  {shown.map((e, i) => {
                    const m = TL_META[e.type] || TL_META.task;
                    const Ic = m.icon;
                    return (
                      <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                        <span style={{ width: 26, height: 26, borderRadius: 7, background: "var(--ink-50)", color: m.color, display: "grid", placeItems: "center", flexShrink: 0 }}><Ic size={13} /></span>
                        <div style={{ minWidth: 0, flex: 1 }}>
                          <div style={{ fontSize: 13 }}>{e.label}</div>
                          {e.detail && <div style={{ fontSize: 12, color: "var(--ink-400)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.detail}</div>}
                        </div>
                        <span style={{ fontSize: 11, color: "var(--ink-300)", whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>{e.ts}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function MiniStat({ label, value, color }) {
  return (
    <div style={{ background: "var(--ink-50)", borderRadius: "var(--r-md)", padding: "8px 11px" }}>
      <div style={{ fontSize: 10.5, color: "var(--ink-400)", textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
      <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2, color: color || "var(--ink-700)" }}>{value}</div>
    </div>
  );
}

function PayrollEdit({ cur, person, onSaved }) {
  const [base, setBase] = React.useState(cur.base || 0);
  const [accruals, setAccruals] = React.useState(cur.accruals || 0);
  const [reason, setReason] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const save = async () => {
    setBusy(true); setErr("");
    try { await window.API.setPayroll(person, { base: Number(base), accruals: Number(accruals), reason: reason.trim() }); onSaved(); }
    catch (e) { setErr(String((e && e.message) || e)); setBusy(false); }
  };
  return (
    <div style={{ padding: "12px 16px", display: "flex", flexDirection: "column", gap: 10 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <div><label className="fld-label">Оклад</label><input className="fld" type="number" min="0" style={{ width: "100%" }} value={base} onChange={e => setBase(e.target.value)} /></div>
        <div><label className="fld-label">Надбавки</label><input className="fld" type="number" min="0" style={{ width: "100%" }} value={accruals} onChange={e => setAccruals(e.target.value)} /></div>
      </div>
      <div><label className="fld-label">Основание изменения</label><input className="fld" style={{ width: "100%" }} placeholder="напр. индексация, повышение" value={reason} onChange={e => setReason(e.target.value)} /></div>
      {err && <div style={{ color: "var(--err)", fontSize: 12.5 }}>{err}</div>}
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <button className="btn btn-accent" style={{ padding: "6px 12px" }} onClick={save} disabled={busy}><I.Check size={13} /> Сохранить</button>
      </div>
    </div>
  );
}

window.PersonProfileModal = PersonProfileModal;
