/* TargiApp — panel administratora: dodawanie osób + generowanie kodów PIN */
function AdminPage() {
  const store = useStore();
  const [first, setFirst] = useState("");
  const [last, setLast] = useState("");
  const [isAdmin, setIsAdmin] = useState(false);
  const [justAdded, setJustAdded] = useState(null);
  const [showPins, setShowPins] = useState(false);   // PIN-y domyślnie ukryte
  const [revealed, setRevealed] = useState(new Set()); // pojedyncze podglądy

  function toggleRow(id) {
    setRevealed((prev) => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  }

  function add() {
    if (!first.trim() || !last.trim()) return;
    Promise.resolve(store.addPerson(first, last, isAdmin)).then((p) => {
      if (p) { setJustAdded(p.id); setTimeout(() => setJustAdded(null), 2500); }
    });
    setFirst(""); setLast(""); setIsAdmin(false);
  }

  const people = store.state.people.slice().sort((a, b) => Number(b.isAdmin) - Number(a.isAdmin) || a.lastName.localeCompare(b.lastName));

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="page-title">Użytkownicy</div>
          <div className="page-sub">Dodawaj osoby i zarządzaj kodami PIN do logowania · {store.state.people.length} osób</div>
        </div>
      </div>

      <div className="admin-grid">
        {/* formularz dodawania */}
        <div className="card">
          <div className="card-head">
            <div className="card-title">Dodaj osobę</div>
            <div className="card-sub">Kod PIN zostanie wygenerowany automatycznie</div>
          </div>
          <div className="card-pad" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="field">
              <label>Imię</label>
              <input value={first} placeholder="np. Anna" onChange={(e) => setFirst(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} />
            </div>
            <div className="field">
              <label>Nazwisko</label>
              <input value={last} placeholder="np. Kowalczyk" onChange={(e) => setLast(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} />
            </div>
            <label className="role-opt" style={{ alignSelf: "flex-start", cursor: "pointer", borderColor: isAdmin ? "var(--blue)" : "var(--border)", background: isAdmin ? "var(--blue-bg)" : "var(--surface)" }}>
              <input type="checkbox" checked={isAdmin} onChange={(e) => setIsAdmin(e.target.checked)} style={{ margin: 0 }} />
              Uprawnienia administratora
            </label>
            <button className="btn primary" style={{ justifyContent: "center" }} onClick={add}>Dodaj i wygeneruj PIN</button>
            {justAdded ? (
              <div style={{ fontSize: 12.5, color: "var(--green)", fontWeight: 600 }}>
                ✓ Dodano. PIN: <b className="pin-badge" style={{ fontSize: 12 }}>{store.personById(justAdded).pin}</b>
              </div>
            ) : null}
          </div>
        </div>

        {/* tabela osób */}
        <div className="card" style={{ overflow: "hidden" }}>
          <div className="card-head" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div className="card-title">Lista osób</div>
              <div className="card-sub">Kody PIN są domyślnie ukryte</div>
            </div>
            <button className="btn ghost" onClick={() => { setShowPins((v) => !v); setRevealed(new Set()); }}>
              {showPins ? "\uD83D\uDE48 Ukryj PIN-y" : "\uD83D\uDC41\uFE0F Pokaż PIN-y"}
            </button>
          </div>
          <table className="utable">
            <thead>
              <tr>
                <th>Osoba</th>
                <th>Rola w systemie</th>
                <th>Kod PIN</th>
                <th style={{ textAlign: "right" }}>Akcje</th>
              </tr>
            </thead>
            <tbody>
              {people.map((p) => (
                <tr key={p.id} style={justAdded === p.id ? { background: "#e7f7ef" } : null}>
                  <td>
                    <div className="u-name"><Avatar name={store.fullName(p)} size={30} />{store.fullName(p)}</div>
                  </td>
                  <td>{p.isAdmin ? <span className="tag-admin">Administrator</span> : <span className="tag-user">Pracownik</span>}</td>
                  <td>
                    {(() => {
                      const visible = showPins || revealed.has(p.id);
                      return (
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          <span className="pin-badge">{visible ? p.pin : "\u2022\u2022\u2022\u2022"}</span>
                          {!showPins ? (
                            <button className="icon-act" title={revealed.has(p.id) ? "Ukryj" : "Pokaż PIN"} onClick={() => toggleRow(p.id)}>
                              {revealed.has(p.id) ? "\uD83D\uDE48" : "\uD83D\uDC41\uFE0F"}
                            </button>
                          ) : null}
                        </div>
                      );
                    })()}
                  </td>
                  <td>
                    <div className="row-actions">
                      <button className="icon-act" title="Nowy PIN" onClick={() => store.regeneratePin(p.id)}>🔄</button>
                      <button className="icon-act danger" title="Usuń osobę" onClick={() => { if (confirm("Usunąć " + store.fullName(p) + "? Zniknie też z harmonogramu.")) store.deletePerson(p.id); }}>🗑</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { AdminPage });
