/* ── USERS VIEW ─────────────────────────────────────────────────────────── */

function UsersView() {
  const [users, setUsers] = React.useState(() => Store.getUsers());
  const [modal, setModal] = React.useState(null); // null | 'add' | 'edit' | 'delete'
  const [editing, setEditing] = React.useState(null);
  const [form, setForm] = React.useState({ nome: '', email: '', role: 'analista', ativo: true });
  const [pwdModal, setPwdModal] = React.useState(false);
  const [newPwd, setNewPwd] = React.useState('');
  const [pwdConfirm, setPwdConfirm] = React.useState('');
  const [pwdMsg, setPwdMsg] = React.useState('');

  const roles = ['admin','analista','aprovador'];
  const roleLabel = { admin: 'Administrador', analista: 'Analista', aprovador: 'Aprovador' };

  function refresh() { setUsers(Store.getUsers()); }

  function openAdd() {
    setForm({ nome: '', email: '', role: 'analista', ativo: true });
    setEditing(null); setModal('add');
  }
  function openEdit(u) {
    setForm({ nome: u.nome, email: u.email, role: u.role, ativo: u.ativo });
    setEditing(u); setModal('edit');
  }
  function openDelete(u) { setEditing(u); setModal('delete'); }

  function save() {
    if (!form.nome.trim() || !form.email.trim()) return;
    if (editing) {
      Store.updateUser(editing.id, form);
    } else {
      Store.addUser({ ...form });
    }
    refresh(); setModal(null);
  }

  function confirmDelete() {
    Store.deleteUser(editing.id); refresh(); setModal(null);
  }

  async function savePassword() {
    if (!newPwd || newPwd !== pwdConfirm) { setPwdMsg('As senhas não coincidem.'); return; }
    if (newPwd.length < 6) { setPwdMsg('Mínimo 6 caracteres.'); return; }
    try {
      await Store.setPassword(newPwd);
      setPwdModal(false); setNewPwd(''); setPwdConfirm(''); setPwdMsg('');
    } catch (ex) {
      setPwdMsg('Erro ao salvar a senha. Tente novamente.');
    }
  }

  const byRole = (role) => users.filter(u => u.role === role);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
        <div className="section-hd" style={{ marginBottom: 0 }}>
          <h2>Usuários</h2>
          <span className="section-sub">{users.length} cadastrados</span>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary btn-sm" onClick={() => setPwdModal(true)}>Alterar senha do sistema</button>
          <button className="btn btn-primary btn-sm" onClick={openAdd}><Icon.plus /> Novo usuário</button>
        </div>
      </div>

      {roles.map(role => {
        const group = byRole(role);
        if (!group.length) return null;
        return (
          <div className="card" style={{ marginBottom: 16 }} key={role}>
            <div className="card-header">
              <h3 style={{ fontSize: '0.8rem', fontFamily: 'Inter, sans-serif' }}>{roleLabel[role]}s</h3>
              <span style={{ fontSize: '0.7rem', color: 'var(--muted)' }}>{group.length}</span>
            </div>
            {group.map(u => (
              <div className="user-row" key={u.id}>
                <div className="user-avatar" style={{ background: u.role === 'admin' ? 'var(--navy)' : u.role === 'aprovador' ? 'var(--gold)' : 'var(--green)' }}>
                  {initials(u.nome)}
                </div>
                <div>
                  <div className="user-name">{u.nome}</div>
                  <div className="user-email">{u.email}</div>
                </div>
                <span className={`user-role-badge${u.role === 'admin' ? ' admin' : ''}`}>{roleLabel[u.role]}</span>
                {!u.ativo && <span style={{ fontSize: '0.62rem', color: 'var(--muted)', padding: '2px 6px', border: '1px solid var(--rule)', borderRadius: 2 }}>Inativo</span>}
                <div className="user-actions">
                  <button className="btn btn-secondary btn-sm" onClick={() => openEdit(u)}>Editar</button>
                  {u.id !== 1 && <button className="btn btn-danger btn-sm" onClick={() => openDelete(u)}>Remover</button>}
                </div>
              </div>
            ))}
          </div>
        );
      })}

      {/* Add/Edit Modal */}
      <Modal open={modal === 'add' || modal === 'edit'} onClose={() => setModal(null)}
        title={editing ? `Editar · ${editing.nome}` : 'Novo Usuário'}
        footer={<>
          <button className="btn btn-secondary" onClick={() => setModal(null)}>Cancelar</button>
          <button className="btn btn-primary" onClick={save}>Salvar</button>
        </>}
      >
        <div className="form-field">
          <label>Nome completo</label>
          <input value={form.nome} onChange={e => setForm(f => ({...f, nome: e.target.value}))} placeholder="Ex: Camila Souza" />
        </div>
        <div className="form-field">
          <label>E-mail</label>
          <input type="email" value={form.email} onChange={e => setForm(f => ({...f, email: e.target.value}))} placeholder="camila@mirabaud.com.br" />
        </div>
        <div className="form-field">
          <label>Perfil</label>
          <select value={form.role} onChange={e => setForm(f => ({...f, role: e.target.value}))}>
            {roles.map(r => <option key={r} value={r}>{roleLabel[r]}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <input type="checkbox" id="ativo" checked={form.ativo} onChange={e => setForm(f => ({...f, ativo: e.target.checked}))} />
          <label htmlFor="ativo" style={{ fontSize: '0.82rem', cursor: 'pointer' }}>Usuário ativo</label>
        </div>
      </Modal>

      {/* Delete Modal */}
      <Modal open={modal === 'delete'} onClose={() => setModal(null)}
        title="Remover usuário"
        footer={<>
          <button className="btn btn-secondary" onClick={() => setModal(null)}>Cancelar</button>
          <button className="btn btn-danger" onClick={confirmDelete}>Remover</button>
        </>}
      >
        <p style={{ fontSize: '0.85rem' }}>Confirma a remoção de <strong>{editing?.nome}</strong>? Esta ação não pode ser desfeita.</p>
      </Modal>

      {/* Password Modal */}
      <Modal open={pwdModal} onClose={() => { setPwdModal(false); setNewPwd(''); setPwdConfirm(''); setPwdMsg(''); }}
        title="Alterar Senha do Sistema"
        footer={<>
          <button className="btn btn-secondary" onClick={() => setPwdModal(false)}>Cancelar</button>
          <button className="btn btn-primary" onClick={savePassword}>Salvar</button>
        </>}
      >
        <div className="form-field">
          <label>Nova senha</label>
          <input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)} placeholder="Mínimo 6 caracteres" />
        </div>
        <div className="form-field">
          <label>Confirmar senha</label>
          <input type="password" value={pwdConfirm} onChange={e => setPwdConfirm(e.target.value)} placeholder="Repita a senha" />
        </div>
        {pwdMsg && <p style={{ color: 'var(--red)', fontSize: '0.75rem' }}>{pwdMsg}</p>}
        <p style={{ fontSize: '0.72rem', color: 'var(--muted)', marginTop: 8 }}>A senha é armazenada localmente neste navegador, criptografada com SHA-256. Alteração recomendada no primeiro acesso.</p>
      </Modal>
    </div>
  );
}

Object.assign(window, { UsersView });
