// Employees — real staff directory (window.PEOPLE / API) with their поручения load.

function EmployeesPage({ onOpenOrders }) {
  const [people, setPeople] = React.useState({});
  const [tasks, setTasks] = React.useState([]);
  const [filter, setFilter] = React.useState("Все");
  const [addOpen, setAddOpen] = React.useState(false);
  const [loading, setLoading] = React.useState(true);

  const load = React.useCallback(() => {
    if (!window.API) { setLoading(false); return; }
    setLoading(true);
    Promise.all([
      window.API.people().catch(() => ({})),
      window.API.listTasks().catch(() => []),
    ]).then(([p, t]) => {
      setPeople(p || {});
      setTasks(Array.isArray(t) ? t : []);
    }).finally(() => setLoading(false));
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const isAdmin = window.ME && window.ME.role === "admin";
  const setActive = async (name, active) => {
    const verb = active ? "Восстановить" : "Уволить";
    if (!window.confirm(`${verb} сотрудника «${name}»?`)) return;
    try {
      if (active) await window.API.restorePerson(name);
      else await window.API.dismissPerson(name);
      load();
      if (window.refreshDirectory) window.refreshDirectory();
    } catch (e) {
      alert(String((e && e.message) || e));
    }
  };

  const eff = (t) => (typeof effStatus === "function" ? effStatus(t) : t.status);
  const depts = (typeof DEPARTMENTS !== "undefined") ? DEPARTMENTS : [];
  const filters = ["Все", ...depts];

  const rows = Object.keys(people).map(name => {
    const p = people[name] || {};
    const mine = tasks.filter(t => t.assignee === name);
    const total = mine.length;
    const done = mine.filter(t => eff(t) === "done").length;
    const overdue = mine.filter(t => eff(t) === "overdue").length;
    const pct = total ? Math.round(done / total * 100) : 0;
    return { name, dept: p.dept || "—", tg: p.tg || "", color: p.color, total, done, overdue, pct, active: p.active !== false };
  }).filter(r => filter === "Все" || r.dept === filter)
    .sort((a, b) => (a.active === b.active ? b.total - a.total : (a.active ? -1 : 1)));

  const exportCSV = () => {
    const header = ["ФИО", "Отдел", "Telegram", "Всего поручений", "Выполнено", "Просрочено"];
    const esc = v => `"${String(v == null ? "" : v).replace(/"/g, '""')}"`;
    const lines = [header.map(esc).join(";")];
    rows.forEach(r => lines.push([r.name, r.dept, r.tg, r.total, r.done, r.overdue].map(esc).join(";")));
    const blob = new Blob(["﻿" + lines.join("\r\n")], { type: "text/csv;charset=utf-8" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "Сотрудники.csv";
    a.click();
  };

  return (
    <div className="page page-fade">
      <div className="page-head">
        <div>
          <h1 className="page-title">Сотрудники</h1>
          <p className="page-subtitle">{Object.keys(people).length} человек · {depts.length} отделов{loading ? " · загрузка…" : ""}</p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-outline" onClick={exportCSV}><I.Download size={14} /> Экспорт</button>
          <button className="btn btn-primary" onClick={() => setAddOpen(true)}><I.Plus size={14} /> Добавить</button>
        </div>
      </div>

      <div className="filter-row">
        {filters.map(d => (
          <button key={d} className={`field ${filter === d ? "active" : ""}`} onClick={() => setFilter(d)}>{d}</button>
        ))}
      </div>

      <div className="emp-grid">
        {rows.map(e => (
          <div
            key={e.name}
            className="emp-card"
            style={{ cursor: "pointer", ...(e.active ? null : { opacity: 0.55 }) }}
            title={`Открыть поручения · ${e.name}`}
            onClick={() => onOpenOrders && onOpenOrders({ assignee: e.name })}
          >
            <div className="av-lg" style={{ background: e.active ? e.color : "var(--ink-300)" }}>{initials(e.name)}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="name" style={{ display: "flex", alignItems: "center", gap: 6 }}>
                {e.name}
                {!e.active && <span className="pill muted" style={{ fontSize: 10 }}>Уволен</span>}
              </div>
              <div className="role">{e.dept}{e.tg ? ` · ${e.tg}` : ""}</div>
              <div className="plan-row">
                <span>Выполнено</span>
                <span className="v" style={{ color: e.pct >= 70 ? "var(--ok)" : e.pct >= 40 ? "var(--ink-700)" : "var(--warn)" }}>{e.pct}%</span>
              </div>
              <div className="progress-track" style={{ marginTop: 4 }}>
                <div className="progress-fill" style={{ width: Math.min(e.pct, 100) + "%", background: e.pct >= 70 ? "linear-gradient(90deg, #4cb685, var(--ok))" : "linear-gradient(90deg, var(--accent), var(--accent-strong))" }} />
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: "2px 12px", marginTop: 10, fontSize: 11.5, color: "var(--ink-400)" }}>
                <span style={{ whiteSpace: "nowrap" }}>{e.total} поручений</span>
                <span style={{ whiteSpace: "nowrap" }}>· выполнено {e.done}</span>
                {e.overdue > 0 && <span style={{ whiteSpace: "nowrap", color: "var(--err)" }}>· просрочено {e.overdue}</span>}
              </div>
              <div style={{ marginTop: 9, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                <span style={{ fontSize: 11.5, fontWeight: 500, color: "var(--accent-strong)", display: "inline-flex", alignItems: "center", gap: 3 }}>
                  Поручения <I.Chevron size={12} style={{ transform: "rotate(-90deg)" }} />
                </span>
                {isAdmin && (
                  e.active
                    ? <button className="btn btn-ghost" style={{ padding: "2px 8px", fontSize: 11, color: "var(--err)" }} onClick={(ev) => { ev.stopPropagation(); setActive(e.name, false); }}><I.Logout size={12} /> Уволить</button>
                    : <button className="btn btn-ghost" style={{ padding: "2px 8px", fontSize: 11, color: "var(--ok)" }} onClick={(ev) => { ev.stopPropagation(); setActive(e.name, true); }}><I.Refresh size={12} /> Восстановить</button>
                )}
              </div>
            </div>
          </div>
        ))}
        {rows.length === 0 && <div style={{ color: "var(--ink-400)", padding: "20px" }}>Нет сотрудников по фильтру</div>}
      </div>

      {addOpen && <AddPersonModal depts={depts} onClose={() => setAddOpen(false)} onAdded={() => { setAddOpen(false); load(); if (window.refreshDirectory) window.refreshDirectory(); }} />}
    </div>
  );
}

function AddPersonModal({ depts, onClose, onAdded }) {
  const [name, setName] = React.useState("");
  const [dept, setDept] = React.useState(depts[0] || "");
  const [tg, setTg] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");

  const submit = async () => {
    if (!name.trim() || !window.API) return;
    setBusy(true); setError("");
    try {
      let handle = tg.trim();
      if (handle && !handle.startsWith("@")) handle = "@" + handle;
      await window.API.addPerson({ name: name.trim(), dept, tg: handle });
      onAdded();
    } catch (e) {
      setError(String((e && e.message) || e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="tg-overlay open" style={{ background: "rgba(13,22,32,.5)", display: "grid", placeItems: "center", zIndex: 250 }} onClick={onClose}>
      <div className="card" style={{ width: 460, maxWidth: "92vw", boxShadow: "var(--sh-3)" }} onClick={e => e.stopPropagation()}>
        <div className="card-head">
          <div style={{ flex: 1 }}>
            <h3 className="card-title">Новый сотрудник</h3>
            <p className="card-sub">Добавится в справочник и станет доступен как ответственный</p>
          </div>
          <button className="icon-btn" style={{ color: "var(--ink-400)" }} onClick={onClose}><I.X size={18} /></button>
        </div>
        <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div>
            <label className="fld-label">ФИО</label>
            <input className="fld" style={{ width: "100%" }} placeholder="Иванов И.И." value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <label className="fld-label">Отдел</label>
              <select className="fld" style={{ width: "100%" }} value={dept} onChange={e => setDept(e.target.value)}>
                {depts.map(d => <option key={d} value={d}>{d}</option>)}
              </select>
            </div>
            <div>
              <label className="fld-label">Telegram</label>
              <input className="fld" style={{ width: "100%" }} placeholder="@username" value={tg} onChange={e => setTg(e.target.value)} />
            </div>
          </div>
          {error && <div style={{ color: "var(--err)", fontSize: 12.5 }}>{error}</div>}
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "0 20px 18px" }}>
          <button className="btn btn-ghost" onClick={onClose}>Отмена</button>
          <button className="btn btn-accent" onClick={submit} disabled={busy || !name.trim()}>
            <I.Plus size={14} /> {busy ? "Добавление…" : "Добавить"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.EmployeesPage = EmployeesPage;
