// Equipe — PAC Advogados

const ROLE_LABELS = {
  socio_admin: 'Sócio Administrador',
  socio: 'Sócio',
  advogado: 'Advogado(a)',
  paralegal: 'Paralegal',
  cliente_externo: 'Cliente externo',
};

const TeamMemberCard = ({ member, isSelf, onSaved }) => {
  const [editing, setEditing] = React.useState(false);
  const [form, setForm] = React.useState({
    phone: member.phone || '',
    cpf: member.cpf || '',
    oab: member.oab || '',
    address: member.address || '',
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const onSave = async () => {
    setSaving(true); setError('');
    try {
      await window.PACApi.users.updateProfile(form);
      onSaved({ ...member, ...form });
      setEditing(false);
    } catch (e) {
      setError(e.message || 'Erro ao salvar.');
    } finally {
      setSaving(false);
    }
  };

  const onCancel = () => {
    setForm({ phone: member.phone || '', cpf: member.cpf || '', oab: member.oab || '', address: member.address || '' });
    setEditing(false);
    setError('');
  };

  const initials = member.initials || member.name?.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase() || '?';
  const color = member.color || '#0D0D6B';

  return (
    <div style={{
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 10,
      padding: 24,
      display: 'flex',
      flexDirection: 'column',
      gap: 14,
      position: 'relative',
    }}>
      {/* Avatar + nome */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 52, height: 52, borderRadius: 999,
          background: color, color: '#fff',
          display: 'grid', placeItems: 'center',
          fontWeight: 800, fontSize: 18, letterSpacing: '-.01em',
          flexShrink: 0,
        }}>{initials}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--pac-black)', lineHeight: 1.2, marginBottom: 3 }}>
            {member.name}
            {isSelf && (
              <span style={{ marginLeft: 8, fontSize: 10, fontWeight: 600, background: 'var(--pac-navy)', color: '#fff', borderRadius: 4, padding: '1px 6px', verticalAlign: 'middle' }}>
                Você
              </span>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--pac-navy)', fontWeight: 600 }}>
            {ROLE_LABELS[member.role] || member.role}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 2, wordBreak: 'break-all' }}>
            {member.email}
          </div>
        </div>
      </div>

      {/* Campos de perfil */}
      {editing ? (
        <div style={{ display: 'grid', gap: 10 }}>
          {error && (
            <div style={{ padding: '7px 10px', background: 'rgba(194,37,62,.08)', border: '1px solid rgba(194,37,62,.2)', borderRadius: 5, color: '#C2253E', fontSize: 12 }}>
              {error}
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <div className="field-w">
              <label>Telefone</label>
              <input value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="(00) 00000-0000" />
            </div>
            <div className="field-w">
              <label>CPF</label>
              <input value={form.cpf} onChange={e => set('cpf', e.target.value)} placeholder="000.000.000-00" />
            </div>
            <div className="field-w" style={{ gridColumn: '1 / -1' }}>
              <label>OAB</label>
              <input value={form.oab} onChange={e => set('oab', e.target.value)} placeholder="OAB/SP 000.000" />
            </div>
            <div className="field-w" style={{ gridColumn: '1 / -1' }}>
              <label>Endereço</label>
              <input value={form.address} onChange={e => set('address', e.target.value)} placeholder="Rua, número, cidade" />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn ghost sm" onClick={onCancel}>Cancelar</button>
            <button className="btn sm" onClick={onSave} disabled={saving}>
              {saving ? <><span className="spinner" style={{ width: 12, height: 12, borderWidth: 2, marginRight: 6 }} />Salvando…</> : 'Salvar'}
            </button>
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { label: 'Telefone', value: member.phone },
            { label: 'CPF', value: member.cpf },
            { label: 'OAB', value: member.oab },
            { label: 'Endereço', value: member.address },
          ].map(({ label, value }) => (
            <div key={label} style={{ display: 'flex', gap: 8, fontSize: 12 }}>
              <span style={{ color: 'var(--fg-muted)', minWidth: 64, fontWeight: 600 }}>{label}</span>
              <span style={{ color: value ? 'var(--pac-black)' : 'var(--fg-muted)', fontStyle: value ? 'normal' : 'italic' }}>
                {value || 'Não informado'}
              </span>
            </div>
          ))}
          {isSelf && (
            <button
              className="btn ghost sm"
              style={{ marginTop: 6, alignSelf: 'flex-start' }}
              onClick={() => setEditing(true)}
            >
              <Icon name="edit" size={12} /> Editar meus dados
            </button>
          )}
        </div>
      )}
    </div>
  );
};

// ============================================================
// Team — view principal
// ============================================================
const Team = ({ currentUser }) => {
  const [members, setMembers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    window.PACApi.users.list()
      .then(us => setMembers(us || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const onMemberSaved = (updated) => {
    setMembers(prev => prev.map(m => m.id === updated.id ? updated : m));
  };

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 300, gap: 12, color: 'var(--fg-muted)', fontSize: 13 }}>
      <div className="spinner" /> Carregando equipe…
    </div>
  );

  return (
    <div style={{ padding: '0 2px' }}>
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 22, fontWeight: 800, color: 'var(--pac-black)', marginBottom: 4 }}>PAC Advogados</h1>
        <p style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
          {members.length} membro{members.length !== 1 ? 's' : ''} · Cada pessoa pode editar seus próprios dados
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
        {members.map(m => (
          <TeamMemberCard
            key={m.id}
            member={m}
            isSelf={currentUser?.id === m.id}
            onSaved={onMemberSaved}
          />
        ))}
      </div>

      {members.length === 0 && (
        <div style={{ textAlign: 'center', padding: '60px 24px', color: 'var(--fg-muted)', fontSize: 13 }}>
          Nenhum membro encontrado.
        </div>
      )}
    </div>
  );
};

window.Team = Team;
